rubyalias-method

Ruby: alias_method for module static method


Given this module

module Test
  def self.foo(v)
    puts "Test.foo with #{v}"
  end
end

The following doesn't work

module Test  
  alias_method :bar, :foo
  # ...
end

although it works for instance methods. I get following error

NameError: undefined method `foo' for module `Test'

My goal is to override self.foo as following

def self.foo(v)
  self.bar(v + " monkey patched")
end

Is there a way to alias static method?


Solution

  • Test.singleton_class.send(:alias_method, :bar, :foo)
    Test.bar("cat")
      #=> "Test Foo with cat"