Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using will_paginate without active record

Presenter:

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 in order 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 would just like to know how i could go about using will_paginate for the above case? .Thank you.

like image 743
kauschan Avatar asked Jan 14 '23 23:01

kauschan


1 Answers

Assuming @presenter.games is an Array, try this:

# 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. More docs on this can be found at https://github.com/mislav/will_paginate/blob/master/lib/will_paginate/collection.rb

like image 78
Sam Avatar answered Jan 18 '23 05:01

Sam