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.3"

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
# File 'lib/strict_struct.rb', line 22

def self.new(*attributes, &block)
  klass = Class.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
      Hash[@_strict_struct_hash.to_a]
    end

    define_method :== do |other|
      attributes.all? {|name| self.send(name) == other.send(name)}
    end
  end
  klass.class_eval(&block) if block_given?
  klass
end