1

我想优化位于模块内的类中的方法,但尽管尝试优化类,但我无法运行优化的代码:

module App
  module Entities
    class User
      def self.name(name)
        puts "Original name: #{name}"
      end
    end
  end
end

module RefinedUser
  refine App::Entities::User do
    def self.name(name)
      puts "Refined name: #{name}"
    end
  end
end

class Runner
  def original
    App::Entities::User.name('Forest')
  end

  using RefinedUser

  def refined
    App::Entities::User.name('Forest')
  end
end

r = Runner.new
r.original
r.refined

输出: Original name: Forest Original name: Forest

4

1 回答 1

1

您需要使用他的singleton_class. 因为name是类方法。

App::Entities::User is ok.

module RefinedUser
  refine App::Entities::User.singleton_class do
    def name(name)
      puts "Refined name: #{name}"
    end
  end
end

using RefinedUser

class Runner
  def refined
    App::Entities::User.name('Forest')
  end
end

r = Runner.new
r.refined
=>Refined name: Forest
于 2017-01-05T11:57:32.527 回答