How to use Module.prepend to override class method in Ruby

Prem Sichanugrist
Sikachu's Blog
Published in
1 min readNov 23, 2017

--

In Ruby 2.0, you can use Module.prepend in place of alias_method_chain to override a method in another class:

class A
def say_hello
puts "Hello from A"
end
end
module B
def say_hello
puts "Hello from B"
super
end
end
A.send :prepend, B> A.new.say_hello
Hello from B
Hello from A

However, it wasn’t clear how to override class method:

module B
def self.say_hello
puts "Hello from B"
super
end
end
A.send :prepend, B> A.say_hello
Hello from A

It turned out all you need to do is to call prepend on A’s singleton_class instead:

class A
def self.say_hello
puts "Hello from A"
end
end
module B
def say_hello
puts "Hello from B"
super
end
end
A.singleton_class.send :prepend, B> A.say_hello
Hello from B
Hello from A

(However, note that say_hello in the last example is now defined as instance method instead of module method.)

--

--

Senior Developer at Degica. I also contribute to open source projects, mostly in Ruby.