Skip to content

Instantly share code, notes, and snippets.

@reddyonrails
Created April 15, 2018 18:57
use instance methods with self for method chaining
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