Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there simpler (one-line) syntax to alias one class method?

Tags:

ruby

I know I can do the following, and it's just 3 lines:

class << self
  alias :generate :new
end

But out of curiosity, is there a simpler way (without semicolons) like:

class_alias :generate, :new
like image 242
AJcodez Avatar asked Feb 28 '13 08:02

AJcodez


2 Answers

Since Ruby 1.9 you can use the singleton_class method to access the singleton object of a class. This way you can also access the alias_method method. The method itself is private so you need to invoke it with send. Here is your one liner:

singleton_class.send(:alias_method, :generate, :new)

Keep in mind though, that alias will not work here.

like image 72
Konrad Reiche Avatar answered Sep 20 '22 15:09

Konrad Reiche


I am pasting some alias method examples

class Test
  def simple_method
    puts "I am inside 'simple_method' method"
  end

  def parameter_instance_method(param1)
    puts param1
  end

  def self.class_simple_method
    puts "I am inside 'class_simple_method'"
  end

  def self.parameter_class_method(arg)
    puts arg
  end


  alias_method :simple_method_new, :simple_method

  alias_method :parameter_instance_method_new, :parameter_instance_method

  singleton_class.send(:alias_method, :class_simple_method_new, :class_simple_method)
  singleton_class.send(:alias_method, :parameter_class_method_new, :parameter_class_method)
end

Test.new.simple_method_new
Test.new.parameter_instance_method_new("I am parameter_instance_method")

Test.class_simple_method_new
Test.parameter_class_method_new(" I am parameter_class_method")

OUTPUT

I am inside 'simple_method' method
I am parameter_instance_method
I am inside 'class_simple_method'
I am parameter_class_method
like image 45
Vijay Chouhan Avatar answered Sep 21 '22 15:09

Vijay Chouhan