Yes, those three dots are intentional. Yes it's a pun. No I won't stop. Yes, you'll understand if you read this article to the end.
The problem
Have you ever ended up writing tons of methods doing mostly parameter forwarding?
class Foo
attr_reader :bar
# That's the one:
def do_stuff(x, y:)
bar.do_stuff(x, y:)
end
end
Ruby's Forwardable
module may be the solution to writing simpler code:
require 'forwardable'
class Foo
attr_reader :bar
extend Forwardable
def_delegator :@bar, :do_stuff
end
But what if I'd like to "do stuff" twice? Or add a log line?
Triple dots to the rescue
Recently, I learned that Ruby includes an argument forwarding shorthand since its version 2.7! (Which exists since 2019)
The syntax
This shorthand is ...
. Simple as that, and you can add your log line without bothering with how the arguments are going to evolve in the future:
def do_stuff(...)
puts 'My log line'
bar.do_stuff(...)
end
The good thing is: if bar#do_stuff
is added another argument, my foo#do_stuff
method do NOT have to change!
Leading arguments
But what if I'd like to access one of the arguments before forwarding it?
Since its version 3.0, Ruby gained support for leading arguments:
def do_stuff(x, ...)
bar.do_stuff(x, ...)
end
Hope you'll use it a lot...
Top comments (0)