Ruby: Tap that method

Ruby: Tap that method

Image for postRuby Tap 🙂

Recently I came across a really cool method which will make our ruby code more readable and it is tap.

The feature is coded in ruby as shown below

class Object def tap yield self self endend

So, How tap is used ?

user = User.new.tap do |u| u.username = “kartik” u.save!end

Isn?t it pretty and simple than the old conventional method of creating a object.

# Old Dusty Traditional Methoduser = User.newuser.username = “kartik”user.save!

So, What it does ?

In Simple words, it just allows you do something with an object inside of a block, and always have that block return the object itself.

It was created for tapping into method chains.

Another overkilling extension of above example can be as below so get what I meant to say, Everything in a block and readable.

user = User.new.tap do |u| u.build_profile u.process_credit_card u.ship_out_item u.send_email_confirmation u.blahblahblahend

Tap for debugging method chains:

If you see most of the time it?s pretty much difficult to debug chained methods. Lets see it with below example.

If I have to debug the below expression :

(1..10).to_a.select {|x| x%2 == 0}.map {|x| x*x}

I would generally add pry debugger above the expression and execute each chain one by one in order to see whats happening. Which is somehow boring and tiresome when you have many one liners like this.

Tap to the rescue :

Same thing can be done using tap without disturbing the chain of expressions and getting immediate results after each chain execution.

(1..10).tap { |x| puts “original: #{x.inspect}” }.to_a. tap { |x| puts “array: #{x.inspect}” }. select { |x| x%2 == 0 }. tap { |x| puts “evens: #{x.inspect}” }. map { |x| x*x }. tap { |x| puts “squares: #{x.inspect}” }

Conclusion :

Just like any other ruby syntactic sugar , I would say tap is a pretty cool ruby method which can not just be used for readability but also to debug chained methods. Give it a shot.

AVIACOMMERCE: OPEN SOURCE E-COMMERCE

Aviacommerce is an open source e-commerce framework with an aim to simplify e-commerce ecosystem by creating and unifying smart services and providing consistent, cost-effective solution to sellers helping them sell more. visit aviacommerce.org to know more.

Image for postclick the image to know more or visit https://aviacommerce.org

Reference :

  1. http://apidock.com/rails/v2.3.8/Object/tap
23