3

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?

Nakilon
  • 34,866
  • 14
  • 107
  • 142
chepukha
  • 2,371
  • 3
  • 28
  • 40
  • I thought you simply wanted to alias a class method with another class method (I provided an answer that does that). However, I don't understand your comment your goal to override `foo` in a particular way. Could you please clarify that, preferably with an edit. – Cary Swoveland Jun 15 '17 at 22:42
  • So, there's existing module Test, whose method **foo** I want to override. But I want to use the existing implementation and just slightly change, e.g. augmenting the arguments. Your solution works for me actually. – chepukha Jun 15 '17 at 22:52

1 Answers1

2
Test.singleton_class.send(:alias_method, :bar, :foo)
Test.bar("cat")
  #=> "Test Foo with cat"
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100