MxLDevs
MxLDevs

Reputation: 19506

Ruby: check if method is defined before aliasing

class Test

  def my_print
    p "Print something"
  end
end

class Test

  alias_method :old_print, :my_print
  def my_print
    old_print
    p "Print some more"
  end
end

My original Test class is at the top. I then decided to add some more to it, but I decided to alias.

But that assumes my_print is already defined. Is there a short and simple way to check whether a method I'm aliasing is already defined?

Upvotes: 6

Views: 2090

Answers (4)

Joshua Pinter
Joshua Pinter

Reputation: 47481

Use defined? Method.

You can use the defined? method to see if a method has already been defined within the current context/scope:

alias_method( :old_print, :my_print ) if defined?( my_print )

Upvotes: 0

Juan Furattini
Juan Furattini

Reputation: 803

if method(:my_print) alias_method :old_print, :my_print end

Upvotes: 0

Siwei
Siwei

Reputation: 21569

since "my_print" is not a class method , but an instance method, you should:

if Mod.instance_methods.include? "my_print"
  alias_method :old_print, :my_print
end

Upvotes: 3

Mauricio
Mauricio

Reputation: 5853

what about

if Test.method_defined? :my_print
    alias_method :old_print, :my_print
end

Upvotes: 4

Related Questions