Class: OpenHash

Inherits:
OpenStruct
  • Object
show all
Defined in:
lib/open_hash.rb

Overview

OpenHash lets Hash called and assigned by the key in chainable way. Example:

person = OpenHash.new(name: "John", hometown: { city: "London" })
person.name #=> "John"
person.hometown.city #=> "London"

person = OpenHash.new
person.name = "Lion"
person.hometown.city = "Paris"
person.parents.father.name = "Heron"
person #=> { name: "Lion", hometown: { city: "Paris" }, parents: { father: { name: "Heron" } } }

Defined Under Namespace

Classes: BlackHole

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ OpenHash

Returns a new instance of OpenHash.



19
20
21
22
23
24
25
# File 'lib/open_hash.rb', line 19

def initialize(hash = {})
  hash = hash.each_with_object({}) do |(k, v), r|
    r[k] = v.is_a?(Hash) ? OpenHash.new(v) : v
  end

  super
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object

:nodoc:



29
30
31
# File 'lib/open_hash.rb', line 29

def method_missing(name, *args) # :nodoc:
  super || BlackHole.new(self, name)
end