0

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)?

2
  • 3
    You need to monkey patch it. Create a file in config/initializers which will override some functionality of the gem. To make it more obvious, create a folder in your lib called extensions and load it in your initializer. Note however that monkey patching has a serious downside - it might make it really hard to upgrade the gem. Commented Feb 29, 2016 at 10:33
  • Is there any other way? because I want to get regular upgrades of the gem Commented Feb 29, 2016 at 10:49

2 Answers 2

3

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}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.