Class: EnumeratedType::PropertyIndex
- Inherits:
-
Object
- Object
- EnumeratedType::PropertyIndex
- Defined in:
- lib/enumerated_type.rb
Overview
In the unfortunate case where there are thousands of elements in an enumerated type, an iteration based strategy for EnumeratedType.by is slow. Particularly, since declare does .by(:name, name) to detect name collisions, EnumeratedType.declare is O(n^2) where n is the EnumeratedType.count, which can take seconds when the enunm is loaded, which is, like, a total bummer. This class indexes enums by property and value so lookups are constant time. The backing hash would look like this for the Shape enum.
{
:sides => {
4 => Shape::Square
},
:name => {
:square => Shape::Square
}
}
Note that there is only a single value for each property/value combination. #set will respect the first instance of a property/value combination (i.e subsequent duplicate #sets will not override the first value). This matches the definition of EnumeratedType.by.
Instance Method Summary collapse
- #get(property, value, miss) ⇒ Object
- #has_property?(property) ⇒ Boolean
-
#initialize ⇒ PropertyIndex
constructor
A new instance of PropertyIndex.
- #set(property, value, enumerated) ⇒ Object
Constructor Details
#initialize ⇒ PropertyIndex
Returns a new instance of PropertyIndex.
27 28 29 |
# File 'lib/enumerated_type.rb', line 27 def initialize self.by_property = { } end |
Instance Method Details
#get(property, value, miss) ⇒ Object
36 37 38 |
# File 'lib/enumerated_type.rb', line 36 def get(property, value, miss) by_property.fetch(property.to_sym).fetch(value, &miss) end |
#has_property?(property) ⇒ Boolean
40 41 42 |
# File 'lib/enumerated_type.rb', line 40 def has_property?(property) by_property.has_key?(property.to_sym) end |
#set(property, value, enumerated) ⇒ Object
31 32 33 34 |
# File 'lib/enumerated_type.rb', line 31 def set(property, value, enumerated) by_value = (by_property[property.to_sym] ||= { }) by_value[value] ||= enumerated end |