Class: Superstructure::ValueObj

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

Class Method Summary collapse

Class Method Details

.new(*arguments, superclass: Object, &blk) ⇒ Object



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
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/superstructure/value_obj.rb', line 4

def new *arguments, superclass: Object, &blk
  Class.new(superclass) do
    define_method(:initialize) do |opts={}|
      attribute_parser = AttributeParser.new(arguments, opts)
      if attribute_parser.error?
        raise attribute_parser.error
      else
        @attributes = attribute_parser.attributes
      end
    end

    def to_hash
      @attributes.clone
    end

    def inspect
      opts = @attributes.map do |k, v|
        "#{k}=#{v.inspect}"
      end.join(", ")

      unless opts.empty?
        opts.prepend(" ")
      end

      "#<value_obj #{self.class}#{opts}>"
    end

    def ==(o)
      self.class == o.class && to_hash == o.to_hash
    end

    alias :eql? :==

    def hash
      self.class.hash ^ @attributes.hash
    end

    arguments.each do |argument|
      define_method(argument) do
        to_hash[argument]
      end
    end

    class_eval(&blk) if blk
  end
end