58

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
Rafał Cieślak
  • 972
  • 1
  • 8
  • 25
AJcodez
  • 31,780
  • 20
  • 84
  • 118

3 Answers3

75

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.

Konrad Reiche
  • 27,743
  • 15
  • 106
  • 143
7

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
Vijay Chouhan
  • 4,613
  • 5
  • 29
  • 35
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!

Matt Sanders
  • 8,023
  • 3
  • 37
  • 49