Created
April 15, 2018 18:57
use instance methods with self for method chaining
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
class Module | |
def with_chain(&block) | |
m = Module.new | |
m.instance_eval(&block) | |
m.methods(false).each do |name| | |
define_method name do | |
m.method(name).call | |
self | |
end | |
end | |
end | |
end | |
class Me | |
def three | |
puts 'three callled' | |
end | |
with_chain do | |
def one | |
puts "one called" | |
end | |
def two | |
puts "two called" | |
end | |
end | |
end | |
Me.new.two.one.three | |
Me.new.three.two.one |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment