Skip to content

Instantly share code, notes, and snippets.

@reddyonrails
Created April 15, 2018 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reddyonrails/57e8c7c05fbec8150c444eaf9428c88c to your computer and use it in GitHub Desktop.
Save reddyonrails/57e8c7c05fbec8150c444eaf9428c88c to your computer and use it in GitHub Desktop.
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