advantage of tap method in ruby

后端 未结 19 1073
天命终不由人
天命终不由人 2020-12-22 16:50

I was just reading a blog article and noticed that the author used tap in a snippet something like:

user = User.new.tap do |u|
  u.username = \         


        
19条回答
  •  半阙折子戏
    2020-12-22 17:56

    I will give another example which I have used. I have a method user_params which returns the params needed to save for the user (this is a Rails project)

    def user_params
      params.require(:user).permit(
        :first_name,
        :last_name,
        :email,
        :address_attributes
      )
    end
    

    You can see I dont return anything but ruby return the output of the last line.

    Then, after sometime, I needed to add a new attribute conditionally. So, I changed it to something like this:

    def user_params 
      u_params = params.require(:user).permit(
        :first_name, 
        :last_name, 
        :email,
        :address_attributes
      )
      u_params[:time_zone] = address_timezone if u_params[:address_attributes]
      u_params
    end
    

    Here we can use tap to remove the local variable and remove the return:

    def user_params 
      params.require(:user).permit(
        :first_name, 
        :last_name, 
        :email,
        :address_attributes
      ).tap do |u_params|
        u_params[:time_zone] = address_timezone if u_params[:address_attributes]
      end
    end
    

提交回复
热议问题