Module: SuperListActiveRecord::ClassMethods

Defined in:
lib/super_list.rb

Instance Method Summary collapse

Instance Method Details

#super_list(column, data, options = {}) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/super_list.rb', line 77

def super_list(column, data, options={})
  original_column = "original_#{column}".to_sym
  data = SuperList[data]
  options = data.options.merge(options)

  before_validation do
    value = attributes[column.to_s]
    keys = data.keys

    if !keys.include?(value)
      index = data.values.find_index(value)

      if index
        self.send("#{column}=", keys[index])
      elsif !options[:no_validation]
        self.errors.add(column, I18n.t('errors.messages.inclusion'))
        return false
      end
    end
  end

  define_method "#{column}" do |*opt|
    opt = opt[0].is_a?(Hash) ? opt[0] : {}
    opt = options.merge(opt)

    data.get_value(attributes[column.to_s], opt)
  end

  define_method original_column do
    attributes[column.to_s]
  end
end