Created
May 9, 2014 05:28
-
-
Save bayleedev/0dad31c7251cd1bcbefb to your computer and use it in GitHub Desktop.
Hash traverser implemented in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-> % ruby traverser.rb | |
" - Created configer" | |
" - Created Document" | |
1 | |
" - Created Document" | |
"Blaines Practice" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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