hashery 2.1.2 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,6 +23,13 @@ module Hashery
23
23
  #
24
24
  class PathHash < Hash
25
25
 
26
+ #
27
+ # Create a PathHash from a Hash, or from key-value pairs as Hash[] takes.
28
+ #
29
+ def self.[](*args)
30
+ new(Hash[*args])
31
+ end
32
+
26
33
  #
27
34
  # Initialize PathHash.
28
35
  #
@@ -30,10 +37,19 @@ module Hashery
30
37
  #
31
38
  def initialize(hsh={})
32
39
  raise ArgumentError, "must be a hash or array of slashed values" unless hsh.is_a?(Hash) || hsh.is_a?(Array)
40
+ hsh = hsh.expand if hsh.is_a?(PathHash)
33
41
  @constructor = hsh.is_a?(Hash) ? hsh.class : Hash
34
42
  @flat = flatten_to_hash(hsh)
35
43
  end
36
44
 
45
+ #
46
+ # Copies get their own table, so changing one doesn't change the other.
47
+ #
48
+ def initialize_copy(source)
49
+ super
50
+ @flat = @flat.dup
51
+ end
52
+
37
53
  # Standard Hash methods, plus the overwritten ones
38
54
  #include StandardHashMethodsInRuby
39
55
 
@@ -44,21 +60,18 @@ module Hashery
44
60
  # hash['c/d']
45
61
  #
46
62
  def [](key)
47
- rg = Regexp.new("^#{key}/?")
48
- start_obj = if @constructor == OrderedHash
49
- @constructor.new((@flat.instance_variable_get(:@keys_in_order) || []).collect {|e| e.gsub(rg,'')})
50
- else
51
- @constructor.new
52
- end
53
- v = @flat.has_key?(key) ? @flat[key] : self.class.new(@flat.reject {|k,v| !(k == key || k =~ rg)}.inject(start_obj) {|h,(k,v)| h[k.gsub(rg,'')] = v; h})
54
- v.is_a?(self.class) && v.empty? ? nil : v
63
+ key = key.to_s
64
+ return @flat[key] if @flat.has_key?(key)
65
+ sub = subtree(key)
66
+ sub.empty? ? nil : self.class.new(sub)
55
67
  end
56
68
 
57
69
  #
58
70
  # Same as above, except sets value rather than retrieving it.
59
71
  #
60
72
  def []=(key,value)
61
- @flat.reject! {|k,v| k == key || k =~ Regexp.new("^#{key}/")}
73
+ key = key.to_s
74
+ @flat.reject! {|k,v| under?(k, key)}
62
75
  if value.is_a?(Hash)
63
76
  flatten_to_hash(value).each do |hk,hv|
64
77
  @flat[key.to_s+'/'+hk.to_s] = hv
@@ -70,27 +83,20 @@ module Hashery
70
83
 
71
84
  def clear # :nodoc:
72
85
  @flat.clear
86
+ self
73
87
  end
74
88
 
75
89
  #
76
- #
90
+ # Like Hash#fetch, but slashed keys can be used here, too.
77
91
  #
78
92
  def fetch(key,default=:ehisehoah0928309q98y30,&block) # :nodoc:
79
- value = @flat.has_key?(key) ? @flat[key] : self.class.new(@flat.reject {|k,v| !(k == key || k =~ Regexp.new("^#{key}/"))}.inject({}) {|h,(k,v)| h[k.split('/',2)[1]] = v; h})
80
- if value.is_a?(self.class) && value.empty?
81
- if default == :ehisehoah0928309q98y30
82
- if block_given?
83
- block.call(key)
84
- else
85
- raise IndexError
86
- end
87
- value
88
- else
89
- default
90
- end
91
- else
92
- value
93
- end
93
+ key = key.to_s
94
+ return @flat[key] if @flat.has_key?(key)
95
+ sub = subtree(key)
96
+ return self.class.new(sub) unless sub.empty?
97
+ return block.call(key) if block
98
+ return default unless default == :ehisehoah0928309q98y30
99
+ raise KeyError, "key not found: #{key.inspect}"
94
100
  end
95
101
 
96
102
  #
@@ -102,9 +108,10 @@ module Hashery
102
108
  # Returns delete value.
103
109
  #
104
110
  def delete(key,&block)
105
- value = @flat.has_key?(key) ? @flat[key] : self.class.new(@flat.reject {|k,v| !(k == key || k =~ Regexp.new("^#{key}/"))}.inject({}) {|h,(k,v)| h[k.split('/',2)[1]] = v; h})
106
- return block.call(key) if value.is_a?(self.class) && value.empty? && block_given?
107
- @flat.keys.reject {|k| !(k == key || k =~ Regexp.new("^#{key}/"))}.each {|k| @flat.delete(k)}
111
+ key = key.to_s
112
+ return block ? block.call(key) : nil unless key?(key)
113
+ value = self[key]
114
+ @flat.delete_if {|k,v| under?(k, key)}
108
115
  return value
109
116
  end
110
117
 
@@ -113,9 +120,51 @@ module Hashery
113
120
  @flat.empty?
114
121
  end
115
122
 
123
+ #
124
+ # Is there a value at this key, or below it? Slashed keys can be used.
125
+ #
126
+ def key?(key)
127
+ key = key.to_s
128
+ @flat.any? {|k,v| under?(k, key)}
129
+ end
130
+ alias_method :has_key?, :key?
131
+ alias_method :include?, :key?
132
+ alias_method :member?, :key?
133
+
116
134
  # This gives you the slashed key of the value, no matter where the value is in the tree.
117
- def index(value)
118
- @flat.index(value)
135
+ def key(value)
136
+ @flat.key(value)
137
+ end
138
+ alias_method :index, :key
139
+
140
+ #
141
+ # Iterate over the top-level keys and their values, as #[] gives them.
142
+ #
143
+ def each
144
+ return to_enum(:each) { size } unless block_given?
145
+ keys.each {|k| yield k, self[k]}
146
+ self
147
+ end
148
+ alias_method :each_pair, :each
149
+
150
+ #
151
+ # The number of top-level keys.
152
+ #
153
+ def size
154
+ keys.size
155
+ end
156
+ alias_method :length, :size
157
+
158
+ #
159
+ # The values of the top-level keys, as #[] gives them.
160
+ #
161
+ def values
162
+ keys.map {|k| self[k]}
163
+ end
164
+
165
+ #
166
+ def to_a
167
+ keys.map {|k| [k, self[k]]}
119
168
  end
120
169
 
121
170
  #
@@ -132,6 +181,7 @@ module Hashery
132
181
  # end up with an array holding several hashes.
133
182
  def rehash # :nodoc:
134
183
  @flat.rehash
184
+ self
135
185
  end
136
186
 
137
187
  # Gives a list of all keys in all levels in the multi-level hash, joined by slashes.
@@ -145,8 +195,9 @@ module Hashery
145
195
 
146
196
  # Expands the whole hash to Hash objects ... not useful very often, it seems.
147
197
  def expand
148
- inject({}) {|h,(k,v)| h[k] = v.is_a?(SlashedHash) ? v.expand : v; h}
198
+ keys.inject({}) {|h,k| v = self[k]; h[k] = v.is_a?(PathHash) ? v.expand : v; h}
149
199
  end
200
+ alias_method :to_h, :expand
150
201
 
151
202
  def to_string_array
152
203
  flatten_to_array(flat,[])
@@ -156,45 +207,68 @@ module Hashery
156
207
  self
157
208
  end
158
209
 
159
- # Same as ordered! but returns a new SlashedHash object instead of modifying the same.
210
+ # Same as ordered! but returns a new PathHash object instead of modifying the same.
160
211
  def ordered(*keys_in_order)
161
212
  dup.ordered!(*keys_in_order)
162
213
  end
163
214
 
164
- # Sets the SlashedArray as ordered. The *keys_in_order must be a flat array
165
- # of slashed keys that specify the order for each level:
215
+ # Puts the entries in the given order. The *keys_in_order must be a flat
216
+ # array of slashed keys that specify the order for each level; entries
217
+ # not named keep their order, after those that are:
166
218
  #
167
- # s = {'a'=>{'b'=>'c', 'c'=>'d'}, 'b'=>'c'}.slashed
219
+ # s = PathHash['a'=>{'b'=>'c', 'c'=>'d'}, 'b'=>'c']
168
220
  # s.ordered!('b', 'a/c', 'a/b')
169
221
  # s.expand # => {'b'=>'c', 'a'=>{'c'=>'d', 'b'=>'c'}}
170
- # # Note that the expanded hashes will *still* be ordered!
171
222
  #
172
223
  def ordered!(*keys_in_order)
173
- return self if @constructor == OrderedHash
174
- @constructor = OrderedHash
175
- @flat = @flat.ordered(*keys_in_order)
224
+ ordered = @flat.class.new
225
+ keys_in_order.each do |key|
226
+ key = key.to_s
227
+ @flat.each {|k,v| ordered[k] = v if under?(k, key) && !ordered.has_key?(k)}
228
+ end
229
+ @flat.each {|k,v| ordered[k] = v unless ordered.has_key?(k)}
230
+ @flat = ordered
176
231
  self
177
232
  end
178
233
 
234
+ #
235
+ # A PathHash equals another with the same entries, or a Hash that would
236
+ # make one.
179
237
  #
180
238
  def ==(other)
181
239
  case other
182
- when SlashedHash
183
- @slashed == other.instance_variable_get(:@slashed)
240
+ when PathHash
241
+ @flat == other.flat
184
242
  when Hash
185
- self == SlashedHash.new(other)
243
+ self == PathHash.new(other)
186
244
  else
187
- raise TypeError, "Cannot compare #{other.class.name} with SlashedHash"
245
+ false
188
246
  end
189
247
  end
190
248
 
191
249
  private
192
250
 
193
- def flatten_to_hash(hsh)
194
- flat = @constructor.new
251
+ # Is the flat key +k+ the key +key+, or below it?
252
+ def under?(k, key)
253
+ k == key || k.start_with?(key + '/')
254
+ end
255
+
256
+ # The entries below +key+, with +key+ taken off the front of their keys.
257
+ def subtree(key)
258
+ prefix = key + '/'
259
+ @flat.each_with_object(@constructor.new) do |(k,v),h|
260
+ h[k[prefix.size..-1]] = v if k.start_with?(prefix)
261
+ end
262
+ end
263
+
264
+ def flatten_to_hash(hsh, flat=@constructor.new)
195
265
  if hsh.is_a?(Array)
196
266
  hsh.each do |e|
197
- flat.merge!(flatten_to_hash(e))
267
+ if e.is_a?(Hash) || e.is_a?(Array)
268
+ flat.merge!(flatten_to_hash(e))
269
+ else
270
+ flatten_to_hash(e, flat)
271
+ end
198
272
  end
199
273
  elsif hsh.is_a?(Hash)
200
274
  hsh.each do |k,v|
@@ -1,3 +1,5 @@
1
+ require 'hashery/crud_hash'
2
+
1
3
  module Hashery
2
4
 
3
5
  # StaticHash ia a Hash object which raises an error if any
@@ -0,0 +1,3 @@
1
+ module Hashery
2
+ VERSION = "2.2.2"
3
+ end
data/lib/hashery.rb CHANGED
@@ -1,6 +1,4 @@
1
- module Hashery
2
- VERSION = "2.1.0"
3
- end
1
+ require 'hashery/version'
4
2
 
5
3
  require 'hashery/core_ext'
6
4
 
@@ -14,8 +14,8 @@ testcase Association do
14
14
  class_method :[] do
15
15
  test do
16
16
  a = Association[:a, 1]
17
- a.assert.index == :a
18
- a.assert.value == 1
17
+ a.index.assert == :a
18
+ a.value.assert == 1
19
19
  end
20
20
  end
21
21
 
@@ -217,30 +217,38 @@ testcase Dictionary do
217
217
  end
218
218
 
219
219
  method :each_key do
220
- d = Dictionary[:a=>1, :b=>2, :c=>3]
221
- d.order_by_key
222
- a = []
223
- d.each_key{ |k| a << k }
224
- a.assert == [:a, :b, :c]
220
+ test do
221
+ d = Dictionary[:a=>1, :b=>2, :c=>3]
222
+ d.order_by_key
223
+ a = []
224
+ d.each_key{ |k| a << k }
225
+ a.assert == [:a, :b, :c]
226
+ end
225
227
  end
226
228
 
227
229
  method :each_value do
228
- d = Dictionary[:a=>1, :b=>2, :c=>3]
229
- d.order_by_value
230
- a = []
231
- d.each_value{ |v| a << v }
232
- a.assert == [1, 2, 3]
230
+ test do
231
+ d = Dictionary[:a=>1, :b=>2, :c=>3]
232
+ d.order_by_value
233
+ a = []
234
+ d.each_value{ |v| a << v }
235
+ a.assert == [1, 2, 3]
236
+ end
233
237
  end
234
238
 
235
239
  method :clear do
236
- d = Dictionary[:a=>1, :b=>2, :c=>3]
237
- d.clear
238
- d.to_a.assert == []
240
+ test do
241
+ d = Dictionary[:a=>1, :b=>2, :c=>3]
242
+ d.clear
243
+ d.to_a.assert == []
244
+ end
239
245
  end
240
246
 
241
247
  method :fetch do
242
- d = Dictionary[:a=>1, :b=>2, :c=>3]
243
- d.fetch(:a).assert == 1
248
+ test do
249
+ d = Dictionary[:a=>1, :b=>2, :c=>3]
250
+ d.fetch(:a).assert == 1
251
+ end
244
252
  end
245
253
 
246
254
  method :key? do
@@ -322,6 +330,253 @@ testcase Dictionary do
322
330
  s = d[:foo]
323
331
  s.class.assert == Dictionary
324
332
  end
333
+
334
+ test "copy fills itself, not the original" do
335
+ d = Dictionary.auto
336
+ d[:a][:b] = 1
337
+ c = d.dup
338
+ c[:x][:y] = 2
339
+ d.keys.assert == [:a]
340
+ c.keys.assert == [:a, :x]
341
+ end
342
+ end
343
+
344
+ # Sorting entries that don't compare (issue #7).
345
+
346
+ method :order_by_key do
347
+ test "with a nil key raises and leaves the dictionary usable" do
348
+ d = Dictionary.new
349
+ d[0] = 1
350
+ d[nil] = 2
351
+ ArgumentError.assert.raised? { d.order_by_key }
352
+ d.keys.assert == [0, nil]
353
+ d.inspect.assert == "{0=>1, nil=>2}"
354
+ end
355
+
356
+ test "with keys of different types raises and leaves the dictionary usable" do
357
+ d = Dictionary[:b, 1, 'a', 2]
358
+ ArgumentError.assert.raised? { d.order_by_key }
359
+ d.keys.assert == [:b, 'a']
360
+ end
361
+ end
362
+
363
+ method :order_by_value do
364
+ test "with a nil value raises and leaves the dictionary usable" do
365
+ d = Dictionary[:a, 2, :b, nil]
366
+ ArgumentError.assert.raised? { d.order_by_value }
367
+ d.values.assert == [2, nil]
368
+ end
369
+ end
370
+
371
+ method :order_by do
372
+ test "keeps the previous order if the new one fails" do
373
+ d = Dictionary[:b, 1, :a, nil]
374
+ d.order_by_key
375
+ ArgumentError.assert.raised? { d.order_by{ |k,v| v } }
376
+ d[:c] = 3
377
+ d.keys.assert == [:a, :b, :c]
378
+ end
379
+
380
+ test "without a block stops sorting" do
381
+ d = Dictionary[:b, 1, :a, 2].order_by_key
382
+ d.order_by
383
+ d[:"0"] = 3
384
+ d.keys.assert == [:a, :b, :"0"]
385
+ end
386
+ end
387
+
388
+ method :store do
389
+ test "refuses a key the sort order can't place" do
390
+ d = Dictionary.new.order_by_key
391
+ d.store(0, 1)
392
+ ArgumentError.assert.raised? { d.store(nil, 2) }
393
+ d.keys.assert == [0]
394
+ d.refute.key?(nil)
395
+ end
396
+
397
+ test "refuses a value the sort order can't place" do
398
+ d = Dictionary.new.order_by_value
399
+ d.store(:a, 1)
400
+ d.store(:b, 2)
401
+ ArgumentError.assert.raised? { d.store(:a, nil) }
402
+ d.to_a.assert == [[:a, 1], [:b, 2]]
403
+ end
404
+ end
405
+
406
+ method :push do
407
+ test "refuses a key the sort order can't place" do
408
+ d = Dictionary[0, 1].order_by_key
409
+ ArgumentError.assert.raised? { d.push(:a, 2) }
410
+ d.keys.assert == [0]
411
+ end
412
+ end
413
+
414
+ method :unshift do
415
+ test "refuses a key the sort order can't place" do
416
+ d = Dictionary[0, 1].order_by_key
417
+ ArgumentError.assert.raised? { d.unshift(:a, 2) }
418
+ d.keys.assert == [0]
419
+ end
420
+ end
421
+
422
+ method :insert do
423
+ test "refuses a key the sort order can't place" do
424
+ d = Dictionary[0, 1].order_by_key
425
+ ArgumentError.assert.raised? { d.insert(0, :a, 2) }
426
+ d.keys.assert == [0]
427
+ end
428
+ end
429
+
430
+ # Other fixes.
431
+
432
+ method :insert do
433
+ test "moves an existing key" do
434
+ d = Dictionary['a', 1, 'b', 2, 'c', 3]
435
+ d.insert(0, 'c', 9)
436
+ d.keys.assert == ['c', 'a', 'b']
437
+ d['c'].assert == 9
438
+ end
439
+
440
+ test "past the end adds at the end" do
441
+ d = Dictionary['a', 1, 'b', 2]
442
+ d.insert(5, 'c', 3)
443
+ d.keys.assert == ['a', 'b', 'c']
444
+ end
445
+ end
446
+
447
+ method :[]= do
448
+ test "with an index and a nil value" do
449
+ d = Dictionary[:a, 1]
450
+ d[:b, 0] = nil
451
+ d.to_a.assert == [[:b, nil], [:a, 1]]
452
+ end
453
+ end
454
+
455
+ method :delete do
456
+ test "matches keys as the hash does" do
457
+ d = Dictionary[1, :a, 1.0, :b]
458
+ d.delete(1)
459
+ d.keys.assert == [1.0]
460
+ d.length.assert == 1
461
+ end
462
+ end
463
+
464
+ method :shift do
465
+ test "when empty" do
466
+ Dictionary.new.shift.assert == nil
467
+ end
468
+
469
+ test "with a nil key" do
470
+ d = Dictionary[nil, 1, :a, 2]
471
+ d.shift.assert == [nil, 1]
472
+ d.keys.assert == [:a]
473
+ end
474
+ end
475
+
476
+ method :pop do
477
+ test "when empty" do
478
+ Dictionary.new.pop.assert == nil
479
+ end
480
+
481
+ test "with a nil key" do
482
+ d = Dictionary[:a, 1, nil, 2]
483
+ d.pop.assert == [nil, 2]
484
+ d.keys.assert == [:a]
485
+ end
486
+ end
487
+
488
+ method :reject! do
489
+ test "removes entries in place" do
490
+ d = Dictionary[:a, 1, :b, 2]
491
+ d.reject!{ |k,v| k == :a }.assert.equal?(d)
492
+ d.to_a.assert == [[:b, 2]]
493
+ end
494
+
495
+ test "returns nil when nothing is removed" do
496
+ d = Dictionary[:a, 1]
497
+ d.reject!{ false }.assert == nil
498
+ end
499
+ end
500
+
501
+ class_method :[] do
502
+ test "copies a hash argument" do
503
+ h = {:a=>1}
504
+ d = Dictionary[h]
505
+ d[:b] = 2
506
+ h.assert == {:a=>1}
507
+ end
508
+ end
509
+
510
+ method :replace do
511
+ test "copies another dictionary's order" do
512
+ a = Dictionary[:x, 1]
513
+ d = Dictionary.new
514
+ d.replace(a)
515
+ d[:y] = 2
516
+ a.keys.assert == [:x]
517
+ end
518
+
519
+ test "keeps the old entries if the sort order can't place the new ones" do
520
+ d = Dictionary[0, 1].order_by_key
521
+ ArgumentError.assert.raised? { d.replace(:a=>1, 2=>3) }
522
+ d.to_a.assert == [[0, 1]]
523
+ end
524
+ end
525
+
526
+ method :dup do
527
+ test "keeps the sort order" do
528
+ d = Dictionary.new.order_by{ |k,v| -v }
529
+ d[:a] = 1
530
+ d[:b] = 2
531
+ c = d.dup
532
+ c[:c] = 3
533
+ c.keys.assert == [:c, :b, :a]
534
+ end
535
+
536
+ test "keeps the default" do
537
+ Dictionary.new(0).dup[:x].assert == 0
538
+ end
539
+
540
+ test "is independent of the original" do
541
+ d = Dictionary[:a, 1]
542
+ c = d.dup
543
+ c[:b] = 2
544
+ c.delete(:a)
545
+ d.to_a.assert == [[:a, 1]]
546
+ end
547
+ end
548
+
549
+ method :clone do
550
+ test "is independent of the original" do
551
+ d = Dictionary[:a, 1]
552
+ c = d.clone
553
+ c[:b] = 2
554
+ d.keys.assert == [:a]
555
+ end
556
+ end
557
+
558
+ method :merge do
559
+ test "keeps the sort order" do
560
+ d = Dictionary[:b, 1].order_by_key
561
+ d.merge(:a=>2).keys.assert == [:a, :b]
562
+ end
563
+ end
564
+
565
+ method :reverse do
566
+ test "of a sorted dictionary" do
567
+ d = Dictionary[:a, 1, :b, 2].order_by_key
568
+ d.reverse.keys.assert == [:b, :a]
569
+ d.keys.assert == [:a, :b]
570
+ end
571
+ end
572
+
573
+ method :== do
574
+ test "with a sorted dictionary changed since it was last read" do
575
+ d = Dictionary.new.order_by_key
576
+ d[:b] = 1
577
+ d[:a] = 2
578
+ d.assert == Dictionary[:a, 2, :b, 1]
579
+ end
325
580
  end
326
581
 
327
582
  end
@@ -6,6 +6,30 @@ test_case IniHash do
6
6
  test do
7
7
  h = IniHash.new('foo.ini', false)
8
8
  end
9
+
10
+ test "from a hash" do
11
+ h = IniHash.new('a' => '1')
12
+ h['a'].assert == '1'
13
+ end
14
+ end
15
+
16
+ class_method :text do
17
+ test do
18
+ IniHash.text('a' => '1', 'b' => {'c' => '3'}).assert == "a=1\n[b]\nc=3\n"
19
+ end
20
+ end
21
+
22
+ class_method :write_to_file do
23
+ test "with a comment" do
24
+ require 'tmpdir'
25
+ Dir.mktmpdir do |dir|
26
+ path = File.join(dir, 'out.ini')
27
+ IniHash.write_to_file(path, {'a' => '1'}, "one\ntwo\n")
28
+ File.read(path).assert == "# one\n# two\na=1\n"
29
+ IniHash.read_comment_from_file(path).assert == "one\ntwo\n"
30
+ IniHash.read_from_file(path).assert == {'a' => '1'}
31
+ end
32
+ end
9
33
  end
10
34
 
11
35
  method :[]= do
@@ -48,8 +72,10 @@ test_case IniHash do
48
72
  end
49
73
 
50
74
  class_method :load do
51
- h = IniHash.load('test/fixture/example.ini')
52
- h['a'].assert == '1'
75
+ test do
76
+ h = IniHash.load('test/fixture/example.ini')
77
+ h['a'].assert == '1'
78
+ end
53
79
  end
54
80
 
55
81
  end