4 # Encapsulates the common pattern of:
6 # alias_method :foo_without_feature, :foo
7 # alias_method :foo, :foo_with_feature
9 # With this, you simply do:
11 # alias_method_chain :foo, :feature
13 # And both aliases are set up for you.
15 # Query and bang methods (foo?, foo!) keep the same punctuation:
17 # alias_method_chain :foo?, :feature
21 # alias_method :foo_without_feature?, :foo?
22 # alias_method :foo?, :foo_with_feature?
24 # so you can safely chain foo, foo?, and foo! with the same feature.
25 def alias_method_chain(target
, feature
)
26 # Strip out punctuation on predicates or bang methods since
27 # e.g. target?_without_feature is not a valid method name.
28 aliased_target
, punctuation
= target
.to_s
.sub(/([?!=])$/, ''), $1
29 yield(aliased_target
, punctuation
) if block_given
?
31 with_method
, without_method
= "#{aliased_target}_with_#{feature}#{punctuation}", "#{aliased_target}_without_#{feature}#{punctuation}"
33 alias_method without_method
, target
34 alias_method target
, with_method
37 when public_method_defined
?(without_method
)
39 when protected_method_defined
?(without_method
)
41 when private_method_defined
?(without_method
)
46 # Allows you to make aliases for attributes, which includes
47 # getter, setter, and query methods.
51 # class Content < ActiveRecord::Base
52 # # has a title attribute
55 # class Email < Content
56 # alias_attribute :subject, :title
60 # e.title # => "Superstars"
61 # e.subject # => "Superstars"
62 # e.subject? # => true
63 # e.subject = "Megastars"
64 # e.title # => "Megastars"
65 def alias_attribute(new_name
, old_name
)
66 module_eval
<<-STR, __FILE__, __LINE__+1
67 def #{new_name}; self.#{old_name}; end # def subject; self.title; end
68 def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end
69 def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end