【问题标题】:How to avoid module conflicts in Rails?如何避免 Rails 中的模块冲突?
【发布时间】:2017-07-04 10:39:14
【问题描述】:

我在 Rails 应用中有名为 Benchmark 的模型,尽管 ruby​​ 在启动进程时默认需要它的 Benchmark 模块。

我是否可以卸载 Benchmark 模块以使用我的 Benchmark 模型?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord activemodel


    【解决方案1】:

    您可以改用命名空间模型。

    module Myapp
      class Benchmark < ActiveRecord::Base
      end
    end
    

    您可能需要指定表名。

    如果我是你,我会为模型取一个不同的名称,例如标准或指标或 MyBenchmark。

    【讨论】:

      【解决方案2】:

      通常可以使用如下逻辑解除 Ruby 常量与其原始名称的绑定:

      require "benchmark"
      
      BM = Benchmark
      Object.send(:remove_const, :Benchmark)
      
      class Benchmark
        def initialize
          puts "Hey, I'm your custom Benchmark"
        end
      
        ...
      end
      

      但是,特别是对于最初的 Benchmark 实现,这是行不通的,因为它在内部充满了像这样的名称引用:

      @list << res = Benchmark.measure(label, &blk)
      

      最好的实用解决方案是选择一个“免费”的同义词来命名您的模型。

      【讨论】:

        猜你喜欢
        • 2011-12-31
        • 1970-01-01
        • 1970-01-01
        • 2019-08-11
        • 1970-01-01
        • 2011-07-02
        • 2018-02-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多