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 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.
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论