Sha256: 32fcd1cb64cc255e8abad4777091cdb7fa3bcb6c18d91731c28cf5a0185c0836

Contents?: true

Size: 1.68 KB

Versions: 15

Compression:

Stored size: 1.68 KB

Contents

# frozen_string_literal: true

module PriceHubble
  module EntityConcern
    module Attributes
      # A separated enum typed attribute helper.
      module Enum
        extend ActiveSupport::Concern

        class_methods do
          # Register a fixed enum attribute.
          #
          # @param name [Symbol, String] the name of the attribute
          # @param values [Array<String, Symbol>] the allowed values
          # @param _args [Hash{Symbol => Mixed}] additional options
          #
          # rubocop:disable Metrics/MethodLength because of the inline
          #   meta method definitions
          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
          # rubocop:enable Metrics/MethodLength
        end
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
pricehubble-1.3.0 lib/price_hubble/entity/concern/attributes/enum.rb
pricehubble-1.2.5 lib/price_hubble/entity/concern/attributes/enum.rb
pricehubble-1.2.4 lib/price_hubble/entity/concern/attributes/enum.rb
pricehubble-1.2.3 lib/price_hubble/entity/concern/attributes/enum.rb
pricehubble-1.2.2 lib/price_hubble/entity/concern/attributes/enum.rb
pricehubble-1.2.1 lib/price_hubble/entity/concern/attributes/enum.rb
pricehubble-1.2.0 lib/price_hubble/entity/concern/attributes/enum.rb
pricehubble-1.1.0 lib/pricehubble/entity/concern/attributes/enum.rb
pricehubble-1.0.0 lib/pricehubble/entity/concern/attributes/enum.rb
pricehubble-0.4.2 lib/pricehubble/entity/concern/attributes/enum.rb
pricehubble-0.4.1 lib/pricehubble/entity/concern/attributes/enum.rb
pricehubble-0.4.0 lib/pricehubble/entity/concern/attributes/enum.rb
pricehubble-0.3.0 lib/pricehubble/entity/concern/attributes/enum.rb
pricehubble-0.2.0 lib/pricehubble/entity/concern/attributes/enum.rb
pricehubble-0.1.0 lib/pricehubble/entity/concern/attributes/enum.rb