Module: Arkaan::Concerns::Enumerable::ClassMethods

Defined in:
lib/arkaan/concerns/enumerable.rb

Overview

Submodule holding all the static methods add to the current subclass.

Author:

Instance Method Summary collapse

Instance Method Details

#enum_field(field_name, values, options = {}) ⇒ Object

Creates the field with the given name, set of possible values, and options.

Parameters:

  • field_name (String)

    the name of the enumerated field.

  • values (Array<Symbol>)

    the possible values of the enumerated field.

  • options (Hash<Symbol, Any>) (defaults to: {})

    the possible options for the field.



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
# File 'lib/arkaan/concerns/enumerable.rb', line 16

def enum_field(field_name, values, options = {})
  field :"enum_#{field_name}", type: Symbol, default: options[:default]

  validates :"enum_#{field_name}", inclusion: {in: values.map(&:to_sym), message: 'inclusion'}

  define_method field_name do
    return self["enum_#{field_name}"]
  end

  define_method "#{field_name}=" do |value|
    if values.include? value.to_sym
      self["enum_#{field_name}"] = value.to_sym
    end
  end

  values.map(&:to_sym).each do |value|
    define_method "#{field_name}_#{value}!" do
      self["enum_#{field_name}"] = value
    end

    define_method "#{field_name}_#{value}?" do
      self["enum_#{field_name}"] == value
    end
  end
end