Class: Configurable::OrderedHashPatch

Inherits:
Hash
  • Object
show all
Defined in:
lib/configurable/class_methods.rb

Overview

Beginning with ruby 1.9, Hash tracks the order of insertion and methods like each_pair return pairs in order. Configurable leverages this feature to keep configurations in order for the command line documentation produced by ConfigParser.

Pre-1.9 ruby implementations require a patched Hash that tracks insertion order. This very thin subclass of hash does that for ASET insertions and each_pair. OrderedHashPatches are used as the configurations object in Configurable classes for pre-1.9 ruby implementations and for nothing else.

Instance Method Summary collapse

Constructor Details

#initializeOrderedHashPatch

Returns a new instance of OrderedHashPatch.



431
432
433
434
# File 'lib/configurable/class_methods.rb', line 431

def initialize
  super
  @insertion_order = []
end

Instance Method Details

#[]=(key, value) ⇒ Object

ASET insertion, tracking insertion order.



437
438
439
440
# File 'lib/configurable/class_methods.rb', line 437

def []=(key, value)
  @insertion_order << key unless @insertion_order.include?(key)
  super
end

#each_pairObject

Yields each key-value pair to the block in insertion order.



450
451
452
453
454
# File 'lib/configurable/class_methods.rb', line 450

def each_pair
  keys.each do |key|
    yield(key, fetch(key))
  end
end

#initialize_copy(orig) ⇒ Object

Ensures the insertion order of duplicates is separate from parents.



457
458
459
460
# File 'lib/configurable/class_methods.rb', line 457

def initialize_copy(orig)
  super
  @insertion_order = orig.instance_variable_get(:@insertion_order).dup
end

#keysObject

Keys, sorted into insertion order



443
444
445
446
447
# File 'lib/configurable/class_methods.rb', line 443

def keys
  super.sort_by do |key|
    @insertion_order.index(key) || length
  end
end

#to_yaml(opts = {}) ⇒ Object

Overridden to preserve insertion order by serializing self as an array of [key, value] pairs.



479
480
481
482
483
484
485
486
487
# File 'lib/configurable/class_methods.rb', line 479

def to_yaml( opts = {} )
  YAML::quick_emit( object_id, opts ) do |out|
    out.seq( taguri, to_yaml_style ) do |seq|
      each_pair do |key, value|
        seq.add( [key, value] )
      end
    end
  end
end

#yaml_initialize(tag, val) ⇒ Object

Overridden to load an array of [key, value] pairs in order (see to_yaml). The default behavior for loading from a hash of key-value pairs is preserved, but the insertion order will not be preserved.



465
466
467
468
469
470
471
472
473
474
475
# File 'lib/configurable/class_methods.rb', line 465

def yaml_initialize( tag, val )
  @insertion_order ||= []
 
  if Array === val
    val.each do |k, v|
      self[k] = v
    end
  else
    super
  end
end