4

プレゼンター:

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

コントローラーのアクション:

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

ビュー:

<% @presenter.games.each do |game| %>
  ...
<% end %>

<%= link_to "Previous", @presenter.previous_page %>
<%= link_to "Next", @presenter.next_page %>

そして、モデル/、コントローラー/、ビュー/などとともにapps/presenters/ディレクトリをロードするようにRailsに指示するには、これをconfig/application.rbに追加します。

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

上記のケースで will_paginate を使用する方法を知りたいですか? 。ありがとうございました。

4

2 に答える 2

8

@presenter.games配列であると仮定して、これを試してください。

# 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 %>

.paginateこれにより、基本的にすべての配列にメソッドが追加されます。これに関するその他のドキュメントは、https://github.com/mislav/will_paginate/blob/master/lib/will_paginate/collection.rbにあります。

于 2013-03-11T20:19:23.230 に答える