Module: SuperMappedAttr::ClassMethods
- Defined in:
- lib/super_mapped_attr.rb
Instance Method Summary collapse
-
#super_mapped_attr(attr, map, options = {}) ⇒ Object
Makes the attribute mapped by a SuperMap, eg.
Instance Method Details
#super_mapped_attr(attr, map, options = {}) ⇒ Object
Makes the attribute mapped by a SuperMap, eg. class User
super_mapped_attr :kind, SuperMap.new(
[:member, 1, "Casual member", { :min_age => 18.years, :welcome_string => "Welcome member!" }],
[:admin, 2, "Administrator", { :min_age => nil, :welcome_string => "Hello admin!" }]
)
end
u = User.new( :kind => 1 )
u.kind_label # “Casual member”
u.kind_key # :member
u.kind_attr( :member, :min_age ) # 18.years
u.kind_key = :admin
u.kind # 2
User.kinds # #SuperMap:0x.…
User.with_kind( :member, :admin ).count.… (scope)
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/super_mapped_attr.rb', line 35 def super_mapped_attr( attr, map, = {} ) if respond_to?( :validates_inclusion_of ) validates_inclusion_of attr, { :in => map.values }.merge( ) end define_method( "#{attr}_key" ) do map.key(send(attr)) end define_method( "#{attr}_key=" ) do |key| send( "#{attr}=", map.value( key )) end define_method( "#{attr}_label" ) do map.label(send(attr)) end define_method( "#{attr}_attr" ) do |key| map.attribute(send(attr), key) end (class << self; self; end).instance_eval do define_method attr.to_s.pluralize, lambda { map } define_method( "with_#{attr}" ) do |*keys| where( attr => keys.collect { |key| map.value( key ) } ) end end end |