Alias class methods in Ruby

Yesterday I came across a problem where one possible solution was to alias a class method. I’ve blogged about aliasing methods before, but I didn’t know how to do this for class methods.

Turns out, it’s pretty simple – the syntax is just a bit different.

class Person
  def self.all
    %w{ Bob Steve }
  end
  
  class << self
    alias_method :old_all, :all
    
    def all
      old = self.old_all
      old << "Peter"
      old << "Owen"
    end
  end
end

p Person.old_all
# ["Bob", "Steve"]

p Person.all
# ["Bob", "Steve", "Peter", "Owen"]

Happy coding.