class Hash

Adds a few extra methods to the standard Hash

Public Instance Methods

get_value_from_path(path, sep_char = '.') click to toggle source
# File lib/screenplay/datatype-extensions.rb, line 56
def get_value_from_path(path, sep_char = '.')
        node, rest = path.to_s.split(sep_char, 2)
        index = node.gsub(/(^.*\[|\]$)/, '')
        value = nil
        if node == index
                value = self[node.to_sym] || self[node.to_s]
        elsif index.numeric?
                node.gsub!(/\[(\w+)\]$/, '')
                if self.include?(node.to_sym) && self[node.to_sym].is_a?(Array)
                        value = self[node.to_sym][index.to_i]
                elsif self.include?(node.to_s) && self[node.to_s].is_a?(Array)
                        value = self[node.to_s][index.to_i]
                else
                        value = nil
                end
        end
        return nil if value.nil?
        return value if rest.nil? || rest.empty?
        return value.is_a?(Hash) ? value.get_value_from_path(rest, sep_char) : nil
end
remove_nil_values!() click to toggle source

Removes all nil values from the hash. If the value is an array or hash, it will do this recursively.

# File lib/screenplay/datatype-extensions.rb, line 26
def remove_nil_values!
        self.delete_if { |_, v| v.nil? }
        self.each { |_, v| v.remove_nil_values! if (v.is_a?(Hash) || v.is_a?(Array)) }
end
stringify_keys!(recursive = true) click to toggle source

Changes all keys to strings. If the value is an array or hash, it will do this recursively.

# File lib/screenplay/datatype-extensions.rb, line 45
def stringify_keys!(recursive = true)
        self.keys.each do |key|
                if !key.is_a?(String)
                        val = self.delete(key)
                        val.stringify_keys! if (recursive && (val.is_a?(Hash) || val.is_a?(Array)))
                        self[(key.to_s rescue key) || key] = val
                end
        end
        return self
end
symbolize_keys!(recursive = true) click to toggle source

Changes all keys to symbols. If the value is an array or hash, it will do this recursively.

# File lib/screenplay/datatype-extensions.rb, line 32
def symbolize_keys!(recursive = true)
        self.keys.each { | key |
                if !key.is_a?(Symbol)
                        val = self.delete(key)
                        val.symbolize_keys! if (recursive && (val.is_a?(Hash) || val.is_a?(Array)))
                        self[(key.to_sym rescue key) || key] = val
                end
                self[key.to_sym].symbolize_keys! if (recursive && (self[key.to_sym].is_a?(Hash) || self[key.to_sym].is_a?(Array)))
        }
        return self
end