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


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...