4

主持人:

应用程序/演示者/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 %>

为了告诉 Rails 加载 apps/presenters/ 目录以及 models/、controllers/、views/ 等,请将其添加到 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 回答
1

我有同样的问题,我找到了一些最简单的解决方案。

创建文件 config/initializers 并且只需要 'will_paginate/array' 作为:

require 'will_paginate/array'

您也可以在任何其他适当的文件上要求它。它适用于任何阵列。

希望它会有所帮助。

谢谢--TechBrains

于 2013-04-09T19:11:19.833 回答