Using will_paginate without an active record

Leading:

app / Presenters / games_presenter.rb

class GamesPresenter attr_reader :games, :next_page, :previous_page def initialize json @games = json['machine-games'] paging = json['paging'] if paging && paging['next'] next_page_query = paging['next'].match(/\?.*/)[0] @next_page = "/machine_games/search#{next_page_query}" end if paging && paging['previous'] previous_page_query = paging['previous'].match(/\?.*/)[0] @previous_page = "/machine_games/search#{previous_page_query}" end end end 

Controller action:

 def show # ... @presenter = GamesPresenter.new(json) end 

Views:

 <% @presenter.games.each do |game| %> ... <% end %> <%= link_to "Previous", @presenter.previous_page %> <%= link_to "Next", @presenter.next_page %> 

And to tell Rails to load the apps / presenters / directory along with models /, controllers /, views, etc., add this to config / application.rb:

 config.after_initialize do |app| app.config.paths.add 'app/presenters', :eager_load => true end 

I just wanted to know how can I use will_paginate for the above case? Thank you.

+4
source share
2 answers

Assuming @presenter.games is an array, try the following:

 # Gemfile gem 'will_paginate' # /config/initializers/will_paginate_array.rb require 'will_paginate/collection' Array.class_eval do def paginate(page = 1, per_page = 15) page = 1 if page.blank? # To fix weird params[:page] = nil problem WillPaginate::Collection.create(page, per_page, size) do |pager| pager.replace self[pager.offset, pager.per_page].to_a end end end # /app/controllers/games_controller.rb def show @presenter = GamesPresenter.new(json) @games = @presenter.games.paginate(params[:page], 5) end # /app/views/games/index.html.erb <% @games.each do |game| %> ... <% end %> <%= will_paginate @games %> 

This basically adds the .paginate method to all arrays. Additional documents on this can be found at https://github.com/mislav/will_paginate/blob/master/lib/will_paginate/collection.rb

+8
source

I had the same problem and found some simplest solution.

Create the file configuration / initializers and simply require "will_paginate / array" as:

require 'will_paginate/array'

You can also request it in any other relevant file. It will work on any array.

Hope this helps.

Thanks - TechBrains

+1
source

All Articles