Module: LightEnum::ClassMethods

Defined in:
lib/light_enum.rb

Instance Method Summary collapse

Instance Method Details

#light_enum(*args) ⇒ Object

light_enum :status , [“Open”,“Close”,“ReOpen”]

“Open”,“Close”,“ReOpen”

will be convert to [[“Open“,0],,[”ReOpen“,2]]

:validate * true * use validator if included ActiveModel::Validations. default is false

Raises:

  • (ArgumentError)


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
37
38
39
40
41
42
43
44
# File 'lib/light_enum.rb', line 11

def light_enum(*args)
  options = {:validate => false}
  options.merge!(args.pop) if args.last.is_a?(Hash)
  raise ArgumentError, "You have to supply at least two format like :attr_name,[['China',1],.....]" if args.empty?

  _attr = args.shift
  const, summary = _attr.upcase, args.pop.to_td

  vals = summary.map(&:last)
  if vals.uniq.length != vals.length
    raise ArgumentError, "The last argument of each array must be unique"
  end
  const_value = "#{const}_VALUES"

  [[const,summary],[const_value,summary.map(&:last)]].each do |name,val|
    silence_warnings {const_set(name,val)} if !const_defined?(name) || val != const_get(name)
  end

  if respond_to?(:validates) && options[:validate]
    validates_presence_of   _attr.to_sym  , :if => proc { respond_to?(:columns_hash) && self.columns_hash[_attr.to_s].type == :boolean }
    validates_inclusion_of  _attr.to_sym  , :in => const_get(const_value)
  end

  define_method("#{_attr}_name") do
    raise NoMethodError,"Not defined #{_attr}" if !respond_to?("#{_attr}")
    if ary = summary.rassoc(send(_attr))
      ary.__send__(:first)
    end
  end

  summary.each do |name,target|
    define_method("#{_attr}_#{target.to_s.downcase}?") { __send__(_attr) == target }
  end
end