Class: Enum
- Inherits:
-
Object
- Object
- Enum
- Extended by:
- Enumerable, Forwardable
- Includes:
- Comparable
- Defined in:
- lib/enum.rb
Overview
An Enum is a class with a predefinite set of instances. Instances have an implicit ordering (dependent on the order of definition), can be retrieved by key and be enumerated.
Defined Under Namespace
Classes: DuplicateEnumKey
Instance Attribute Summary collapse
-
#key ⇒ Symbol
(also: #to_sym)
readonly
The key of this value in the enumeration.
-
#ord ⇒ Integer
readonly
Relative ordering index of the instance.
Class Method Summary collapse
Instance Method Summary collapse
-
#<=>(other) ⇒ Object
Objects are compared based on their implicit ordering (order of definition).
-
#==(other) ⇒ Boolean
(also: #eql?)
Tests the objects for equality.
- #hash ⇒ Object
-
#inspect ⇒ String
Returns a representation of this instance (e.g. ‘EnumName::VALUE_1`).
Instance Attribute Details
#key ⇒ Symbol (readonly) Also known as: to_sym
The key of this value in the enumeration
115 116 117 |
# File 'lib/enum.rb', line 115 def key @key end |
#ord ⇒ Integer (readonly)
Relative ordering index of the instance
119 120 121 |
# File 'lib/enum.rb', line 119 def ord @ord end |
Class Method Details
.const_missing(sym) ⇒ Object
191 192 193 194 195 |
# File 'lib/enum.rb', line 191 def const_missing(sym) self.for(sym) rescue super end |
.create(*keys) ⇒ Class
179 180 181 182 183 |
# File 'lib/enum.rb', line 179 def create(*keys) Class.new(self).tap do |enum| keys.each { |key| enum.value(key) } end end |
.for(value) ⇒ self Also known as: []
172 173 174 175 176 |
# File 'lib/enum.rb', line 172 def for(value) return value if value.is_a? self.class enum_key = value&.upcase&.to_sym values.find(proc { raise KeyError, "Enumerated value not found: #{value.inspect}" }) { |v| v.key == enum_key } end |
.inspect ⇒ Object
187 188 189 |
# File 'lib/enum.rb', line 187 def inspect "#{name || 'Enum'}(#{values.map(&:to_s).join(', ')})" end |
Instance Method Details
#<=>(other) ⇒ Object
Objects are compared based on their implicit ordering (order of definition).
152 153 154 155 |
# File 'lib/enum.rb', line 152 def <=>(other) other = self.class.for(other) if other.is_a?(Symbol) || other.is_a?(String) ord <=> other.ord end |
#==(other) ⇒ Boolean Also known as: eql?
Tests the objects for equality. Two enum values are considered equal if they have the same key and belong to the same enumeration.
140 141 142 143 144 |
# File 'lib/enum.rb', line 140 def ==(other) return false if other.nil? other = self.class.for(other) if other.is_a?(Symbol) || other.is_a?(String) instance_of?(other.class) && key == other.key end |
#hash ⇒ Object
130 131 132 |
# File 'lib/enum.rb', line 130 def hash key.to_s.hash end |
#inspect ⇒ String
Returns a representation of this instance (e.g. ‘EnumName::VALUE_1`)
123 124 125 |
# File 'lib/enum.rb', line 123 def inspect "#{self.class.name || 'Enum'}::#{key}" end |