Search code examples
rubyrespond-to

Trying to alias old method and create new one in ruby


I'm using the following snippet to only alias the method if the method exists:

alias_method old_name, func_name if self.respond_to? func_name

How can it Error with alias_method': undefined method 'get' for class 'Sinatra::Base' (NameError) when self.respond_to? func_name returns true?

func_name = :get in this snippet


Solution

  • I found a good answer to my problem here at this link

    Instead of monkey patching the original class I instead create a module and then use prepend and just call super to call the original method. I now do this:

    Sinatra::Base.prepend Restman::Patches::Sinatra_Base_Patch
    

    With the module Sinatra_Base_Patch containing the function that overwrites the original.

    The example I followed is this:

    class Foo
      def bar
        'Hello'
      end
    end 
    
    module FooExtensions
      def bar
        super + ' World'
      end
    end
    
    class Foo
      prepend FooExtensions # the only change to above: prepend instead of include
    end
    
    Foo.new.bar # => 'Hello World'