Module: RubyEnum::ClassMethods

Defined in:
lib/ruby_enum.rb

Instance Method Summary collapse

Instance Method Details

#[](name) ⇒ Object

Returns the enumeration instance with the specified name or nil if none exists.

Returns:

  • the enumeration instance with the specified name or nil if none exists



84
85
86
# File 'lib/ruby_enum.rb', line 84

def [](name)
  _enumeration_values[_normalize(name)]
end

#allArray

Returns all enumeration instances defined in this enumeration class.

Returns:

  • (Array)

    all enumeration instances defined in this enumeration class



89
90
91
# File 'lib/ruby_enum.rb', line 89

def all
  _enumeration_values.map { |_, instance| instance }
end

#const_missing(name) ⇒ Object

enable retrieving enumeration values as constants



61
62
63
# File 'lib/ruby_enum.rb', line 61

def const_missing(name)
  self[name] || super
end

#enum(name, value = nil) ⇒ Object

Raises:

  • (ArgumentError)


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/ruby_enum.rb', line 65

def enum(name, value = nil)
  raise ArgumentError, 'name is required for an enumeration' if name.nil?

  normalized_name = _normalize name
  if self[normalized_name]
    raise ArgumentError, "an enumeration value for #{normalized_name} has " \
      "already been defined in #{self.name}."
  else
    value = normalized_name.to_s unless value
    if find_by_value value
      raise ArgumentError, "duplicate associated value `#{value}` for enumeration" \
        "with name `#{name}`"
    end
    _define_instance_accessor_for normalized_name
    _enumeration_values[normalized_name] = new(normalized_name, value)
  end
end

#find_by_value(value) ⇒ Object

Returns the enumeration instance with the specifed associated value.

Returns:

  • the enumeration instance with the specifed associated value



105
106
107
# File 'lib/ruby_enum.rb', line 105

def find_by_value(value)
  all.find { |instance| instance.value == value }
end

#find_by_value!(value) ⇒ Object

Returns the enumeration instance with the specified associated value.

Returns:

  • the enumeration instance with the specified associated value

Raises:

  • (ArgumentError)

    when no enumeration instance with the associated value is found



95
96
97
98
99
100
101
102
# File 'lib/ruby_enum.rb', line 95

def find_by_value!(value)
  result = find_by_value(value) 
  unless result
    raise ArgumentError, "No enumeration value with associated value #{value} found"
  end

  result
end