使用没有活动记录的will_paginate

时间:2013-03-11 19:35:27

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

主讲人:

的应用程序/主持人/ 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?谢谢。

2 个答案:

答案 0 :(得分: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

找到

答案 1 :(得分:1)

我遇到了同样的问题,我发现了一些最简单的解决方案。

创建文件配置/初始化程序,只需要'will_paginate / array'为:

require 'will_paginate/array'

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

希望它会有所帮助。

谢谢 - TechBrains