Created
May 26, 2014 08:17
-
-
Save v2e4lisp/832e31dade7da8924883 to your computer and use it in GitHub Desktop.
rails / activesupport / lib / active_support / core_ext / module / aliasing.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Module | |
def alias_method_chain(target, feature) | |
# Strip out punctuation on predicates or bang methods since | |
# e.g. target?_without_feature is not a valid method name. | |
aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1 | |
yield(aliased_target, punctuation) if block_given? | |
with_method = "#{aliased_target}_with_#{feature}#{punctuation}" | |
without_method = "#{aliased_target}_without_#{feature}#{punctuation}" | |
alias_method without_method, target | |
alias_method target, with_method | |
share_access_modifier target, without_method | |
end | |
def share_access_modifier(new_method, old_method) | |
modifier = access_modifier(old_method) | |
modifier and __send__(modifier, new_method) | |
end | |
def access_modifier(method_name) | |
case | |
when public_method_defined?(method_name) | |
:public | |
when protected_method_defined?(method_name) | |
:protected | |
when private_method_defined?(method_name) | |
:private | |
end | |
end | |
def alias_attribute(new_name, old_name) | |
module_eval <<-STR, __FILE__, __LINE__ + 1 | |
def #{new_name}; self.#{old_name}; end # def subject; self.title; end | |
share_access_modifier(#{new_name}, #{old_name}) | |
STR | |
respond_to?("#{old_name}?") and module_eval <<-STR, __FILE__, __LINE__ + 1 | |
def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end | |
share_access_modifier(#{new_name}?, #{old_name}?) | |
STR | |
respond_to?("#{old_name}=") and module_eval <<-STR, __FILE__, __LINE__ + 1 | |
def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end | |
share_access_modifier(#{new_name}=, #{old_name}=) | |
STR | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment