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

Ruby

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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 - Ruby

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 - Ruby

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAJcodezView Question on Stackoverflow
Solution 1 - RubyKonrad ReicheView Answer on Stackoverflow
Solution 2 - RubyVijay ChouhanView Answer on Stackoverflow
Solution 3 - RubyMatt SandersView Answer on Stackoverflow