Created
June 14, 2011 15:41
-
-
Save code-later/1025167 to your computer and use it in GitHub Desktop.
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
class HouseDetail | |
def foo | |
return [1,2,3] | |
end | |
end | |
class KeyInvoker | |
instance_methods.reject {|meth| meth.to_s =~ /^_/ }.each { |meth| undef_method(meth.to_sym) } | |
def initialize(object) | |
@proxy_object = object | |
end | |
def call(path) | |
path_elements = path.split(".") | |
meth, path = path_elements.shift, path_elements.join('.') | |
value = __send__(meth) | |
if path_elements.empty? | |
respond_to?(meth) ? value : nil | |
else | |
KeyInvoker.new(value).call(path) | |
end | |
end | |
def respond_to?(meth) | |
@proxy_object.respond_to?(meth) | |
end | |
def method_missing(meth, *args, &blk) | |
if @proxy_object.respond_to?(meth) | |
@proxy_object.send(meth) | |
else | |
@proxy_object | |
end | |
end | |
end | |
ki = KeyInvoker.new(HouseDetail.new) | |
puts ki.call("house_detail.foo.length.to_s") | |
puts ki.call("house_detail.foo2.length") | |
puts ki.call("house_detail2.foo.length") | |
puts ki.call("house_detail.foo.length3") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment