Module: Rstructural::Enum

Defined in:
lib/rstructural/enum.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(klass) ⇒ Object



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

def self.extended(klass)
  klass.class_variable_set(:@@enum_values, [])
  klass.class_variable_set(:@@enum_super_class, klass)
end

Instance Method Details

#enum(value, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/rstructural/enum.rb', line 11

def enum(value, &block)
  if (type = of(value))
    raise ArgumentError, "Enum '#{value}' already defined in #{type.name}"
  end
  Rstructural::Struct.new(:value, __caller: caller, &block).new(value).tap do |k|
    self.class_variable_get(:@@enum_values) << k
    k.class.include(self.class_variable_get(:@@enum_super_class))
    def k.name
      self.class.name
    end
  end
end

#interface(&block) ⇒ Object



28
29
30
31
32
# File 'lib/rstructural/enum.rb', line 28

def interface(&block)
  self.class_variable_get(:@@enum_values).each do |t|
    t.class.class_eval(&block)
  end
end

#of(value) ⇒ Object



24
25
26
# File 'lib/rstructural/enum.rb', line 24

def of(value)
  self.class_variable_get(:@@enum_values).find { |v| v.value == value }
end