/
hash.rb
525 lines (493 loc) · 14.2 KB
/
hash.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
require 'hanami/utils/duplicable'
require 'transproc'
module Hanami
module Utils
# Hash on steroids
# @since 0.1.0
#
# rubocop:disable Metrics/ClassLength
class Hash
# @since 0.6.0
# @api private
#
# @see Hanami::Utils::Hash#deep_dup
# @see Hanami::Utils::Duplicable
DUPLICATE_LOGIC = proc do |value|
case value
when Hash
value.deep_dup
when ::Hash
Hash.new(value).deep_dup.to_h
end
end.freeze
extend Transproc::Registry
import Transproc::HashTransformations
# Symbolize the given hash
#
# @param input [::Hash] the input
#
# @return [::Hash] the symbolized hash
#
# @since 1.0.1
#
# @see .deep_symbolize
#
# @example Basic Usage
# require 'hanami/utils/hash'
#
# hash = Hanami::Utils::Hash.symbolize("foo" => "bar", "baz" => {"a" => 1})
# # => {:foo=>"bar", :baz=>{"a"=>1}}
#
# hash.class
# # => Hash
def self.symbolize(input)
self[:symbolize_keys].call(input)
end
# Performs deep symbolize on the given hash
#
# @param input [::Hash] the input
#
# @return [::Hash] the deep symbolized hash
#
# @since 1.0.1
#
# @see .symbolize
#
# @example Basic Usage
# require 'hanami/utils/hash'
#
# hash = Hanami::Utils::Hash.deep_symbolize("foo" => "bar", "baz" => {"a" => 1})
# # => {:foo=>"bar", :baz=>{a:=>1}}
#
# hash.class
# # => Hash
def self.deep_symbolize(input)
self[:deep_symbolize_keys].call(input)
end
# Stringifies the given hash
#
# @param input [::Hash] the input
#
# @return [::Hash] the stringified hash
#
# @since 1.0.1
#
# @example Basic Usage
# require 'hanami/utils/hash'
#
# hash = Hanami::Utils::Hash.stringify(foo: "bar", baz: {a: 1})
# # => {"foo"=>"bar", "baz"=>{:a=>1}}
#
# hash.class
# # => Hash
def self.stringify(input)
self[:stringify_keys].call(input)
end
# Deeply stringifies the given hash
#
# @param input [::Hash] the input
#
# @return [::Hash] the deep stringified hash
#
# @since 1.1.1
#
# @example Basic Usage
# require "hanami/utils/hash"
#
# hash = Hanami::Utils::Hash.deep_stringify(foo: "bar", baz: {a: 1})
# # => {"foo"=>"bar", "baz"=>{"a"=>1}}
#
# hash.class
# # => Hash
def self.deep_stringify(input) # rubocop:disable Metrics/MethodLength
input.each_with_object({}) do |(key, value), output|
output[key.to_s] =
case value
when ::Hash
deep_stringify(value)
when Array
value.map do |item|
item.is_a?(::Hash) ? deep_stringify(item) : item
end
else
value
end
end
end
# Deep duplicates hash values
#
# The output of this function is a deep duplicate of the input.
# Any further modification on the input, won't be reflected on the output
# and viceversa.
#
# @param input [::Hash] the input
#
# @return [::Hash] the deep duplicate of input
#
# @since 1.0.1
#
# @example Basic Usage
# require 'hanami/utils/hash'
#
# input = { "a" => { "b" => { "c" => [1, 2, 3] } } }
# output = Hanami::Utils::Hash.deep_dup(input)
# # => {"a"=>{"b"=>{"c"=>[1,2,3]}}}
#
# output.class
# # => Hash
#
#
#
# # mutations on input aren't reflected on output
#
# input["a"]["b"]["c"] << 4
# output.dig("a", "b", "c")
# # => [1, 2, 3]
#
#
#
# # mutations on output aren't reflected on input
#
# output["a"].delete("b")
# input
# # => {"a"=>{"b"=>{"c"=>[1,2,3,4]}}}
def self.deep_dup(input)
input.each_with_object({}) do |(k, v), result|
result[k] = case v
when ::Hash
deep_dup(v)
else
Duplicable.dup(v)
end
end
end
# Deep serializes given object into a `Hash`
#
# Please note that the returning `Hash` will use symbols as keys.
#
# @param input [#to_hash] the input
#
# @return [::Hash] the deep serialized hash
#
# @since 1.1.0
#
# @example Basic Usage
# require 'hanami/utils/hash'
# require 'ostruct'
#
# class Data < OpenStruct
# def to_hash
# to_h
# end
# end
#
# input = Data.new("foo" => "bar", baz => [Data.new(hello: "world")])
#
# Hanami::Utils::Hash.deep_serialize(input)
# # => {:foo=>"bar", :baz=>[{:hello=>"world"}]}
def self.deep_serialize(input) # rubocop:disable Metrics/MethodLength
input.to_hash.each_with_object({}) do |(key, value), output|
output[key.to_sym] =
case value
when ->(h) { h.respond_to?(:to_hash) }
deep_serialize(value)
when Array
value.map do |item|
item.respond_to?(:to_hash) ? deep_serialize(item) : item
end
else
value
end
end
end
# Initialize the hash
#
# @param hash [#to_h] the value we want to use to initialize this instance
# @param blk [Proc] define the default value
#
# @return [Hanami::Utils::Hash] self
#
# @since 0.1.0
# @deprecated
#
# @see http://www.ruby-doc.org/core/Hash.html#method-c-5B-5D
#
# @example Passing a Hash
# require 'hanami/utils/hash'
#
# hash = Hanami::Utils::Hash.new('l' => 23)
# hash['l'] # => 23
#
# @example Passing a block for default
# require 'hanami/utils/hash'
#
# hash = Hanami::Utils::Hash.new {|h,k| h[k] = [] }
# hash['foo'].push 'bar'
#
# hash.to_h # => { 'foo' => ['bar'] }
def initialize(hash = {}, &blk)
@hash = hash.to_hash
@hash.default_proc = blk if blk
end
# Converts in-place all the keys to Symbol instances.
#
# @return [Hash] self
#
# @since 0.1.0
# @deprecated Use {Hanami::Utils::Hash.symbolize}
#
# @example
# require 'hanami/utils/hash'
#
# hash = Hanami::Utils::Hash.new 'a' => 23, 'b' => { 'c' => ['x','y','z'] }
# hash.symbolize!
#
# hash.keys # => [:a, :b]
# hash.inspect # => { :a => 23, :b => { 'c' => ["x", "y", "z"] } }
def symbolize!
keys.each do |k|
v = delete(k)
self[k.to_sym] = v
end
self
end
# Converts in-place all the keys to Symbol instances, nested hashes are converted too.
#
# @return [Hash] self
#
# @since 1.0.0
# @deprecated Use {Hanami::Utils::Hash.deep_symbolize}
#
# @example
# require 'hanami/utils/hash'
#
# hash = Hanami::Utils::Hash.new 'a' => 23, 'b' => { 'c' => ['x','y','z'] }
# hash.deep_symbolize!
#
# hash.keys # => [:a, :b]
# hash.inspect # => {:a=>23, :b=>{:c=>["x", "y", "z"]}}
def deep_symbolize!
keys.each do |k|
v = delete(k)
v = self.class.new(v).deep_symbolize! if v.respond_to?(:to_hash)
self[k.to_sym] = v
end
self
end
# Converts in-place all the keys to Symbol instances, nested hashes are converted too.
#
# @return [Hash] self
#
# @since 0.3.2
# @deprecated Use {Hanami::Utils::Hash.stringify}
#
# @example
# require 'hanami/utils/hash'
#
# hash = Hanami::Utils::Hash.new a: 23, b: { c: ['x','y','z'] }
# hash.stringify!
#
# hash.keys # => [:a, :b]
# hash.inspect # => {"a"=>23, "b"=>{"c"=>["x", "y", "z"]}}
def stringify!
keys.each do |k|
v = delete(k)
v = self.class.new(v).stringify! if v.respond_to?(:to_hash)
self[k.to_s] = v
end
self
end
# Returns a deep copy of the current Hanami::Utils::Hash
#
# @return [Hash] a deep duplicated self
#
# @since 0.3.1
# @deprecated Use {Hanami::Utils::Hash.deep_dup}
#
# @example
# require 'hanami/utils/hash'
#
# hash = Hanami::Utils::Hash.new(
# 'nil' => nil,
# 'false' => false,
# 'true' => true,
# 'symbol' => :foo,
# 'fixnum' => 23,
# 'bignum' => 13289301283 ** 2,
# 'float' => 1.0,
# 'complex' => Complex(0.3),
# 'bigdecimal' => BigDecimal('12.0001'),
# 'rational' => Rational(0.3),
# 'string' => 'foo bar',
# 'hash' => { a: 1, b: 'two', c: :three },
# 'u_hash' => Hanami::Utils::Hash.new({ a: 1, b: 'two', c: :three })
# )
#
# duped = hash.deep_dup
#
# hash.class # => Hanami::Utils::Hash
# duped.class # => Hanami::Utils::Hash
#
# hash.object_id # => 70147385937100
# duped.object_id # => 70147385950620
#
# # unduplicated values
# duped['nil'] # => nil
# duped['false'] # => false
# duped['true'] # => true
# duped['symbol'] # => :foo
# duped['fixnum'] # => 23
# duped['bignum'] # => 176605528590345446089
# duped['float'] # => 1.0
# duped['complex'] # => (0.3+0i)
# duped['bigdecimal'] # => #<BigDecimal:7f9ffe6e2fd0,'0.120001E2',18(18)>
# duped['rational'] # => 5404319552844595/18014398509481984)
#
# # it duplicates values
# duped['string'].reverse!
# duped['string'] # => "rab oof"
# hash['string'] # => "foo bar"
#
# # it deeply duplicates Hash, by preserving the class
# duped['hash'].class # => Hash
# duped['hash'].delete(:a)
# hash['hash'][:a] # => 1
#
# duped['hash'][:b].upcase!
# duped['hash'][:b] # => "TWO"
# hash['hash'][:b] # => "two"
#
# # it deeply duplicates Hanami::Utils::Hash, by preserving the class
# duped['u_hash'].class # => Hanami::Utils::Hash
def deep_dup
self.class.new.tap do |result|
@hash.each { |k, v| result[k] = Duplicable.dup(v, &DUPLICATE_LOGIC) }
end
end
# Returns a new array populated with the keys from this hash
#
# @return [Array] the keys
#
# @since 0.3.0
# @deprecated
#
# @see http://www.ruby-doc.org/core/Hash.html#method-i-keys
def keys
@hash.keys
end
# Deletes the key-value pair and returns the value from hsh whose key is
# equal to key.
#
# @param key [Object] the key to remove
#
# @return [Object,nil] the value hold by the given key, if present
#
# @since 0.3.0
# @deprecated
#
# @see http://www.ruby-doc.org/core/Hash.html#method-i-keys
def delete(key)
@hash.delete(key)
end
# Retrieves the value object corresponding to the key object.
#
# @param key [Object] the key
#
# @return [Object,nil] the correspoding value, if present
#
# @since 0.3.0
# @deprecated
#
# @see http://www.ruby-doc.org/core/Hash.html#method-i-5B-5D
def [](key)
@hash[key]
end
# Associates the value given by value with the key given by key.
#
# @param key [Object] the key to assign
# @param value [Object] the value to assign
#
# @since 0.3.0
# @deprecated
#
# @see http://www.ruby-doc.org/core/Hash.html#method-i-5B-5D-3D
def []=(key, value)
@hash[key] = value
end
# Returns a Ruby Hash as duplicated version of self
#
# @return [::Hash] the hash
#
# @since 0.3.0
# @deprecated
#
# @see http://www.ruby-doc.org/core/Hash.html#method-i-to_h
def to_h
@hash.each_with_object({}) do |(k, v), result|
v = v.to_h if v.respond_to?(:to_hash)
result[k] = v
end
end
alias to_hash to_h
# Converts into a nested array of [ key, value ] arrays.
#
# @return [::Array] the array
#
# @since 0.3.0
# @deprecated
#
# @see http://www.ruby-doc.org/core/Hash.html#method-i-to_a
def to_a
@hash.to_a
end
# Equality
#
# @return [TrueClass,FalseClass]
#
# @since 0.3.0
# @deprecated
def ==(other)
@hash == other.to_h
end
alias eql? ==
# Returns the hash of the internal @hash
#
# @return [Fixnum]
#
# @since 0.3.0
# @deprecated
def hash
@hash.hash
end
# Returns a string describing the internal @hash
#
# @return [String]
#
# @since 0.3.0
# @deprecated
def inspect
@hash.inspect
end
# Overrides Ruby's method_missing in order to provide ::Hash interface
#
# @api private
# @since 0.3.0
#
# @raise [NoMethodError] If doesn't respond to the given method
def method_missing(method_name, *args, &blk)
raise NoMethodError.new(%(undefined method `#{method_name}' for #{@hash}:#{self.class})) unless respond_to?(method_name)
h = @hash.__send__(method_name, *args, &blk)
h = self.class.new(h) if h.is_a?(::Hash)
h
end
# Overrides Ruby's respond_to_missing? in order to support ::Hash interface
#
# @api private
# @since 0.3.0
def respond_to_missing?(method_name, include_private = false)
@hash.respond_to?(method_name, include_private)
end
end
# rubocop:enable Metrics/ClassLength
end
end