Should I use alias or alias_method?

后端 未结 7 1736
再見小時候
再見小時候 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 16:58

    I think there is an unwritten rule (something like a convention) that says to use 'alias' just for registering a method-name alias, means if you like to give the user of your code one method with more than one name:

    class Engine
      def start
        #code goes here
      end
      alias run start
    end
    

    If you need to extend your code, use the ruby meta alternative.

    class Engine
      def start
        puts "start me"
      end
    end
    
    Engine.new.start() # => start me
    
    Engine.class_eval do
      unless method_defined?(:run)
        alias_method :run, :start
        define_method(:start) do
          puts "'before' extension"
          run()
          puts "'after' extension"
        end
      end
    end
    
    Engine.new.start
    # => 'before' extension
    # => start me
    # => 'after' extension
    
    Engine.new.run # => start me
    

提交回复
热议问题