3
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
|
# File 'lib/r_kit/struct/safe_struct.rb', line 3
def self.new allowed:, defaults: {}
Class.new do
@allowed = allowed.map(&:ivar)
@defaults = defaults
def self.allowed() @allowed end
def self.defaults() @defaults end
attr_reader *allowed, default: proc{ |_, name| defaults[name] }
attr_writer *allowed
def initialize **options
options.keys.each do |name|
instance_variable_set "@#{ name }", options[name]
end
end
def instance_variable_set name, value
super if __class__.allowed.include? name
end
def to_hash
instance_variables.reduce({}) do |options, name|
options[name.lvar] = instance_variable_get name
options
end
end
delegate :slice,
to: :to_hash
end
end
|