Class: Object

Inherits:
BasicObject
Defined in:
lib/enum_plus.rb

Class Method Summary collapse

Class Method Details

.enum(name, enumeration) ⇒ Object



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
45
46
47
48
49
50
51
52
53
# File 'lib/enum_plus.rb', line 16

def self.enum name, enumeration
  name = name.to_s
  class_eval "
    attr_accessor :#{name}
    def self.#{name}_values
      #{enumeration}
    end
    def self.#{name}_captions
      #{enumeration}.map do |value|
        humanize_#{name} value
      end
    end"
  enumeration.each do |value|
    value = value.to_s
    eval "
      def #{value}?
        self.#{name} == '#{value}'
      end
      def #{value}!
        self.#{name} = '#{value}'
      end"
  end
  eval "
    def humanize_#{name} value
      value = value.to_s
      begin
        Required::Module::const_get 'I18n'
        ::I18n.t \"enum.#{self.to_s.underscore}.#{name}.#{'#{value}'}\"
      rescue NameError
        value
      end
    end
    def #{name}_caption
      self.#{name}.nil? ? self.#{name} : humanize_#{name}(self.#{name})
    end"

  # validates_inclusion_of name.to_sym, { allow_nil: true, in: enumeration } if self.ancestors.include? 'ActiveRecord::Base'
end