diff options
author | Jeremy Kemper <jeremy@bitsweat.net> | 2009-01-07 13:19:48 -0800 |
---|---|---|
committer | Jeremy Kemper <jeremy@bitsweat.net> | 2009-01-07 13:19:48 -0800 |
commit | 0f9e65b71f9af30dac17689e81f4353e9fcac5b6 (patch) | |
tree | 60b61c07e519ae2078575ec07ef7a030e4857467 /activesupport | |
parent | 17da45b789e0a2581eae6e6b2b1ae8d2b98e0f5d (diff) | |
download | rails-0f9e65b71f9af30dac17689e81f4353e9fcac5b6.tar.gz rails-0f9e65b71f9af30dac17689e81f4353e9fcac5b6.tar.bz2 rails-0f9e65b71f9af30dac17689e81f4353e9fcac5b6.zip |
Object#tap for Ruby < 1.8.7
Diffstat (limited to 'activesupport')
-rw-r--r-- | activesupport/CHANGELOG | 3 | ||||
-rw-r--r-- | activesupport/lib/active_support/core_ext/object/misc.rb | 15 | ||||
-rw-r--r-- | activesupport/test/core_ext/object_ext_test.rb | 8 |
3 files changed, 26 insertions, 0 deletions
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 3c5f39d321..757cb1da04 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,8 @@ *2.3.0 [Edge]* +* Object#tap shim for Ruby < 1.8.7. Similar to Object#returning, tap yields self then returns self. [Jeremy Kemper] + array.select { ... }.tap(&:inspect).map { ... } + * TimeWithZone#- gives correct result with wrapped DateTime, and with DateTime argument [Geoff Buesing] * Updated i18n gem to version 0.1.1 #1635 [Yaroslav Markin] 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 <code>x</code> to the block, and then returns <code>x</code>. + # 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 diff --git a/activesupport/test/core_ext/object_ext_test.rb b/activesupport/test/core_ext/object_ext_test.rb new file mode 100644 index 0000000000..a413d331c4 --- /dev/null +++ b/activesupport/test/core_ext/object_ext_test.rb @@ -0,0 +1,8 @@ +require 'abstract_unit' + +class ObjectExtTest < Test::Unit::TestCase + def test_tap_yields_and_returns_self + foo = Object.new + assert_equal foo, foo.tap { |x| assert_equal foo, x; :bar } + end +end |