Module: SuperListActiveRecord::ClassMethods

Defined in:
lib/super_list.rb

Instance Method Summary collapse

Instance Method Details

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



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
109
110
111
112
113
114
# File 'lib/super_list.rb', line 82

def super_list(column, data, options={})
  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[:allow_blank] && value.blank?
        # do nothing
      elsif !options[:no_validation]
        self.errors.add(column, I18n.t('errors.messages.inclusion'))
        return false
      end
    end
    return true
  end

  define_method "#{column}" do |*opts|
    key = attributes[column.to_s]
    if opts.blank? && SuperList.options[:format].blank?
      key
    else
      format = opts[0].is_a?(Symbol) ? opts[0] : nil
      opts   = opts[1].is_a?(Hash) ? opts[1] : (opts[0].is_a?(Hash) ? opts[0] : {})
      data.get_value(key, format, options.merge(opts))
    end
  end
end