Last active
August 16, 2022 09:54
-
-
Save tadd/58b6a2578585fb5a1a318bf0528983ce to your computer and use it in GitHub Desktop.
Easier method chaining for Ruby
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
# 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