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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With