From 0f9e65b71f9af30dac17689e81f4353e9fcac5b6 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 7 Jan 2009 13:19:48 -0800 Subject: Object#tap for Ruby < 1.8.7 --- activesupport/lib/active_support/core_ext/object/misc.rb | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'activesupport/lib/active_support') diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb index 46f9c7d676..4570570bbc 100644 --- a/activesupport/lib/active_support/core_ext/object/misc.rb +++ b/activesupport/lib/active_support/core_ext/object/misc.rb @@ -40,6 +40,21 @@ class Object value end + # Yields x to the block, and then returns x. + # The primary purpose of this method is to "tap into" a method chain, + # in order to perform operations on intermediate results within the chain. + # + # (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}" } + def tap + yield self + self + end unless Object.respond_to?(:tap) + # An elegant way to factor duplication out of options passed to a series of # method calls. Each method called in the block, with the block variable as # the receiver, will have its options merged with the default +options+ hash -- cgit v1.2.3