Writing Clean Monkey Patches-in-ruby

Posted By Weston Ganger

I recently did bundle update on a project. I later noticed that the pagination was giving me an error:

# config/initializers/kaminari_monkey_patch.rb

require 'kaminari/version'

if Kaminari::VERSION == "1.0.0"

  Kaminari::PageScopeMethods.module_eval do
    prepend(KaminariFix = Module.new do    

      def per(num, max_per_page: nil)
        if num && num.is_a?(String)
          num = num.to_i 
        end

        super # or you can do `super(num, max_per_page: max_per_page)` which is the same thing
      end

    end)
  end

else
  Rails.logger.debug("WARNING: You are running Kaminari #{Kaminari::VERSION}. The monkey patch located at config/initializers/kaminari_monkey_patch.rb only applies to 1.0.0, so please remove the monkey patch if you are seeing this message.")
  ### or maybe you might rather raise an error instead, its totally up to you
end

This fixed the problem splendidly.

I hope this encourages you to monkey patch more often, it can help solve large issues with ease. I also hope it makes you love Ruby just a little more.

Note 1: Yes, the parenthesis ( ) for the prepend call are required when using this inline style. If you do not use the parenthesis it will fail silently and the patch will not be applied.

Note 2: If your having a hard time understanding the monkey patch then I recommend you read the following article: https://bibwild.wordpress.com/2016/12/27/a-class_eval-monkey-patching-pattern-with-prepend/

Related External Links:

Article Topic:Software Development - Ruby / Rails

Date:January 17, 2017