程式扎記: [ 常見問題 ] Is there simpler (one-line) syntax to alias one class method?

標籤

2014年11月7日 星期五

[ 常見問題 ] Is there simpler (one-line) syntax to alias one class method?

Source From Here
Question
I know I can do the following, and it's just 3 lines:
  1. class << self  
  2.   alias :generate :new  
  3. end  
But out of curiosity, is there a simpler way (without semicolons) like:
  1. class_alias :generate, :new  
Answers
Since Ruby 1.9 you can use the obj.singleton_class (Returns the singleton class of obj) method to access the singleton object of a class. This way you can also access thealias_method(new_nameold_name) method. The method itself is private so you need to invoke it with send. Here is your one liner:
  1. self.singleton_class.send(:alias_method, :generate, :new)  
For example:
  1. class MyObj  
  2.     def objTest  
  3.         puts "objTest"  
  4.     end  
  5.     def MyObj.clsTest  
  6.         puts "clsTest"  
  7.     end  
  8.     self.singleton_class.send(:alias_method, :clsTest2, :clsTest)  
  9. end  
  10.   
  11. obj = MyObj.new  
  12. obj.objTest  
  13. #obj.clsTest # NoMethodError: undefined method `clsTest' ...  
  14. obj.class.clsTest  
  15. MyObj.clsTest2  
Keep in mind though, that alias will not work here.

Supplement
[ Ruby Gossip ] Basic : 類別 - 關於 self
[ 文章收集 ] alias vs alias_method


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!