简体   繁体   English

在 Rails 应用程序中更改 gem 文件

[英]Change gem files in rails application

I have a rails application, I am adding an open source gem in the gemfile.我有一个 Rails 应用程序,我在 gemfile 中添加了一个开源 gem。 Most of the code in the gem works fine as per my requirement, but I need to make a few changes in the gem code to make it more useful.根据我的要求,gem 中的大部分代码都可以正常工作,但我需要对 gem 代码进行一些更改以使其更有用。

I am not including the gem code in lib because it would mean maintaining more code than required.我没有在 lib 中包含 gem 代码,因为这意味着维护的代码比需要的多。

How to I include the gem while also rewriting some of the code which replaces the gem code (only for some files)?如何在包含 gem 的同时重写一些替换 gem 代码的代码(仅适用于某些文件)?

I would just monkey patch the gem and put those patches inside $RAILS_ROOT/lib/patches/ , then require them in the config/boot.rb : 我只是猴子修补宝石,然后将这些修补程序放入$RAILS_ROOT/lib/patches/ ,然后在config/boot.rb要求它们:

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)

require 'bundler/setup' # Set up gems listed in the Gemfile.

# Apply patches
Dir[File.expand_path('../../lib/patches/*.rb', __FILE__)].each {|f| require f}

You can change Gemfile for your application and require gem with patch all together您可以为您的应用程序更改 Gemfile 并同时需要带有补丁的 gem

Example how to patch json 1.8.6 to suppress warnings for ruby 2.7.x例如如何修补 json 1.8.6 以抑制 ruby 2.7.x 的警告

Gemfile宝石文件

gem 'json', require: File.expand_path('lib/monkey_patches/json.rb', __FILE__)

lib/monkey_patch/json.rb lib/monkey_patch/json.rb

require 'json'

module JSON
  module_function

  def parse(source, opts = {})
    Parser.new(source, **opts).parse
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM