class Hash

Overwriting hash class with new methods

Public Class Methods

to_raw(content_hash) click to toggle source

Converts a hash to a raw String in the form KEY = VAL

@param template [String] Hash content

@return [Hash, OpenNebula::Error] String representation in the form KEY = VALUE of

the hash, or an OpenNebula Error if the conversion fails
# File lib/opennebula/flow/validator.rb, line 64
def to_raw(content_hash)
    return '' if content_hash.nil? || content_hash.empty?

    content = ''
    content_hash.each do |key, value|
        case value
        when Hash
            sub_content = to_raw(value)

            content      += "#{key} = [\n"
            content_lines = sub_content.split("\n")

            content_lines.each_with_index do |line, index|
                content += line.to_s
                content += ",\n" unless index == content_lines.size - 1
            end

            content += "\n]\n"
        when Array
            value.each do |element|
                content += to_raw({ key.to_s => element })
            end
        else
            content += "#{key} = \"#{value.to_s.gsub('"', '\"')}\"\n"
        end
    end

    content
rescue StandardError => e
    return OpenNebula::Error.new("Error wrapping the hash: #{e.message}")
end

Public Instance Methods

deep_merge(other_hash, merge_array = true) click to toggle source

Returns a new hash containing the contents of other_hash and the contents of self. If the value for entries with duplicate keys is a Hash, it will be merged recursively, otherwise it will be that of other_hash.

@param [Hash] other_hash

@return [Hash] Containing the merged values

@example Merging two hashes

h1 = {:a => 3, {:b => 3, :c => 7}}
h2 = {:a => 22, c => 4, {:b => 5}}

h1.deep_merge(h2) #=> {:a => 22, c => 4, {:b => 5, :c => 7}}
# File lib/opennebula/flow/validator.rb, line 37
def deep_merge(other_hash, merge_array = true)
    target = clone

    other_hash.each do |key, value|
        current = target[key]

        target[key] =
            if value.is_a?(Hash) && current.is_a?(Hash)
                current.deep_merge(value)
            elsif (value.is_a?(Array) && current.is_a?(Array)) && merge_array
                current + value
            else
                value
            end
    end

    target
end