Created
December 11, 2012 04:26
-
-
Save supernullset/4255860 to your computer and use it in GitHub Desktop.
Method chaining by message sending
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 Object | |
def send_each(*methods) | |
methods.inject(self) do |o, m| | |
o.respond_to?(m) ? o.public_send(m) : o | |
end | |
end | |
end | |
class MethodSequence | |
def document_download_cells(object, name, icon_path) | |
icon = content_tag(:td, image_tag(icon_path)) | |
title = content_tag(:td, name) | |
methods = [:content, :url] | |
link = nil | |
if url = chain(object, methods) | |
link = content_tag(:td, link_to("Download", url)) | |
end | |
[icon, title, link].sum | |
end | |
def chain(object, methods) | |
methods.each do |sym| | |
if object.send(sym) | |
object = object.send(sym) | |
else | |
return nil | |
end | |
end | |
object | |
end | |
# def send_each(methods, object) | |
# methods.inject(object) {|o, m| o.send(m) } | |
# end | |
end | |
class SomeObject | |
def foo | |
"FOO" | |
return nil | |
end | |
def bar | |
"bar" | |
end | |
def baz | |
"baz" | |
end | |
end | |
# result = MethodSequence.new.send_each([:foo, :downcase, :reverse], SomeObject.new) | |
# puts result | |
result = SomeObject.new.send_each(:foo, :downcase, :reverse) | |
puts result | |
result = "Foo".send_each(:downcase, :not_here, :reverse) | |
result = "Foo".downcase.reverse | |
puts result | |
# obj = SomeObject.new | |
# obj.foo.bar.baz.downcase <-- chain? | |
# obj.foo | |
# obj.bar | |
# obj.bax | |
# obj.downcase | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment