2
# Returns +value+ after yielding +value+ to the block. This simplifies the
3
# process of constructing an object, performing work on the object, and then
4
# returning the object from a method. It is a Ruby-ized realization of the K
5
# combinator, courtesy of Mikael Brockman.
17
# foo # => ['bar', 'baz']
19
# # returning with a local variable
21
# returning values = [] do
27
# foo # => ['bar', 'baz']
29
# # returning with a block argument
31
# returning [] do |values|
37
# foo # => ['bar', 'baz']
43
# Yields <code>x</code> to the block, and then returns <code>x</code>.
44
# The primary purpose of this method is to "tap into" a method chain,
45
# in order to perform operations on intermediate results within the chain.
47
# (1..10).tap { |x| puts "original: #{x.inspect}" }.to_a.
48
# tap { |x| puts "array: #{x.inspect}" }.
49
# select { |x| x%2 == 0 }.
50
# tap { |x| puts "evens: #{x.inspect}" }.
52
# tap { |x| puts "squares: #{x.inspect}" }
56
end unless Object.respond_to?(:tap)
58
# An elegant way to factor duplication out of options passed to a series of
59
# method calls. Each method called in the block, with the block variable as
60
# the receiver, will have its options merged with the default +options+ hash
61
# provided. Each method called on the block variable must take an options
62
# hash as its final argument.
64
# with_options :order => 'created_at', :class_name => 'Comment' do |post|
65
# post.has_many :comments, :conditions => ['approved = ?', true], :dependent => :delete_all
66
# post.has_many :unapproved_comments, :conditions => ['approved = ?', false]
67
# post.has_many :all_comments
70
# Can also be used with an explicit receiver:
72
# map.with_options :controller => "people" do |people|
73
# people.connect "/people", :action => "index"
74
# people.connect "/people/:id", :action => "show"
77
def with_options(options)
78
yield ActiveSupport::OptionMerger.new(self, options)
81
# A duck-type assistant method. For example, Active Support extends Date
82
# to define an acts_like_date? method, and extends Time to define
83
# acts_like_time?. As a result, we can do "x.acts_like?(:time)" and
84
# "x.acts_like?(:date)" to do duck-type-safe comparisons, since classes that
85
# we want to act like Time simply need to define an acts_like_time? method.
87
respond_to? "acts_like_#{duck}?"