Created
June 11, 2017 11:50
-
-
Save amitpatelx/2a7f44e7b26c12c6237a76713cb4a822 to your computer and use it in GitHub Desktop.
Move sorting and pagination logic at common place
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def paginated(resources, per_page=Settings.pagination.default) | |
resources.page(params[:page]).per(per_page) | |
end | |
def sort_by_options(resources) | |
resources.order("#{sort_column(resources.first.class)} #{sort_direction}") | |
end | |
def sort_and_paginate(resources) | |
paginated(sort_by_options(resources)) | |
end | |
def sort_column(resource, default_column = "created_at") | |
if resource.present? && resource != NilClass | |
resource.column_names.include?(params[:sort]) ? params[:sort] : default_column | |
else | |
default_column | |
end | |
end | |
def sort_direction | |
%w[asc desc].include?(params[:direction]) ? params[:direction] : 'desc' | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def index | |
sort_and_paginate(Products.selling_fast) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment