gpt4 book ai didi

ruby-on-rails - 在没有事件记录的情况下使用 will_paginate

转载 作者:行者123 更新时间:2023-12-04 23:04:38 31 4
gpt4 key购买 nike

主持人:

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

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

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

为了告诉 Rails 加载 apps/presenters/目录以及模型/、 Controller /、 View /等,将其添加到 config/application.rb:
config.after_initialize do |app|
app.config.paths.add 'app/presenters', :eager_load => true
end

我只想知道如何在上述情况下使用 will_paginate ? 。谢谢。

最佳答案

假设 @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 上找到。

关于ruby-on-rails - 在没有事件记录的情况下使用 will_paginate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15347051/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com