Skip to content

Instantly share code, notes, and snippets.

@masarakki
Created December 2, 2010 08:28
Show Gist options
  • Save masarakki/724983 to your computer and use it in GitHub Desktop.
Save masarakki/724983 to your computer and use it in GitHub Desktop.
HOW TO alias class method in ruby
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"
@alejomongua
Copy link

I was looking for this. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment