Module: AttributeMapper::ClassMethods

Defined in:
lib/attribute_mapper.rb

Instance Method Summary collapse

Instance Method Details

#map_attribute(attribute, options) ⇒ Object

Map a column in your table to a human-friendly attribute on your model. When ++attribute is accessed, it will return the key from the mapping hash. When the attribute is updated, the value from the mapping hash is written to the database.

A class method is also added providing access to the mapping hash, i.e. defining an attribute status will add a statuses class method that returns the hash passed to the :to option.

Predicates are also added to each object for each attribute. If you have a key open in your mapping, your objects will have an ++open?++ method that returns true if the attribute value is :open

Examples:

Define a Ticket model with a status column that maps to open or closed

map_attribute :status, :to => {:open => 1, :closed => 2}

Parameters:

  • attribute (String)

    the column to map on

  • options (Hash)

    the options for this attribute

Options Hash (options):

  • :to (Hash)

    The enumeration to use for this attribute. See example above.



30
31
32
33
34
35
36
# File 'lib/attribute_mapper.rb', line 30

def map_attribute(attribute, options)
  mapping = options[:to]
  verify_existence_of attribute
  add_accessor_for    attribute, mapping
  add_predicates_for  attribute, mapping.keys
  override            attribute
end