/
ostruct2.rb
409 lines (363 loc) · 8.03 KB
/
ostruct2.rb
1
2
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# OpenStruct2 is a better OpenStruct class.
#
# To demonstrate the weakness of the original OpenStruct, try this IRB session:
#
# irb(main):001:0> o = OpenStruct.new
# => #<OpenStruct>
# irb(main):002:0> o.display = "Hello, World!"
# => "Hello, World!"
# irb(main):003:0> o.display
# #<OpenStruct display="Hello, World!">=> nil
#
# This new OpenStruct class allows *almost* any member name to be used.
# The only exceptions are methods starting with double underscores,
# such as `__id__` and `__send__`, and a few neccessary public
# methods: `clone`, `dup`, `freeze`, `hash`, `to_enum`, `to_h`,
# `to_s` and `inspect`, as well as `instance_eval` and `instance_exec`.
#
# Also note that `empty`, `eql`, `equal`, `frozen` and `key` can be used as
# members but the key-check shorthand of using `?`-methods cannot be used since
# these have special definitions.
#
# To offset the loss of most methods, OpenStruct provides numerous
# bang-methods which can be used to manipulate the data, e.g. `#each!`.
# Currently most bang-methods route directly to the underlying hash table,
# so developers should keep that in mind when using this feature. A future
# version may add an intermediate interface to always ensure proper "CRUD",
# functonality but in the vast majority of cases it will make no difference,
# so it is left for later consideration.
#
# This improved version of OpenStruct also has no issues with being cloned
# since it does not depend on singleton methods to work. But singleton methods
# are used to help boost performance. But instead of always creating singleton
# methods, it only creates them on the first attempt to use them.
#
class OpenStruct2 < BasicObject
class << self
#
# Create autovivified OpenStruct.
#
# @example
# o = OpenStruct2.renew
# o.a #=> #<OpenStruct2: {}>
#
def auto(data=nil)
leet = lambda{ |h,k| new(&leet) }
new(&leet)
end
#
# Another name for #auto method.
#
# TODO: Still wondering waht the best name is for this.
#
alias :renew :auto
#
# Create a nested OpenStruct, such that all sub-hashes
# added to the table also become OpenStruct objects.
#
def nested(data=nil)
o = new
o.nested!(true)
o.update!(data) if data
o
end
#
# Shorter name for `nested`.
#
alias :nest :nested
#
# Constructor that is both autovivified and nested.
#
def cascade(data=nil)
o = renew
o.nested!(true)
o.update!(data) if data
o
end
private
def const_missing(name)
::Object.const_get(name)
end
end
#
# Initialize new instance of OpenStruct.
#
# @param [Hash] data
#
def initialize(data=nil, &block)
@table = ::Hash.new(&block)
update!(data || {})
end
#
# Because there is no means of getting the class via a BasicObject instance,
# we define such a method manually.
#
def __class__
OpenStruct2
end
#
# Duplicate underlying table when OpenStruct is duplicated or cloned.
#
# @param [OpenStruct] original
#
def initialize_copy(original)
super
@table = @table.dup
end
#
# Dispatch unrecognized member calls.
#
def method_missing(sym, *args, &blk)
str = sym.to_s
type = str[-1,1]
name = str.chomp('=').chomp('!').chomp('?')
case type
when '!'
# TODO: Probably should have an indirect interface to ensure proper
# functonality in all cases.
@table.public_send(name, *args, &blk)
when '='
new_ostruct_member(name)
store!(name, args.first)
when '?'
new_ostruct_member(name)
key?(name)
else
new_ostruct_member(name)
read!(name)
end
end
#
# Get/set nested flag.
#
def nested!(boolean=nil)
if boolean.nil?
@nested
else
@nested = !!boolean
end
end
#
# CRUD method for listing all keys.
#
def keys!
@table.keys
end
#
# Also a CRUD method like #read!, but for checking for the existence of a key.
#
def key?(key)
@table.key?(key.to_sym)
end
#
# The CRUD method for read.
#
def read!(key)
@table[key.to_sym]
end
#
# The CRUD method for create and update.
#
def store!(key, value)
if @nested && Hash === value # value.respond_to?(:to_hash)
value = OpenStruct2.new(value)
end
#new_ostruct_member(key) # this is here only for speed bump
@table[key.to_sym] = value
end
#
# The CRUD method for destroy.
#
def delete!(key)
@table.delete(key.to_sym)
end
#
# Same as `#delete!`. This method provides compatibility
# with the original OpenStruct class.
#
# @deprecated Use `#delete!` method instead.
#
def delete_field(key)
@table.delete(key.to_sym)
end
#
# Like #read but will raise a KeyError if key is not found.
#
def fetch!(key)
key!(key)
read!(key)
end
#
# If key is not present raise a KeyError.
#
# @param [#to_sym] key
#
# @raise [KeyError] If key is not present.
#
# @return key
#
def key!(key)
return key if key?(key)
::Kernel.raise ::KeyError, ("key not found: %s" % [key.inspect])
end
#
# Alias for `#read!`.
#
# @param [#to_sym] key
#
# @return [Object]
#
def [](key)
read!(key)
end
#
# Alias for `#store!`.
#
# @param [#to_sym] key
#
# @param [Object] value
#
# @return value.
#
def []=(key, value)
store!(key, value)
end
#
# CRUDified each.
#
# @return nothing
#
def each!
@table.each_key do |key|
yield(key, read!(key))
end
end
#
def map!(&block)
to_enum.map(&block)
end
#
# CRUDified update method.
#
# @return [self]
#
def update!(other)
other.each do |k,v|
store!(k,v)
end
self
end
#
# Merge this OpenStruct with another OpenStruct or Hash object
# returning a new OpenStruct instance.
#
# IMPORTANT! This method does not act in-place like `Hash#merge!`,
# rather it works like `Hash#merge`.
#
# @return [OpenStruct]
#
def merge!(other)
o = dup
other.each do |k,v|
o.store!(k,v)
end
o
end
#
# Inspect OpenStruct object.
#
# @return [String]
#
def inspect
"#<#{__class__}: #{@table.inspect}>"
end
alias :to_s :inspect
#
# Get a duplicate of the underlying table.
#
# @return [Hash]
#
def to_h
@table.dup
end
# TODO: Should OpenStruct2 support #to_hash ?
#alias :to_hash :to_h
#
# Create an enumerator based on `#each!`.
#
# @return [Enumerator]
#
def to_enum
# Why has Ruby 2 deprecated this form?
#::Enumerator.new(self, :each!)
::Kernel.instance_method(:to_enum).bind(self).call(:each!)
end
#
# Duplicate OpenStruct object.
#
# @return [OpenStruct] Duplicate instance.
#
def dup
__class__.new(@table, &@table.default_proc)
end
alias :clone :dup
#
# Hash number.
#
def hash
@table.hash
end
#
# Freeze OpenStruct instance.
#
def freeze
@table.freeze
end
#
# Is the OpenStruct instance frozen?
#
# @return [Boolean]
#
def frozen?
@table.frozen?
end
#
# Is the OpenStruct void of entries?
#
def empty?
@table.empty?
end
#
# Two OpenStructs are equal if they are the same class and their
# underlying tables are equal.
#
def eql?(other)
return false unless(other.kind_of?(__class__))
return @table == other.table #to_h
end
#
# Two OpenStructs are equal if they are the same class and their
# underlying tables are equal.
#
# TODO: Why not equal for other hash types, e.g. via #to_h?
#
def ==(other)
return false unless(other.kind_of?(__class__))
return @table == other.table #to_h
end
protected
def table
@table
end
def new_ostruct_member(name)
name = name.to_sym
# TODO: Check `#respond_to?` is needed? And if so how to do this in BasicObject?
#return name if self.respond_to?(name)
(class << self; self; end).class_eval do
define_method(name) { read!(name) }
define_method("#{name}?") { key?(name) }
define_method("#{name}=") { |value| store!(name, value) }
end
name
end
end