Module: StrictStruct

Defined in:
lib/strict_struct.rb,
lib/strict_struct/version.rb

Overview

require “strict_struct/version”

Defined Under Namespace

Modules: Helper

Constant Summary collapse

VERSION =
"0.0.4"

Class Method Summary collapse

Class Method Details

.new(*attributes, &block) ⇒ Object



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

def self.new(*attributes, &block)
  mod = Module.new 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
  klass = Class.new
  klass.send :include, mod
  klass.class_eval(&block) if block_given?
  klass
end