Created
August 19, 2010 01:03
-
-
Save jgagner/536696 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#doesn't accept args for the methods... probably next on that | |
class Object | |
def try_chain(*args) | |
method = args.shift | |
if respond_to?(method) | |
args.empty? ? self.send(method) : self.send(method).try_chain(*args) | |
else | |
nil | |
end | |
end | |
end | |
class MyClass | |
attr_accessor :domain_object | |
attr_accessor :text_value | |
def initialize(domain_object,text_value=nil) | |
@domain_object = domain_object | |
@text_value = text_value | |
end | |
def to_s | |
return @text_value + " to_s" | |
end | |
end | |
obj = MyClass.new(MyClass.new(MyClass.new(nil,"obj3"),"obj2"),"obj 1") | |
puts obj.try_chain(:domain_object) | |
puts obj.domain_object | |
puts "*******" | |
puts obj.try_chain(:domain_object,:domain_object,:domain_object,:domain_object) | |
puts obj.domain_object.domain_object.text_value | |
puts "*******" | |
puts obj.try_chain(:domain_object,:text_value) | |
puts obj.try_chain(:text_value) | |
puts obj.try_chain(:domain_object,:domain_object) | |
obj2 to_s | |
obj2 to_s | |
******* | |
nil | |
obj3 | |
******* | |
obj2 | |
obj 1 | |
obj3 to_s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment