如何避免 Rails 中的模块冲突?
How to avoid module conflicts in Rails?
我在 rails 应用程序中有一个名为 Benchmark 的模型,尽管 ruby 在启动过程时默认需要它的 Benchmark 模块。
我是否可以卸载 Benchmark 模块以使用我的 Benchmark 模型?
您可以改为使用命名空间模型。
module Myapp
class Benchmark < ActiveRecord::Base
end
end
您可能需要指定 table 名称。
如果我是你,我会为模型起一个不同的名字,例如标准或指标或 MyBenchmark。
通常可以使用如下逻辑将 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)
最实用的解决方案是选择一个 "free" 同义词来命名您的模型。
我在 rails 应用程序中有一个名为 Benchmark 的模型,尽管 ruby 在启动过程时默认需要它的 Benchmark 模块。
我是否可以卸载 Benchmark 模块以使用我的 Benchmark 模型?
您可以改为使用命名空间模型。
module Myapp
class Benchmark < ActiveRecord::Base
end
end
您可能需要指定 table 名称。
如果我是你,我会为模型起一个不同的名字,例如标准或指标或 MyBenchmark。
通常可以使用如下逻辑将 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)
最实用的解决方案是选择一个 "free" 同义词来命名您的模型。