简体   繁体   中英

Change gem files in rails application

I have a rails application, I am adding an open source gem in the gemfile. 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.

I am not including the gem code in lib because it would mean maintaining more code than required.

How to I include the gem while also rewriting some of the code which replaces the gem code (only for some files)?

I would just monkey patch the gem and put those patches inside $RAILS_ROOT/lib/patches/ , then require them in the 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

Example how to patch json 1.8.6 to suppress warnings for ruby 2.7.x

Gemfile

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

lib/monkey_patch/json.rb

require 'json'

module JSON
  module_function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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