Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use alias or alias_method?

Tags:

alias

ruby

I found a blog post on alias vs. alias_method. As shown in the example given in that blog post, I simply want to alias a method to another within the same class. Which should I use? I always see alias used, but someone told me alias_method is better.

Usage of alias

class User    def full_name     puts "Johnnie Walker"   end    alias name full_name end  User.new.name #=>Johnnie Walker 

Usage of alias_method

class User    def full_name     puts "Johnnie Walker"   end    alias_method :name, :full_name end  User.new.name #=>Johnnie Walker 

Blog post link here

like image 323
ma11hew28 Avatar asked Jan 21 '11 19:01

ma11hew28


People also ask

What does Alias_method do Ruby?

To alias a method or variable name in Ruby is to create a second name for the method or variable. Aliasing can be used either to provide more expressive options to the programmer using the class or to help override methods and change the behavior of the class or object.

What is Alias_attribute?

alias_attribute is a method provided by Rails that is both a getter and setter method. alias_attribute is the only one that also aliases question and setting methods (they will not work if you use alias or alias_method). Use alias_attribute if you are trying to alias a Rails attribute.


2 Answers

alias_method can be redefined if need be. (it's defined in the Module class.)

alias's behavior changes depending on its scope and can be quite unpredictable at times.

Verdict: Use alias_method - it gives you a ton more flexibility.

Usage:

def foo   "foo" end  alias_method :baz, :foo 
like image 94
Jacob Relkin Avatar answered Sep 19 '22 21:09

Jacob Relkin


Apart from the syntax, the main difference is in the scoping:

# scoping with alias_method class User    def full_name     puts "Johnnie Walker"   end    def self.add_rename     alias_method :name, :full_name   end  end  class Developer < User   def full_name     puts "Geeky geek"   end   add_rename end  Developer.new.name #=> 'Geeky geek' 

In the above case method “name” picks the method “full_name” defined in “Developer” class. Now lets try with alias.

class User    def full_name     puts "Johnnie Walker"   end    def self.add_rename     alias name full_name   end end  class Developer < User   def full_name     puts "Geeky geek"   end   add_rename end  Developer.new.name #=> 'Johnnie Walker' 

With the usage of alias the method “name” is not able to pick the method “full_name” defined in Developer.

This is because alias is a keyword and it is lexically scoped. It means it treats self as the value of self at the time the source code was read . In contrast alias_method treats self as the value determined at the run time.

Source: http://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html

like image 45
Darme Avatar answered Sep 18 '22 21:09

Darme