Should I use alias or alias_method?

后端 未结 7 1759
再見小時候
再見小時候 2020-11-30 16:25

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 t

7条回答
  •  鱼传尺愫
    2020-11-30 17:04

    The rubocop gem contributors propose in their Ruby Style Guide:

    Prefer alias when aliasing methods in lexical class scope as the resolution of self in this context is also lexical, and it communicates clearly to the user that the indirection of your alias will not be altered at runtime or by any subclass unless made explicit.

    class Westerner
      def first_name
       @names.first
      end
    
     alias given_name first_name
    end
    

    Always use alias_method when aliasing methods of modules, classes, or singleton classes at runtime, as the lexical scope of alias leads to unpredictability in these cases

    module Mononymous
      def self.included(other)
        other.class_eval { alias_method :full_name, :given_name }
      end
    end
    
    class Sting < Westerner
      include Mononymous
    end
    

提交回复
热议问题