Module: ActiveRecord::ComposedOfEnum

Defined in:
lib/active_record/composed_of_enum.rb,
lib/active_record/composed_of_enum/version.rb

Constant Summary collapse

VERSION =
'0.0.4'

Instance Method Summary collapse

Instance Method Details

#composed_of_enum(part, options = {}) ⇒ Object



7
8
9
10
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
45
46
47
# File 'lib/active_record/composed_of_enum.rb', line 7

def composed_of_enum(part, options = {})
  unless options.has_key?(:base)
    raise ArgumentError, 'must provide :base option'
  end

  unless options.has_key?(:enumeration)
    raise ArgumentError, 'must provide :enumeration option'
  end

  base = options[:base]
  enum_column = :"#{part}_cd"

  base.class_attribute(enum_column, :instance_accessor => false)

  enumeration = options[:enumeration]

  enumeration.each_with_index do |enum, cd|
    enum.send(:"#{enum_column}=", cd)
  end

  validates(
    enum_column,
    :presence => true,
    :inclusion => 0...enumeration.size
  )

  setter_method_name = :"#{part}="

  if options.has_key?(:default)
    after_initialize do
      send(setter_method_name, options[:default]) unless send(part).present?
    end
  end

  define_method(setter_method_name) { |enum| self[enum_column] = enum.send(enum_column) }

  define_method(part) do
    enum_cd = self[enum_column]
    enum_cd.present? ? enumeration[enum_cd] : nil
  end
end