猴子补丁包含在Ruby宝石中的Mongoid模型

时间:2015-01-16 14:39:32

标签: ruby mongoid monkeypatching

我有一个包含一些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(地址)时(例如),我得到NoMethodError

1 个答案:

答案 0 :(得分:0)

我想我现在已经钉了这个。我没有把猴子补丁放在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'

我仍然有兴趣知道为什么这有效