Class: Renum::EnumeratedValue

Inherits:
Object
  • Object
show all
Extended by:
Enumerable, Forwardable
Includes:
Comparable
Defined in:
lib/renum/enumerated_value.rb

Overview

This is the superclass of your enumeration classes. The class methods defined here are intended to be called on your enumerated value classes. An enumeration class is Enumerable over its values and exposes them by numeric index via []. Values are also comparable, sorting into the order in which they’re declared.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ EnumeratedValue

You should never directly new-up an EnumeratedValue, so this is basically internal. It sets up the value with its class, so if you override, be sure to call super! Better yet define init as shown in the README.



46
47
48
49
50
# File 'lib/renum/enumerated_value.rb', line 46

def initialize name
  @name = name.to_s.freeze
  @index = self.class.values.size
  self.class.values << self
end

Instance Attribute Details

#indexObject (readonly)

Returns the value of attribute index.



41
42
43
# File 'lib/renum/enumerated_value.rb', line 41

def index
  @index
end

#nameObject (readonly)

Returns the value of attribute name.



41
42
43
# File 'lib/renum/enumerated_value.rb', line 41

def name
  @name
end

Class Method Details

.valuesArray

Returns values of this type in the order they’re declared.

Returns:

  • (Array)

    values of this type in the order they’re declared.



18
19
20
# File 'lib/renum/enumerated_value.rb', line 18

def values
  @values ||= []
end

.values_by_name{String => EnumeratedType}

Returns values keyed by name.

Returns:

  • ({String => EnumeratedType})

    values keyed by name.



30
31
32
33
34
35
# File 'lib/renum/enumerated_value.rb', line 30

def values_by_name
  @values_by_name ||= values.inject({}) do |memo, value|
    memo[value.name] = value
    memo
  end.freeze
end

.with_name(name) ⇒ EnumeratedValue?

Lookup by name.

Parameters:

  • name (String)

    of the value you want

Returns:

  • (EnumeratedValue, nil)

    the value with ‘name` or nil if there is no value by that name



25
26
27
# File 'lib/renum/enumerated_value.rb', line 25

def with_name name
  values_by_name[name]
end

Instance Method Details

#<=>(other) ⇒ Object

Sorts enumerated values into the order in which they’re declared.



60
61
62
# File 'lib/renum/enumerated_value.rb', line 60

def <=> other
  index <=> other.index
end

#==(other) ⇒ Object



64
65
66
# File 'lib/renum/enumerated_value.rb', line 64

def == other
  equal? other
end

#to_sObject

Returns the fully qualified name of the constant referring to this value. Don’t override this if you’re using Renum with the constantize_attribute plugin, which relies on this behavior.



55
56
57
# File 'lib/renum/enumerated_value.rb', line 55

def to_s
  "#{self.class}::#{name}"
end