Read more

How to organize monkey patches in Ruby on Rails projects

Henning Koch
June 16, 2016Software engineer at makandra GmbH

As your Rails project grows, you will accumulate a number of small patches. These will usually fix a bug in a gem, or add a method to core classes.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Instead of putting many files into config/initializers, I recommend to group them by gem in lib/ext:

lib/
  ext/
    factory_girl/
      mixin.rb
    carrierwave/
      change_storage.rb
      fix_cache_ids.rb
      sanitize_filename_characters.rb
    ruby/
      range/
        covers_range.rb
      array/
        dump_to_excel.rb
        xss_aware_join.rb
      enumerable/
        collect_hash.rb
        natural_sort.rb
      string/
        to_sort_atoms.rb
    rails/
      find_by_anything.rb
      form_builder.rb
      form_for_with_development_errors.rb

Note how all patches for standard library classes are in the ruby folder.

Now add a config/initializers/ext.rb that loads these files:

Dir.glob(Rails.root.join('lib/ext/**/*.rb')).sort.each do |filename|
  require filename
end
Posted by Henning Koch to makandra dev (2016-06-16 13:36)