Module: SymbolizedEnum::ClassMethods

Defined in:
lib/symbolized_enum.rb

Constant Summary collapse

NO_DEFAULT_PROVIDED =

:nodoc:

Object.new

Instance Method Summary collapse

Instance Method Details

#symbolized_enum(attr_name, predicates: false, prefixed_predicate: false, suffixed_predicate: false, predicate_name_generator: nil, default: NO_DEFAULT_PROVIDED, **validates_inclusion_of_options) ⇒ Object

Parameters:

  • attr_name (String, Symbol)

    Activerecord attribute to treat as a symbol

  • kwargs (Boolean)

    :predicates (false) Generate boolean methods for each enum value. This must be true for any of the other predicate options to take effect

  • kwargs (Boolean)

    :prefixed_predicate (false) Generate boolean methods for each enum value prefixed with the name of the attribute

  • kwargs (Boolean)

    :suffixed_predicate (false) Generate boolean methods for each enum value suffixed with the name of the attribute

  • kwargs (Proc, nil)

    :predicate_name_generator (nil) Generate boolean methods for each enum value by calling the proc with attribute name and enum value

  • kwargs (Object, nil)

    :default This value is passed to the activerecord attribute default option

  • **validates_inclusion_of_options (Hash)

    Any options accepted by activerecord’s validates_inclusion_of



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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/symbolized_enum.rb', line 25

def symbolized_enum(attr_name, predicates: false,
                    prefixed_predicate: false,
                    suffixed_predicate: false,
                    predicate_name_generator: nil,
                    default: NO_DEFAULT_PROVIDED,
                    **validates_inclusion_of_options)
  if default == NO_DEFAULT_PROVIDED
    attribute(attr_name, :symbol)
  else
    attribute(attr_name, :symbol, default: default)
  end

  validates_inclusion_of(attr_name, validates_inclusion_of_options)

  return unless predicates

  enum_values = validates_inclusion_of_options[:in]
  if prefixed_predicate
    enum_values.each do |enum_value|
      define_method("#{attr_name}_#{enum_value}?") do
        send(attr_name) == enum_value
      end
    end
  elsif suffixed_predicate
    enum_values.each do |enum_value|
      define_method("#{enum_value}_#{attr_name}?") do
        send(attr_name) == enum_value
      end
    end
  elsif predicate_name_generator
    enum_values.each do |enum_value|
      define_method(predicate_name_generator.call(attr_name, enum_value)) do
        send(attr_name) == enum_value
      end
    end
  else
    enum_values.each do |enum_value|
      define_method("#{enum_value}?") do
        send(attr_name) == enum_value
      end
    end
  end
end