root/trunk/activesupport/lib/active_support/core_ext/object/misc.rb
| Revision 7666, 1.7 kB (checked in by david, 9 months ago) |
|---|
| Line | |
|---|---|
| 1 | class Object |
| 2 | unless respond_to?(:send!) |
| 3 | # Anticipating Ruby 1.9 neutering send |
| 4 | alias send! send |
| 5 | end |
| 6 | |
| 7 | # A Ruby-ized realization of the K combinator, courtesy of Mikael Brockman. |
| 8 | # |
| 9 | # def foo |
| 10 | # returning values = [] do |
| 11 | # values << 'bar' |
| 12 | # values << 'baz' |
| 13 | # end |
| 14 | # end |
| 15 | # |
| 16 | # foo # => ['bar', 'baz'] |
| 17 | # |
| 18 | # def foo |
| 19 | # returning [] do |values| |
| 20 | # values << 'bar' |
| 21 | # values << 'baz' |
| 22 | # end |
| 23 | # end |
| 24 | # |
| 25 | # foo # => ['bar', 'baz'] |
| 26 | # |
| 27 | def returning(value) |
| 28 | yield(value) |
| 29 | value |
| 30 | end |
| 31 | |
| 32 | # An elegant way to refactor out common options |
| 33 | # |
| 34 | # with_options :order => 'created_at', :class_name => 'Comment' do |post| |
| 35 | # post.has_many :comments, :conditions => ['approved = ?', true], :dependent => :delete_all |
| 36 | # post.has_many :unapproved_comments, :conditions => ['approved = ?', false] |
| 37 | # post.has_many :all_comments |
| 38 | # end |
| 39 | # |
| 40 | # Can also be used with an explicit receiver: |
| 41 | # |
| 42 | # map.with_options :controller => "people" do |people| |
| 43 | # people.connect "/people", :action => "index" |
| 44 | # people.connect "/people/:id", :action => "show" |
| 45 | # end |
| 46 | # |
| 47 | def with_options(options) |
| 48 | yield ActiveSupport::OptionMerger.new(self, options) |
| 49 | end |
| 50 | |
| 51 | # A duck-type assistant method. For example, ActiveSupport extends Date |
| 52 | # to define an acts_like_date? method, and extends Time to define |
| 53 | # acts_like_time?. As a result, we can do "x.acts_like?(:time)" and |
| 54 | # "x.acts_like?(:date)" to do duck-type-safe comparisons, since classes that |
| 55 | # we want to act like Time simply need to define an acts_like_time? method. |
| 56 | def acts_like?(duck) |
| 57 | respond_to? "acts_like_#{duck}?" |
| 58 | end |
| 59 | end |
Note: See TracBrowser for help on using the browser.