classy-adornments
More functional versions of the attr, attr_reader and attr_writer methods. I often find myself repeating these across projects so I’ve extracted them into a gem. Inspired by ‘Chapter 2 - Designing Beautiful APIs’ in the ‘Ruby Best Practices’ book.
Simple adornment
Provides a single method interface to instance variables. Methods calls without an argument return the attribute value. Method calls with an argument set corresponding instance variable to this value.
class Person
include ClassyAdornments
adorn :partner
end
developer = Person.new
developer.partner #=> nil
developer.partner "Sophie"
developer.partner #=> "Sophie"
developer.instance_variable_get("@partner") #=> The instance variable also set
developer.partner = "Sophie" #=> Method variable= also usable
Array adornment
Provides an adornment using an array as a base. Method calls with an argument append the argument to the array. Empty method calls return the array of values.
class Relationship
include ClassyAdornments
adorn :dates, :array => true
adorn :fights, :array => true
end
romance = Relationship.new
romance.dates #=> [] Initialised with empty array
romance.dates(:wings) #=> Value appended to array
romance.dates #=> [:wings]
romance.dates([:drive_thru,:tv_night]) #=> Array values also added
romance.dates #=> [:wings,:drive_thru,:tv_night]
romance.fights :dates, :guy_friend_tim #=> Multi-arguments appended also
romance.fights #=> [:dates, :guy_friend_tim]
Copyright
Copyright © 2011 Michael Barton. See LICENSE.txt for further details.