0

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

Thermatix
  • 2,757
  • 21
  • 51

3 Answers3

2

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'
Community
  • 1
  • 1
Thermatix
  • 2,757
  • 21
  • 51
1

I bet you call alias_method inside the scope of Sinatra::Base. You should call it inside the singleton class of Sinatra::Base, because the method get is defined as a class method.

Aetherus
  • 8,720
  • 1
  • 22
  • 36
0

The syntax is:

alias_method :new_name, :func_name

E.g., you have a name attribute in a record:

alias_method :to_s, :name
Jaffa
  • 12,442
  • 4
  • 49
  • 101
  • `old_name` & `func_name` are variables storing values, in this case: `old_name = :old_get` & `func_name = :get`. Oddly when I try to instead store the old method as an `UnBoundMethod` using `instance_method(func_name)` it errors with the same Error (that the method doesn't exist) however doing `puts Sinatra::Base.methods.sort.to_s` shows that the method `:get` does indeed exist. – Thermatix May 11 '15 at 17:13