Method: EnumTable::Record::ClassMethods#enum_map

Defined in:
lib/enum_table/record.rb

#enum_map(name, options) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/enum_table/record.rb', line 54

def enum_map(name, options)
  case (table = options[:table])
  when Hash
    table
  when Array
    map = {}
    table.each_with_index { |element, i| map[element] = i + 1 }
    map
  else
    map = {}
    table_name = table || "#{self.table_name.singularize}_#{name.to_s.pluralize}"
    return {} if EnumTable.missing_tables_allowed? && !connection.tables.include?(table_name)
    connection.execute("SELECT id, value FROM #{connection.quote_table_name table_name}").each do |row|
      map[row[1]] = row[0]
    end
    map
  end
end