Class: ADT::Constructor

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent, name, parameters, &block) ⇒ Constructor

Returns a new instance of Constructor.



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
# File 'lib/adt/constructor.rb', line 5

def initialize(parent, name, parameters, &block)
  @name = name
  @klass = Class.new(parent, &block)
  keys = parameters.keys
  types = parameters.values
  @klass.class_eval """
    attr_reader #{keys.map { |n| ":#{n}" }.join(', ')}

    def initialize(#{keys.join(", ")})
      arg_types = [#{keys.join(", ")}].map(&:class)
      unless arg_types.zip([#{types.join(", ")}]).all? { |arg_type, type| arg_type <= type }
        raise TypeError, 'Types mismatch: given ' + arg_types.join(', ') + ', expected #{types.join(", ")}'
      end
      #{keys.empty? ? "" : keys.map{ |n| "@#{n}" }.join(',') + " = " + keys.join(", ")}
    end

    def ==(other)
      other.is_a?(self.class) && #{keys.empty? ? "true" : keys.map { |key| "#{key} == other.#{key}"}.join(" && ")}
    end

    def to_s
      self.class.name.split('::').last + '(' + instance_variables.map { |i| i.to_s[1..-1] + ': ' + instance_variable_get(i).inspect }.join(', ') + ')'
    end
    alias inspect to_s
  "
  @parameters = parameters
  @others = []
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



3
4
5
# File 'lib/adt/constructor.rb', line 3

def klass
  @klass
end

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/adt/constructor.rb', line 3

def name
  @name
end

#othersObject (readonly)

Returns the value of attribute others.



3
4
5
# File 'lib/adt/constructor.rb', line 3

def others
  @others
end

Instance Method Details

#inspectObject



38
39
40
# File 'lib/adt/constructor.rb', line 38

def inspect
  to_s
end

#to_sObject



34
35
36
# File 'lib/adt/constructor.rb', line 34

def to_s
  "#{@name}(#{@parameters})"
end

#|(other) ⇒ Object



42
43
44
45
# File 'lib/adt/constructor.rb', line 42

def |(other)
  @others << other
  self
end