覆盖gem模块的方法

时间:2013-07-12 08:53:47

标签: ruby-on-rails ruby monkeypatching

我需要覆盖gem“omnicontacts”的方法“email_to_name”,因为它不适用于ruby 1.8.7。 我在这个方法中使用命名正则表达式有错误

lib/omnicontacts/parse_utils.rb:32: undefined (?...) sequence: /(?<first>[a-z|A-Z]+)[\.|_](?<last>[a-z|A-Z]+)/ (SyntaxError)

此方法位于模块ParseUtils

module OmniContacts
  module ParseUtils
    def email_to_name username_or_email
      ...
    end
  end
end

然后在其他模块中需要

require "omnicontacts/parse_utils"
require "omnicontacts/middleware/oauth2"
require "json"

module OmniContacts
  module Importer
    class Gmail < Middleware::OAuth2
      include ParseUtils
    end
  end
end

我试图覆盖此方法,但它不起作用:

#config/initializer/omnicontacts.rb
require "omnicontacts"

module OmniContacts
  module ParseUtils
    def email_to_name username_or_email
      p "test"
    end
  end
end

module OmniContacts
  module Importer
    class Gmail
      module ParseUtils
        def email_to_name username_or_email
          p "test"
        end
      end
    end
  end
end

ActionController::Dispatcher.middleware.use OmniContacts::Builder do
  importer :gmail, "test", "test", {:redirect_path => "/contacts/gmail/callback"}
  importer :yahoo, "test", "test", {:callback_path => '/contacts/yahoo/callback'}
end

我使用rails 2和ruby 1.8.7

2 个答案:

答案 0 :(得分:0)

你确定你的猴子补丁是在宝石后加载的吗?因为如果它在gem之前加载,gem的实现将覆盖你的。

答案 1 :(得分:0)

我将文件lib / omnicontacts / parse_utils.rb添加到我的项目中,它从gem覆盖了这样的文件。它解决了问题,但它似乎不是很好的解决方案,因为我只是分叉宝石并在那里添加所需的更改。

相关问题