How to organize monkey patches in Ruby on Rails projects

Updated . Posted . Visible to the public. Repeats.

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.

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
Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2016-06-16 11:36)