Class: Enumy::Enum
- Inherits:
-
Object
- Object
- Enumy::Enum
- Defined in:
- lib/enumy/enum.rb
Direct Known Subclasses
Instance Attribute Summary collapse
-
#key ⇒ Object
readonly
Returns the value of attribute key.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(key) ⇒ Enum
constructor
A new instance of Enum.
- #inspect ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(key) ⇒ Enum
Returns a new instance of Enum.
8 9 10 11 |
# File 'lib/enumy/enum.rb', line 8 def initialize(key) raise Errors::KeyMissingError.new(self) if key.nil? @key = key.to_sym end |
Instance Attribute Details
#key ⇒ Object (readonly)
Returns the value of attribute key.
6 7 8 |
# File 'lib/enumy/enum.rb', line 6 def key @key end |
Class Method Details
.all ⇒ Object
38 39 40 |
# File 'lib/enumy/enum.rb', line 38 def all instances.values end |
.define(enum) ⇒ Object
28 29 30 31 32 33 34 35 36 |
# File 'lib/enumy/enum.rb', line 28 def define(enum) raise ArgumentError, "Expected an object of type `Enumy::Enum`, got #{enum.class.name}" unless enum.is_a?(Enumy::Enum) if instances[enum.key] raise Errors::DuplicateEnumInstanceError, "Enum `#{enum.key.to_s.upcase}` is using a duplicate key `#{enum.key}` for Enum '#{enum.class.name}'." else instances[enum.key] = enum end end |
.find(key) ⇒ Object
42 43 44 |
# File 'lib/enumy/enum.rb', line 42 def find(key) find_by(key: key.to_sym) || raise(Errors::EnumNotFoundError.new("Could not find a `#{self.name}` enum with a `key` of #{key}")) end |
.find_by(**args) ⇒ Object
46 47 48 49 50 51 52 53 54 |
# File 'lib/enumy/enum.rb', line 46 def find_by(**args) raise ArgumentError, "`find_by` requires at least one key-value pair" if args.empty? instances.values.find do |instance| args.all? do |attr, value| instance.send(attr) == value end end end |
Instance Method Details
#inspect ⇒ Object
17 18 19 20 21 22 23 24 |
# File 'lib/enumy/enum.rb', line 17 def inspect attributes = instance_variables.map do |name| value = instance_variable_get(name) "#{name}: #{value.inspect}" end "#<#{self.class.name} #{attributes.join(', ')}>" end |
#to_s ⇒ Object
13 14 15 |
# File 'lib/enumy/enum.rb', line 13 def to_s key.to_s end |