Skip to content

Instantly share code, notes, and snippets.

@bayleedev
Created May 9, 2014 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bayleedev/0dad31c7251cd1bcbefb to your computer and use it in GitHub Desktop.
Save bayleedev/0dad31c7251cd1bcbefb to your computer and use it in GitHub Desktop.
Hash traverser implemented in ruby
-> % ruby traverser.rb
" - Created configer"
" - Created Document"
1
" - Created Document"
"Blaines Practice"
require 'pry'
class Configer
attr_accessor :data
def initialize(data)
@data = data
p " - Created configer"
end
def method_missing(method, *args)
pointer = data[method]
if pointer.is_a?(Enumerable)
Document.new(config: self, pointer: pointer)
else
@pointer
end
end
end
class Document
attr_accessor :pointer, :op
def initialize(options)
p " - Created Document"
@pointer = options[:pointer]
@op = @pointer
@config = options[:config]
end
def traverse_next_key?(key)
return_key(key).is_a?(Enumerable)
end
def traverse_next_key(key)
@pointer = return_key(key)
self
end
def return_key(key)
pointer[key]
end
def reset
@pointer = op
end
def method_missing(method, *args)
if traverse_next_key?(method)
traverse_next_key(method)
else
data = return_key(method) and reset and data
end
end
end
conf = Configer.new({
name: 'Dr Blaine',
practice: {
numbers: ['a', 'b', 'c'],
name: 'Blaines Practice',
location: {
street: '107 E 31st Pl',
city: 'Tulsa',
state: 'Oklahoma',
country: {
_id: 1,
name: 'United States of America',
}
}
}
})
p conf.practice.location.country._id
p conf.practice.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment