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

Solution 1:

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.

Solution 2:

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

Solution 3:

I don't believe there is any class-specific version of alias. I usually use it as you have previously demonstrated.

However you may want to investigate the difference between alias and alias_method. This is one of those tricky areas of ruby that can be a bit counter-intuitive. In particular the behavior of alias with regard to descendants is probably not what you expect.

Hope this helps!