Module: YamlNormalizer::Ext::SortByKey

Defined in:
lib/yaml_normalizer/ext/sort_by_key.rb

Overview

YamlNormalizer::Ext::SortByKey extends an instance of Hash to provide the additional public helper methods sort_by_key. The approach of extending Hash instances avoids monkey-patching a Ruby Core class and using refinements.

Instance Method Summary collapse

Instance Method Details

#sort_by_key(recursive: true) ⇒ Object

Sorts entries alphabetically by key and returns a new Hash. sort_by_key does not modify the instance of Hash it’s called on.

Examples:

hash = { { b: { z: 20, x: 10, y: { b: 1, a: 2 } }, a: nil } }
hash.extend(YamlNormalizer::Ext::SortByKey)
hash.sort_by_key
=> {:a=>nil, :b=>{:x=>10, :y=>{:a=>2, :b=>1}, :z=>20}}

Parameters:

  • recursive (Boolean) (defaults to: true)

    defines if sort_by_key is called on child nodes, defaults to true



19
20
21
22
23
24
# File 'lib/yaml_normalizer/ext/sort_by_key.rb', line 19

def sort_by_key(recursive: true)
  keys.sort_by(&:to_s).each_with_object({}) do |key, seed|
    value = seed[key] = fetch(key)
    seed[key] = value.extend(SortByKey).sort_by_key if recursive && value.instance_of?(Hash)
  end
end