如何从模块内的类中细化方法

时间:2017-01-05 11:05:33

标签: ruby refinements

我想改进一个位于模块内的类中的方法,但是尽管尝试优化类,但我无法运行精炼的代码:

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

1 个答案:

答案 0 :(得分:1)

您需要使用singleton_class优化App :: Entities :: User。因为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