Class: NextPage::Paginator
- Inherits:
-
Object
- Object
- NextPage::Paginator
- Defined in:
- lib/next_page/paginator.rb
Overview
Paginator
Class Paginator uses the controller information to determine the model and variable name for the request, then applies a limit and offset to the query based upon the parameters or the defaults. It also extends the resource with the NextPage::PaginationAttributes mixin.
Configuration can be specified in the controller by calling ‘paginate_with`. The following overrides can be specified if necessary:
-
default_limit: limit to use if request does not specify (default value is 10)
-
instance_variable_name: default value is the controller name; for example, @photos in PhotosController
-
model_class: default derived from controller name (or path if nested); for example, Photo for PhotosController
Constant Summary collapse
- DEFAULT_LIMIT =
10
Instance Method Summary collapse
-
#initialize(controller_name, controller_path) ⇒ Paginator
constructor
A new instance of Paginator.
- #paginate(controller, page_params) ⇒ Object
- #paginate_resource(data, page_params) ⇒ Object
- #paginate_with(instance_variable_name, model_class, default_limit) ⇒ Object
Constructor Details
#initialize(controller_name, controller_path) ⇒ Paginator
Returns a new instance of Paginator.
18 19 20 21 22 23 |
# File 'lib/next_page/paginator.rb', line 18 def initialize(controller_name, controller_path) @controller_name = controller_name @controller_path = controller_path @default_limit = DEFAULT_LIMIT end |
Instance Method Details
#paginate(controller, page_params) ⇒ Object
31 32 33 34 35 36 |
# File 'lib/next_page/paginator.rb', line 31 def paginate(controller, page_params) name = "@#{instance_variable_name}" data = controller.instance_variable_get(name) || model_class.all controller.instance_variable_set(name, paginate_resource(data, page_params)) end |
#paginate_resource(data, page_params) ⇒ Object
38 39 40 41 42 43 44 |
# File 'lib/next_page/paginator.rb', line 38 def paginate_resource(data, page_params) data.extend(NextPage::PaginationAttributes) limit = page_size(page_params) offset = page_number(page_params) - 1 data.limit(limit).offset(offset * limit) end |
#paginate_with(instance_variable_name, model_class, default_limit) ⇒ Object
25 26 27 28 29 |
# File 'lib/next_page/paginator.rb', line 25 def paginate_with(instance_variable_name, model_class, default_limit) @default_limit = default_limit if default_limit.present? @instance_variable_name = instance_variable_name @model_class = model_class.is_a?(String) ? model_class.constantize : model_class end |