21

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?

2 Answers 2

30

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.

1
  • In that case maybe your question needs some of the surrounding code for context. super calls the method that is overridden by the current method. What class and method is your code from, and what class does it inherit from?
    – dmnd
    Feb 24, 2011 at 11:24
23

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.

1
  • Your last sentence explains exactly what I'm looking for. Feb 24, 2011 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.