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

Each attribute you map generates an options method, suitable for use in form helpers. If you define an attribute status, instances of your model will have a status_options method (on the class and any instances) that returns a sorted array of arrays containing humanized-option-name/value pairs. By default this array is sorted by the option name (closed/open/etc.) If you’d rather sort by value, pass false to the options method. This method also will set the selected option for records where the attribute is already set.

Examples:

Define a Ticket model with a status column:

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.

  • :predicate_methods (Object)

    Generate methods for checking whether an object has a certain attribute set



45
46
47
48
49
50
51
52
53
# File 'lib/attribute_mapper.rb', line 45

def map_attribute(attribute, options)
  mapping = build_mapping(options)
  verify_existence_of attribute
  add_accessor_for    attribute, mapping
  add_predicates_for  attribute, mapping.keys if options.fetch(:predicate_methods) { true }
  override            attribute
  add_options_helper_for attribute, mapping
  add_options_helper_to_class attribute, self
end