Class: SwifterEnum::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/swifter_enum/base.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Base



45
46
47
# File 'lib/swifter_enum/base.rb', line 45

def initialize(value)
  @value = value&.to_sym
end

Class Attribute Details

.valuesObject

Returns the value of attribute values.



4
5
6
# File 'lib/swifter_enum/base.rb', line 4

def values
  @values
end

Instance Attribute Details

#valueObject

Returns the value of attribute value.



43
44
45
# File 'lib/swifter_enum/base.rb', line 43

def value
  @value
end

Class Method Details

.[](key) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/swifter_enum/base.rb', line 22

def [](key)
  unless key.is_a?(Symbol)
    raise ArgumentError, "Enum key must be a Symbol, got #{key.class}"
  end

  unless @values.key?(key)
    raise ArgumentError, "Unknown enum value: :#{key}. Valid values are: #{@values.keys.map { |k| ":#{k}" }.join(", ")}"
  end

  new(key)
end

.allObject



69
70
71
# File 'lib/swifter_enum/base.rb', line 69

def self.all
  values.keys.map { |value| new(value) }
end

.all_casesObject



18
19
20
# File 'lib/swifter_enum/base.rb', line 18

def all_cases
  @values.keys.map { |key| new(key) }
end

.set_values(input) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/swifter_enum/base.rb', line 6

def set_values(input)
  case input
  when Hash
    @values = input.freeze
  when Array
    validate_array_elements!(input)
    @values = input.map { |item| [item.to_sym, item.to_s] }.to_h.freeze
  else
    raise ArgumentError, "Input must be a Hash or an Array of symbols or strings"
  end
end

Instance Method Details

#==(other) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/swifter_enum/base.rb', line 49

def ==(other)
  if other.is_a?(Symbol) || other.is_a?(String)
    value.to_s == other.to_s
  else
    other.instance_of?(self.class) && value == other.value
  end
end

#in?(collection) ⇒ Boolean



57
58
59
# File 'lib/swifter_enum/base.rb', line 57

def in?(collection)
  collection.any? { |item| self == item }
end

#tObject



61
62
63
# File 'lib/swifter_enum/base.rb', line 61

def t
  I18n.t("swifter_enum.#{self.class.name.demodulize.underscore}.#{value}")
end

#to_sObject



65
66
67
# File 'lib/swifter_enum/base.rb', line 65

def to_s
  value.to_s
end