Module: ActsAsEnum::ClassMethods

Defined in:
lib/acts_as_enum.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_enum(attr, options = { :in => [], :prefix => false }) ⇒ Object Also known as: enum_attr



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
# File 'lib/acts_as_enum.rb', line 49

def acts_as_enum(attr, options = { :in => [], :prefix => false })
  attr = attr.to_s
  plural_upcase_attr = attr.pluralize.upcase
  enum = options[:in]

  raise "Can not load Rails." unless defined?(Rails)
  raise "Options :in can not be empty." if enum.blank?
  raise "Options :in must be an object of Array or Hash." unless enum.is_a?(Array) or enum.is_a?(Hash)

  if enum.is_a?(Hash)
    enum = enum.to_a
  elsif enum.is_a?(Array) and enum.first.is_a?(String)
    enum = enum.inject([]) { |arr, obj| arr << [obj] * 2 }
  end

  is_key_value_enum = enum.first.size == 2 ? true : false

  # validates_inclusion_of attr, :in => enum.collect { |arr| arr[1] }, :allow_blank => true

  attr_options = enum.inject({}) do |hash, arr|
    hash[is_key_value_enum ? arr.first : arr[1]] = arr.last.to_s
    hash
  end
  const_set(plural_upcase_attr, attr_options)

  enum.each do |arr|
    enum_name = arr.first.to_s.downcase
    attr_value = is_key_value_enum ? arr.first : arr[1]
    method_name = options[:prefix] ? "#{attr}_#{enum_name}" : enum_name

    const_set("#{method_name}".upcase, attr_value)

    if Rails.version =~ /^4/
      scope method_name.to_sym, -> { where(["#{self.table_name}.#{attr} = ?", attr_value]) }
    elsif Rails.version =~ /^3/
      scope method_name.to_sym, where(["#{self.table_name}.#{attr} = ?", attr_value])
    else
      named_scope method_name.to_sym, :conditions => { attr.to_sym => attr_value }
    end

    class_eval(%Q{
      def #{method_name}?
        # #{attr}.to_s == #{method_name.upcase}
        #{attr}.to_s == "#{attr_value}"
      end
    })
  end

  class_eval(%Q{
    def self.#{attr}_options
      #{plural_upcase_attr}.inject([]){ |arr, obj| arr << obj.reverse }
    end

    def #{attr}_name
      return #{plural_upcase_attr}[#{attr}] if #{attr}.is_a?(FalseClass)
      #{plural_upcase_attr}[#{attr}] unless #{attr}.blank?
    end
  })
end