Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/activesupport/lib/active_support/core_ext/module/aliasing.rb

Revision 8312, 2.0 kB (checked in by marcel, 5 months ago)

Fix incorrect superclass in documentation for alias_attribute. Closes #7171 [tzaharia]

Line 
1 class Module
2   # Encapsulates the common pattern of:
3   #
4   #   alias_method :foo_without_feature, :foo
5   #   alias_method :foo, :foo_with_feature
6   #
7   # With this, you simply do:
8   #
9   #   alias_method_chain :foo, :feature
10   #
11   # And both aliases are set up for you.
12   #
13   # Query and bang methods (foo?, foo!) keep the same punctuation:
14   #
15   #   alias_method_chain :foo?, :feature
16   #
17   # is equivalent to
18   #
19   #   alias_method :foo_without_feature?, :foo?
20   #   alias_method :foo?, :foo_with_feature?
21   #
22   # so you can safely chain foo, foo?, and foo! with the same feature.
23   def alias_method_chain(target, feature)
24     # Strip out punctuation on predicates or bang methods since
25     # e.g. target?_without_feature is not a valid method name.
26     aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
27     yield(aliased_target, punctuation) if block_given?
28    
29     with_method, without_method = "#{aliased_target}_with_#{feature}#{punctuation}", "#{aliased_target}_without_#{feature}#{punctuation}"
30    
31     alias_method without_method, target
32     alias_method target, with_method
33    
34     case
35       when public_method_defined?(without_method)
36         public target
37       when protected_method_defined?(without_method)
38         protected target
39       when private_method_defined?(without_method)
40         private target
41     end
42   end
43
44   # Allows you to make aliases for attributes, which includes
45   # getter, setter, and query methods.
46   #
47   # Example:
48   #
49   #   class Content < ActiveRecord::Base
50   #     # has a title attribute
51   #   end
52   #
53   #   class Email < Content
54   #     alias_attribute :subject, :title
55   #   end
56   #
57   #   e = Email.find(1)
58   #   e.title    # => "Superstars"
59   #   e.subject  # => "Superstars"
60   #   e.subject? # => true
61   #   e.subject = "Megastars"
62   #   e.title    # => "Megastars"
63   def alias_attribute(new_name, old_name)
64     module_eval <<-STR, __FILE__, __LINE__+1
65       def #{new_name}; self.#{old_name}; end
66       def #{new_name}?; self.#{old_name}?; end
67       def #{new_name}=(v); self.#{old_name} = v; end
68     STR
69   end
70 end
Note: See TracBrowser for help on using the browser.