Skip to content

Instantly share code, notes, and snippets.

@tadd
Last active August 16, 2022 09:54
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 tadd/58b6a2578585fb5a1a318bf0528983ce to your computer and use it in GitHub Desktop.
Save tadd/58b6a2578585fb5a1a318bf0528983ce to your computer and use it in GitHub Desktop.
Easier method chaining for Ruby
# Only for those who are too lazy to write `self` at the end of their methods
def tapper(m)
Module.new do
define_method(m) do |*a, **k, &b|
tap { super(*a,**k, &b) }
end
end
end
def chaining
singleton_class.define_method(:method_added) do |m|
prepend tapper(m)
end
end
return unless $0 == __FILE__
class C
attr_reader :x
def initialize(x)
@x = x
end
chaining
def foo
@x += 1
end
def bar
@x *= 2
end
def baz
@x **= 2
end
end
pp C.new(1).foo.bar.baz.x # => 16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment