Module: HashKeyOrderable

Defined in:
lib/hash_key_orderable.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#key_orderObject

Returns the value of attribute key_order.



2
3
4
# File 'lib/hash_key_orderable.rb', line 2

def key_order
  @key_order
end

Class Method Details

.extended(obj) ⇒ Object



17
18
19
20
21
22
# File 'lib/hash_key_orderable.rb', line 17

def self.extended(obj)
  obj.instance_eval do
    alias :each_without_key_order :each
    alias :each :each_with_key_order
  end
end

Instance Method Details

#each_with_key_order(&block) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/hash_key_orderable.rb', line 4

def each_with_key_order(&block)
  if @key_order.nil? || @key_order.empty?
    each_without_key_order(&block)
    return self
  end
  unexist_keys = @key_order - self.keys
  actual_order = (@key_order - unexist_keys) | self.keys
  actual_order.each do |key|
    yield(key, self[key])
  end
  self
end