Search code examples
rubyruby-on-rails-3paginationkaminari

How to force Kaminari to always include page param?


Kaminari's URL generation omits the page param if it is generating the link back to the first page. However, the application is designed to select a random page if the page parameter is omitted. Kaminari's default behaviour, then, precludes paginating back to the first page in a reliable way.

I've resolved this issue, and will post my solution below a bit later, but I wanted to post this question for posterity, and I'm also pretty new to Rails, thus I'm not sure my solution is the best or most elegant, and I'm interested in improvements and refinements, if just for my own selfish edification!


Solution

  • The line of code in Kaminari that implements the behaviour we want to change is in lib/kaminari/helpers/tags.rb, in the method Kaminari::Helpers::Tag::page_url_for.

      def page_url_for(page)
        @template.url_for @template.params.merge(@param_name => (page <= 1 ? nil : page))
      end
    

    To override this behaviour, I created a file lib/kaminari/helpers/tag.rb, containing the following:

    module Kaminari
      module Helpers
        class Tag
          def page_url_for(page)
            @template.url_for @template.params.merge(@param_name => (page < 1 ? nil : page))
          end
        end
      end
    end
    

    I then patched in the file by adding the following line to config/initializers/extensions.rb:

    require "lib/kaminari/helpers/tag.rb"
    

    My apologies for any awkwardness with the Ruby/Rails terminology, I'm still fairly new to Ruby. Comments and criticisms are welcome.