【问题标题】:Monkey Patching Mongoid models contained in a Ruby gemRuby gem 中包含的 Monkey Patching Mongoid 模型
【发布时间】:2015-01-16 14:39:32
【问题描述】:

我有一个包含一些 Mongoid 模型的 Ruby gem which gets used across multiple projects

我目前正在尝试在一个项目中重用它们并修补一些额外的方法。但是,当我需要项目并运行测试时。我得到一个NoMethodError。有什么想法我哪里出错了吗?

这是我的主要项目文件:

require 'bundler'
Bundler.require(:default)

require 'mongoid-elasticsearch'
Mongoid::Elasticsearch.prefix = ENV["MONGOID_ENVIRONMENT"]

require 'mongoid_address_models/require_all' # This is where I include my gem

Mongoid.load!(File.join(File.dirname(__FILE__), "..", "config", "mongoid.yml"), ENV["MONGOID_ENVIRONMENT"] || :development)

# Here are my monkey patched models
require 'models/street'
require 'models/locality'
require 'models/town'
require 'models/postcode'

require 'sorting_office/address'

module SortingOffice
end

这是猴子修补模型之一的示例

class Postcode

  REGEX = /([A-PR-UWYZ01][A-Z01]?[0-9IO][0-9A-HJKMNPR-YIO]\s?[0-9IO][ABD-HJLNPQ-Z10]{2})/i

  def self.calculate(address)
    postcode = UKPostcode.new(address.match(REGEX)[0])
    where(name: postcode.norm).first
  end

end

当我调用 Postcode.calculate(address)(例如)时,我得到一个 NoMethodError

【问题讨论】:

    标签: ruby mongoid monkeypatching


    【解决方案1】:

    我想我现在已经搞定了。我没有将猴子补丁放在lib/models 中,而是将它们移至lib/sorting_office/models 并要求它们:

    require 'sorting_office/models/street'
    require 'sorting_office/models/locality'
    require 'sorting_office/models/town'
    require 'sorting_office/models/postcode'
    

    我仍然很想知道为什么这会奏效

    【讨论】:

      猜你喜欢
      • 2013-06-11
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 2013-12-28
      • 2014-06-11
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多