Class: Fastball::HashDot

Inherits:
Object
  • Object
show all
Defined in:
lib/fastball/hash_dot.rb

Overview

A utility class to allow referencing nested hash values as chained method calls.

Example

!!!
ruby> h = Fastball::HashDot.new name: { name: 'Jordan', state: 'Texas' }
ruby> h.contact.name
 => "Jordan"
ruby> h.contact.state
 => "Texas"

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ HashDot

Returns a new instance of HashDot.


16
17
18
19
20
21
22
23
24
25
26
# File 'lib/fastball/hash_dot.rb', line 16

def initialize(hash={})
  @hash = {}

  hash.map do |k, v|
    @hash[k.to_s] = if v.kind_of?(Hash)
      self.class.new v
    else
      @hash[k.to_s] = v
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object (private)


30
31
32
# File 'lib/fastball/hash_dot.rb', line 30

def method_missing(method_name, *args, &block)
  @hash[method_name.to_s] || super
end