Class: Rumbly::OptionsHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/rumbly/options_hash.rb

Overview

An OptionsHash is a subclass of Hash class that adds the following functionality:

  • all keys are converted to symbols when storing or retrieving

  • values can be accessed using methods named after keys (ala Structs)

  • nested values can be accessed using chained method calls or dotted key values

  • keys are implicitly created if an unknown method is called

  • the has_key? method is enhanced to test for nested key paths

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &blk) ⇒ Object

Allows values to be stored and retrieved using methods named for the keys. If an attempt is made to access a key that doesn’t exist, a nested OptionsHash will be created as the value stored for the given key. This allows for setting a nested option without having to explicitly create each nested hash.



58
59
60
61
62
63
64
65
66
# File 'lib/rumbly/options_hash.rb', line 58

def method_missing (name, *args, &blk)
  unless respond_to?(name)
    if reader?(name, args, blk)
      get_or_create_value(name)
    elsif writer?(name, args, blk)
      store_value(chop_sym(name), args[0])
    end
  end
end

Instance Method Details

#[](key) ⇒ Object

Converts key to a Symbol before calling the normal Hash#[] method. If the key is a dotted list of keys, digs down into any nested hashes to find the value. Returns nil if any of the sub-hashes are not present.



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rumbly/options_hash.rb', line 14

def [] (key)
  unless key =~ /\./
    super(key.to_sym)
  else
    k, *r = *split_key(key)
    if (sub = self[k]).nil?
      nil
    else
      self[k][join_keys(r)]
    end
  end
end

#[]=(key, value) ⇒ Object

Converts key to a Symbol before calling the normal Hash#[]= method. If the key is a dotted list of keys, digs down into any nested hashes (creating them if necessary) to store the value.



30
31
32
33
34
35
36
37
38
# File 'lib/rumbly/options_hash.rb', line 30

def []= (key, value)
  unless key =~ /\./
    super(key.to_sym, value)
  else
    k, *r = *split_key(key)
    sub = get_or_create_value(k)
    sub[join_keys(r)] = value
  end
end

#has_key?(key) ⇒ Boolean

Returns true if this OptionsHash has a value stored under the given key. In the case of a compound key (multiple keys separated by dots), digs down into any nested hashes to find a value. Returns false if any of the sub-hashes or values are nil.

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
# File 'lib/rumbly/options_hash.rb', line 44

def has_key? (key)
  unless key =~ /\./
    super(key.to_sym)
  else
    k, *r = *split_key(key)
    return false if (sub = self[k]).nil?
    return sub.has_key?(join_keys(r))
  end
end