Module: Minfraud::Enum::ClassMethods

Defined in:
lib/minfraud/enum.rb

Overview

ClassMethods provides helpers for working with attributes with enumerated types.

Instance Method Summary collapse

Instance Method Details

#enum_accessor(attribute, assignable_values) ⇒ nil

Create a set of methods for enum-like behavior of the attribute.

Parameters:

  • attribute (Symbol)

    The attribute name.

  • assignable_values (Array)

    The set of permitted values.

Returns:

  • (nil)


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/minfraud/enum.rb', line 31

def enum_accessor(attribute, assignable_values)
  mapping[attribute] = assignable_values.map(&:intern)

  self.class.instance_eval do
    define_method("#{attribute}_values") { mapping[attribute] }
  end

  class_eval do
    define_method(attribute.to_s) { instance_variable_get("@#{attribute}") }
    define_method "#{attribute}=" do |value|
      raise NotEnumValueError, 'Value is not permitted' if value && !self.class.mapping[attribute].include?(value.intern)

      instance_variable_set("@#{attribute}", value ? value.intern : nil)
    end
  end

  nil
end

#mappingHash

Returns a hash in the following format: attribute_name => permitted_values

Returns:

  • (Hash)


17
18
19
20
21
22
# File 'lib/minfraud/enum.rb', line 17

def mapping
  # rubocop:disable ThreadSafety/ClassInstanceVariable
  # This is a false positive - this is set during class definition and then only read
  @mapping ||= {}
  # rubocop:enable ThreadSafety/ClassInstanceVariable
end