I came across this construction in a gem and don't understand the intent. I know what tap does alone, but why would someone call super.tap {} instead of just continuing the code normally after the super call.
def my_method
super.tap do |u|
if @user && @user.new_record?
@omniauth = u.session[:session]
u.session[:omniauth] = nil unless @user.new_record?
end
end
end
Can anyone enlighten me?
tap method. This method allows you to "tap" into the result of a method call, usually to perform additional operations on that result, or to debug that result (i.e. by printing to the console). A quick Google search for ruby tap method will return a lot of articles and StackOverflow discussions about when to use .
tap
is used to perform some operations on an object, and then return that object. That sounds confusing, but it's helpful when chaining methods. Example:
def make_a_something
t = Something.new
t.method
t.attr = 'foo'
t # must remember to manually return t, otherwise 'foo' is returned
end
can be replaced with
def make_a_something
Something.new.tap do |t|
t.method
t.attr = 'foo'
end
end
If that doesn't strike you as terribly useful, see some further examples here.
super.tap
is nothing but tap
method called on whatever super
returns. User dmnd already explained pretty well what tap
does (why the downwote?). super
calls the method from the ancestor class which you are overriding.
So, the code you pasted is equivalent with the following:
original_result = super
if @user && @user.new_record?
@omniauth = original_result.session[:session]
original_result.session[:omniauth] = nil unless @user.new_record?
end
return original_result
Essentially, super.tap
can be used for wrapping the method from the inherited class, adding some functionality, but keeping the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With