user2851669
user2851669

Reputation:

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

Upvotes: 0

Views: 755

Answers (2)

Volodymyr
Volodymyr

Reputation: 1186

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

Upvotes: 0

Aetherus
Aetherus

Reputation: 8888

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}

Upvotes: 3

Related Questions