Module: Inum::ActiveRecordMixin

Defined in:
lib/inum/active_record_mixin.rb

Overview

Mixin module to ActiveRecord.

Examples:

class Fruit < ActiveRecord::Base
  bind_enum :type, FruitType
end

Instance Method Summary collapse

Instance Method Details

#bind_inum(column, enum_class, options = {}) ⇒ Object

Define compare method in class.

Parameters:

  • column (Symbol)

    Binding column name.

  • enum_class (Inum::Base)

    Binding Enum.

  • options (Hash) (defaults to: {})

    option

Options Hash (options):

  • :prefix (Symbol)

    Prefix. (default: column)



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
# File 'lib/inum/active_record_mixin.rb', line 16

def bind_inum(column, enum_class, options = {})
  options = { prefix: column }.merge(options)
  options[:prefix] = options[:prefix] ? "#{options[:prefix]}_" : ''

  self.class_eval do
    define_method(column) do
      enum_class.parse(read_attribute(column))
    end

    define_method("#{column}=") do |value|
      enum_class.parse(value).tap do |enum|
        if enum
          write_attribute(column, enum.to_i)
        else
          write_attribute(column, nil)
        end
      end
    end

    enum_class.each do |enum|
      define_method("#{options[:prefix]}#{enum.to_s.underscore}?") do
        enum.eql?(read_attribute(column))
      end
    end
  end
end