class General::GDotHash

Wrapper for hash objects which implements dot notation

Author: Anshul Kharbanda Created: 9 - 27 - 2016

Public Class Methods

new(hash={}) click to toggle source

Initializes the given GDotHash with the given hash

Parameter: hash - the hash being manipulated

# File lib/gdothash.rb, line 30
def initialize(hash={}); @hash = hash; end

Public Instance Methods

[](key) click to toggle source

Gets the value at the given key

Parameter: key - the key to return

Return: the value at the given key

# File lib/gdothash.rb, line 67
def [] key
        # Split keys
        subkeys = key.to_s.split(".").collect(&:to_sym)

        # Travel down to value
        get = @hash
        subkeys.each do |subkey|
                if get.is_a?(Hash) && get.has_key?(subkey)
                        get = get[subkey]
                else
                        raise ArgumentError, "key is not defined in hash: #{key}"
                end
        end

        # Return value
        return get
end
[]=(key, value) click to toggle source

Sets the given key to the given value

Parameter: key - the key to set Parameter: value - the value to set

# File lib/gdothash.rb, line 89
def []= key, value
        # Split subkeys
        subkeys = key.to_s.split(".").collect(&:to_sym)

        # Generate structure of new data
        new_data = Hash.new
        sub = new_data
        subkeys[0...-1].each do |subkey|
                sub[subkey] = Hash.new
                sub = sub[subkey]
        end
        sub[subkeys[-1]] = value

        # Merge hash with new data
        @hash.merge! new_data
end
has_key?(key) click to toggle source

Returns true if the GDotHash contains the given key

Parameter: key - the key to check

Return: true if the GDotHash contains the given key

# File lib/gdothash.rb, line 42
def has_key? key
        # Split keys
        subkeys = key.to_s.split(".").collect(&:to_sym)

        # Check each subkey
        sub = @hash
        subkeys.each do |subkey|
                # Return false if subhash doesn't contain key
                # Else continue
                if sub.is_a?(Hash) && sub.has_key?(subkey)
                        sub = sub[subkey]
                else
                        return false
                end
        end

        # Return true if passed
        return true
end
to_s() click to toggle source

Returns the string representation of the hash

Return: the string representation of the hash

# File lib/gdothash.rb, line 35
def to_s; @hash.to_s; end