Class: UnionValue

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

Class Method Summary collapse

Class Method Details

.new(*values, &block) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/unionvalue.rb', line 2

def self.new(*values, &block)

  Class.new do
    attr_accessor(:type, :data, *values)

    values.each do |value|
        define_singleton_method(value) do |*val|
            a = self.new
            a.data = val.first if val
            a.type = value
            a.freeze
            a
        end

        define_method(:"is_#{value}?") do
            type == value
        end
    end

    const_set :VALUES, values

    def ==(other)
      eql?(other)
    end

    def eql?(other)
      self.class == other.class && self.type == other.type && self.data == other.data
    end

    def inspect
      "#<#{self.class.name} #{self.type}:#{self.data}>"
    end

    class_eval &block if block
  end
end