advantage of tap method in ruby

后端 未结 19 1088
天命终不由人
天命终不由人 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:48

    This can be useful with debugging a series of ActiveRecord chained scopes.

    User
      .active                      .tap { |users| puts "Users so far: #{users.size}" } 
      .non_admin                   .tap { |users| puts "Users so far: #{users.size}" }
      .at_least_years_old(25)      .tap { |users| puts "Users so far: #{users.size}" }
      .residing_in('USA')
    

    This makes it super easy to debug at any point in the chain without having to store anything in in a local variable nor requiring much altering of the original code.

    And lastly, use it as a quick and unobtrusive way to debug without disrupting normal code execution:

    def rockwell_retro_encabulate
      provide_inverse_reactive_current
      synchronize_cardinal_graham_meters
      @result.tap(&method(:puts))
      # Will debug `@result` just before returning it.
    end
    

提交回复
热议问题