Created
August 24, 2013 20:10
-
-
Save elskwid/6330170 to your computer and use it in GitHub Desktop.
Saw someone wishing for method cascading in Ruby and wanted to play around with the idea ...
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
# define | |
class Object | |
def cascade(method_name, *args, &block) | |
self.send(method_name, *args, &block) | |
self | |
end | |
# catch the cascade | |
def method_missing(method_name, *args, &block) | |
sig = /^__/ | |
if method_name =~ sig | |
new_method = method_name.to_s.gsub!(sig, "") | |
cascade new_method.to_sym, *args, &block | |
else | |
super | |
end | |
end | |
end | |
class A | |
attr_accessor :name | |
attr_accessor :description | |
def set_name(n) | |
self.name = n | |
end | |
end | |
a = A.new | |
# Call it directly | |
a.cascade(:name=, "Don") | |
.cascade(:description=, "Some guy") | |
puts a.inspect | |
#=> #<A:0x007fb53c873f40 @name="Don", @description="Some guy"> | |
a = A.new | |
# method missing | |
a.__set_name("Ernie") | |
.__description=("Another guy") | |
puts a.inspect | |
#=> #<A:0x007fb53c873d88 @name="Ernie", @description="Another guy"> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment