Class: Enumy::Enum

Inherits:
Object
  • Object
show all
Defined in:
lib/enumy/enum.rb

Direct Known Subclasses

Rails::Enum

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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

#keyObject (readonly)

Returns the value of attribute key.



6
7
8
# File 'lib/enumy/enum.rb', line 6

def key
  @key
end

Class Method Details

.allObject



38
39
40
# File 'lib/enumy/enum.rb', line 38

def all
  instances.values
end

.define(enum) ⇒ Object

Raises:

  • (ArgumentError)


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

Raises:

  • (ArgumentError)


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

#inspectObject



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_sObject



13
14
15
# File 'lib/enumy/enum.rb', line 13

def to_s
  key.to_s
end