Sha256: c1abda44732e4d0f9c40b7dc94a459f0b3ec24797bc09d60aa8d196b6ee33aa6

Contents?: true

Size: 1.68 KB

Versions: 9

Compression:

Stored size: 1.68 KB

Contents

module Hieracles
  module Utils

    def to_shallow_hash(hash)
      hash.reduce({}) do |shallow_hash, (key, value)|
        if value.is_a?(Hash)
          to_shallow_hash(value).each do |sub_key, sub_value|
            shallow_hash[[key, sub_key].join('.')] = sub_value
          end
        else
          shallow_hash[key.to_s] = value
        end
        shallow_hash
      end
    end

    def to_deep_hash(hash)
      hash.reduce({}) do |a, (key, value)|
        keys = key.to_s.split('.').reverse
        leaf_key = keys.shift
        key_hash = keys.reduce(leaf_key.to_sym => value) { |h, k| { k.to_sym => h } }
        local_merge!(a, key_hash)
        a
      end
    end
    
    def local_merge!(hash1, hash2)
      merger = proc { |key, v1, v2| v1.is_a?(Hash) && v2.is_a?(Hash) ? v1.merge(v2, &merger) : v2 }
      hash1.merge!(hash2, &merger)
    end

    def local_merge(hash1, hash2)
      merger = proc { |key, v1, v2| v1.is_a?(Hash) && v2.is_a?(Hash) ? v1.merge(v2, &merger) : v2 }
      hash1.merge(hash2, &merger)
    end

    def deep_sort(object)
      if object.is_a?(Hash)
        res = {}
        object.each { |k, v| res[k] = deep_sort(v) }
        Hash[res.sort { |a, b| a[0].to_s <=> b[0].to_s }]
      elsif object.is_a?(Array)
        if object[0].is_a?(Hash) || object[0].is_a?(Array)
          array = []
          object.each_with_index { |v, i| array[i] = deep_sort(v) }
          array
        else
          object.sort
        end
      else
        object
      end
    end

    def max_key_length(hash)
      hash.keys.reduce(0) { |a, x| (x.length > a) ? x.length : a }
    end

    def sym_keys(hash)
      hash.reduce({}) { |a, (k, v)| a[k.to_sym] = v ; a }
    end

  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
hieracles-0.4.2 lib/hieracles/utils.rb
hieracles-0.4.1 lib/hieracles/utils.rb
hieracles-0.4.0 lib/hieracles/utils.rb
hieracles-0.3.6 lib/hieracles/utils.rb
hieracles-0.3.5 lib/hieracles/utils.rb
hieracles-0.3.4 lib/hieracles/utils.rb
hieracles-0.3.3 lib/hieracles/utils.rb
hieracles-0.3.2 lib/hieracles/utils.rb
hieracles-0.3.1 lib/hieracles/utils.rb