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)


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

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
# File 'lib/minfraud/enum.rb', line 17

def mapping
  @mapping ||= {}
end