Sha256: 684a5b063ce2ba61184b36587a5926265e2008b2e8130980e00e47ef8dc6e82e
Contents?: true
Size: 1.36 KB
Versions: 2
Compression:
Stored size: 1.36 KB
Contents
module ActiveEnum module ActsAsEnum module MacroMethods def acts_as_enum(options={}) extend ClassMethods class_inheritable_accessor :active_enum_options self.active_enum_options = options.reverse_merge(:name_column => 'name') scope :enum_values, select("#{primary_key}, #{active_enum_options[:name_column]}"). where(active_enum_options[:conditions]). order("#{primary_key} #{active_enum_options[:order]}") end end module ClassMethods def ids enum_values.map {|v| v.id } end def names enum_values.map {|v| v.send(active_enum_options[:name_column]) } end def to_select enum_values.map {|v| [v.send(active_enum_options[:name_column]), v.id] } end def [](index) if index.is_a?(Fixnum) v = lookup_by_id(index) v.send(active_enum_options[:name_column]) unless v.blank? else v = lookup_by_name(index) v.id unless v.blank? end end private def lookup_by_id(index) enum_values.find_by_id(index) end def lookup_by_name(index) enum_values.where("#{active_enum_options[:name_column]} like ?", index.to_s).first end end end end ActiveRecord::Base.extend ActiveEnum::ActsAsEnum::MacroMethods
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
active_enum-0.9.3 | lib/active_enum/acts_as_enum.rb |
active_enum-0.9.1 | lib/active_enum/acts_as_enum.rb |