Class: StrictStruct::AttributeModule

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

Instance Method Summary collapse

Constructor Details

#initialize(*attributes) ⇒ AttributeModule

Returns a new instance of AttributeModule.



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
50
51
52
53
54
# File 'lib/strict_struct.rb', line 23

def initialize *attributes
  super() do
    define_method :initialize do |hash={}|
      Helper.validate_arguments(hash.keys, attributes)
      @_strict_struct_hash = Hash[hash.to_a].freeze
    end

    attributes.each do |attribute|
      define_method(attribute) do
        @_strict_struct_hash[attribute]
      end
    end

    def to_h
      to_hash
    end

    def to_hash
      Hash[@_strict_struct_hash.to_a]
    end

    define_method :== do |other|
      return false unless self.class == other.class

      attributes.all? {|name| self.send(name) == other.send(name)}
    end

    define_method :hash do
      @_strict_struct_hash.hash
    end
  end
end