Module: RubyEnum::ClassMethods
- Defined in:
- lib/ruby_enum.rb
Instance Method Summary collapse
-
#[](name) ⇒ Object
The enumeration instance with the specified name or nil if none exists.
-
#all ⇒ Array
All enumeration instances defined in this enumeration class.
-
#const_missing(name) ⇒ Object
enable retrieving enumeration values as constants.
- #enum(name, value = nil) ⇒ Object
-
#find_by_value(value) ⇒ Object
The enumeration instance with the specifed associated value.
-
#find_by_value!(value) ⇒ Object
The enumeration instance with the specified associated value.
Instance Method Details
#[](name) ⇒ Object
Returns the enumeration instance with the specified name or nil if none exists.
87 88 89 |
# File 'lib/ruby_enum.rb', line 87 def [](name) _enumeration_values[_normalize(name)] end |
#all ⇒ Array
Returns all enumeration instances defined in this enumeration class.
92 93 94 |
# File 'lib/ruby_enum.rb', line 92 def all _enumeration_values.map { |_, instance| instance } end |
#const_missing(name) ⇒ Object
enable retrieving enumeration values as constants
64 65 66 |
# File 'lib/ruby_enum.rb', line 64 def const_missing(name) self[name] || super end |
#enum(name, value = nil) ⇒ Object
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/ruby_enum.rb', line 68 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.
108 109 110 |
# File 'lib/ruby_enum.rb', line 108 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.
98 99 100 101 102 103 104 105 |
# File 'lib/ruby_enum.rb', line 98 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 |