Module: PriceHubble::EntityConcern::Attributes::Enum

Extended by:
ActiveSupport::Concern
Included in:
PriceHubble::EntityConcern::Attributes
Defined in:
lib/price_hubble/entity/concern/attributes/enum.rb

Overview

A separated enum typed attribute helper.

Class Method Summary collapse

Class Method Details

.typed_attr_enum(name, values:, **_args) ⇒ Object

Register a fixed enum attribute.

rubocop:disable Metrics/MethodLength because of the inline

meta method definitions

Parameters:

  • name (Symbol, String)

    the name of the attribute

  • values (Array<String, Symbol>)

    the allowed values

  • _args (Hash{Symbol => Mixed})

    additional options



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
48
49
50
51
# File 'lib/price_hubble/entity/concern/attributes/enum.rb', line 19

def typed_attr_enum(name, values:, **_args)
  values = values.map(&:to_sym)
  const_values = "ATTR_#{name.to_s.upcase}"

  class_eval <<-RUBY, __FILE__, __LINE__ + 1
    # Define the constant for all valid values
    #{const_values} = #{values}.freeze

    def #{name}=(value)
      #{name}_will_change!
      value = value.to_sym

      unless #{const_values}.include? value
        raise ArgumentError, "'\#{value}' is not a valid #{name} " \
          "(values: \#{#{const_values}})"
      end

      @#{name} = value
    end
  RUBY

  values.each do |value|
    class_eval <<-RUBY, __FILE__, __LINE__ + 1
      def #{value}!
        self.#{name} = :#{value}
      end

      def #{value}?
        self.#{name} == :#{value}
      end
    RUBY
  end
end