Module: Enumerate::Model

Defined in:
lib/enumerate/model.rb

Instance Method Summary collapse

Instance Method Details

#enumerate(attribute, vals = {}, opts = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
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
# File 'lib/enumerate/model.rb', line 3

def enumerate(attribute, vals={}, opts={})

  validates_inclusion_of attribute, :in => vals, :allow_nil => !!opts[:allow_nil]
  
  
  # Get the column type of the attribute. We support int and string
	  if self.columns_hash[attribute.to_s].nil?
    raise "Column '#{attribute}' does not exist in #{self.class.name}"
  else
    col_type = self.columns_hash[attribute.to_s].type
	  end
  
  const_hash_name = attribute.to_s.pluralize.upcase

  if col_type == :string
    vals = Hash[vals.zip vals.map{ |s| s.to_s }] if vals.kind_of?(Array)
  elsif col_type == :integer
    # Converts an array into a hash of values with indicies as the "values"
    vals = Hash[vals.zip (0...vals.size)] if vals.kind_of?(Array)
  else
    raise "Unsupported column type for enumeration :#{attribute} in #{self.class}!"
  end
  
  # Ensure that only arrays and hashes are appropriate datatypes.
  raise "Unsupported values datatype for enumeration :#{attribute} in #{self.class}!" if !vals.kind_of?(Hash)
  
  # Sets a class costant with the enumerated values
  const_set(const_hash_name, vals)
  
  setup_accessors(const_hash_name, attribute)

  setup_predicates(vals, attribute)

end