Created
December 2, 2010 08:28
-
-
Save masarakki/724983 to your computer and use it in GitHub Desktop.
HOW TO alias class method in ruby
This file contains 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 BaseClass | |
def self.find | |
"find" | |
end | |
end | |
# in class definition | |
class ClassA < BaseClass | |
def self.find_with_my_name | |
find_without_my_name + " ClassA" | |
end | |
class << self | |
alias_method :find_without_my_name, :find | |
alias_method :find, :find_with_my_name | |
end | |
end | |
puts ClassA.find #=> "find ClassA" | |
# AS module | |
module FindWithFeatureB | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def self.extended(base) | |
class << base | |
alias_method_chain :find, :feature_b | |
end | |
end | |
def find_with_feature_b | |
find_without_feature_b + " with feature B" | |
end | |
end | |
end | |
class ClassC < BaseClass | |
include FindWithFeatureB | |
end | |
puts ClassC.find #=> "find with feature B" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was looking for this. Thank you!