Module: EnumRecords::ActiveRecord::ClassMethods

Defined in:
lib/enum_records.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_enum(enum_column_name = 'enum_key') ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/enum_records.rb', line 12

def acts_as_enum(enum_column_name = 'enum_key')
  self.class_eval do
    # first cehck for enum column name existance
    raise ArgumentError, "Enum column #{enum_column_name} doesn't exsist in the table" unless self.columns_hash.keys.include?(enum_column_name)

    # stores all the names for named records (and their optoins) that are defined in the model.
    self.class_attribute :_enums
    self._enums = {
      :definitions => {},
      :column_name => enum_column_name
    }

    #define class methods
    def self.define_enums *args, &block
      self._enums[:globalized] = self.respond_to?(:translations_table_name)
      EnumRecords::Definer.new self, &block
    end

    def self.enums
      self.where(self._enums[:column_name].to_sym => self._enums[:definitions].keys)
    end

    def self.enum(key)
      self.send "find_by_#{self._enums[:column_name]}", key
    end

  end
end