重构分页代码

时间:2013-01-18 06:08:53

标签: ruby-on-rails ruby pagination

我需要使用自己的分页代码,因为我的需求太多样化和具体。我已将此代码段复制并粘贴到许多控制器操作中

per_page = params[:per_page] ? params[:per_page].to_i : 15
page_num = params[:page] ? params[:page].to_i : 1
to_skip = ( page_num - 1 ) * (per_page)
max_index = per_page * page_num

我做的越多,我感觉到的是笨蛋。我确信有一种方法可以做得更好,但我不确定如何。

奖金(我可以为此奖励吗?) - >如果我需要

,我希望能够在模型中使用COMPUTED参数

示例:

# frontend requests for items 15-30

def controller_action
  # code as above
  # Item.get (...)
end

# and in the model have access to these params
def get
  # use per_page, to_skip 
end

1 个答案:

答案 0 :(得分:1)

我可能会将此作为请求过滤器放入ApplicationController

class ApplicationController < ActionController::Base
  protected
  def set_paging_params
    @per_page = params[:per_page] ? params[:per_page].to_i : 15
    @page_num = params[:page] ? params[:page].to_i : 1
    @to_skip = ( @page_num - 1 ) * (@per_page)
    @max_index = @per_page * @page_num
  end
end

class FooController < ApplicationController
  before_filter :set_paging_params, only: [:index]

  def index
    # do stuff with @per_page and others
  end
end

模型没有办法使用这些控制器实例变量,除非你明确地传递它们(或在闭包中捕获它们,但我不知道你的Item.get实现是否支持这个)。像这样:

class FooController < ApplicationController
  before_filter :set_paging_params, only: [:controller_action]

  def controller_action
    Item.get(params[:id], per_page: @per_page,
      page_num: @page_num,
      to_skip: @to_skip,
      max_index: @max_index,
    )
  end
end

class Item
  def self.get iid, opts = {}
    # use opts[:per_page] here
  end
end