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
|
# File 'lib/l43/open_object.rb', line 7
def attributes(*atts, **defaults)
attr_reader(*atts)
attr_reader(*defaults.keys)
define_method :== do |other|
other&.to_h == to_h
end
define_method :initialize do |**kwds|
missing = atts - kwds.keys
raise ArgumentError, "missing required keyword parameters: #{missing.inspect}" unless missing.empty?
spurious = kwds.keys - atts - defaults.keys
raise ArgumentError, "spurious keyword parameters: #{spurious.inspect}" unless spurious.empty?
values = defaults.merge(kwds)
values.each do |key, value|
instance_variable_set("@#{key}", value)
end
_init if respond_to?(:_init)
end
define_method :to_h do |*|
first = atts.inject Hash.new do |h, attribute|
h.update(attribute => send(attribute))
end
defaults.keys.inject first do |h, attribute|
h.update(attribute => send(attribute))
end
end
alias_method :deconstruct_keys, :to_h
end
|