Skip to content

Instantly share code, notes, and snippets.

@amitpatelx
Created June 11, 2017 11:50
Show Gist options
  • Save amitpatelx/2a7f44e7b26c12c6237a76713cb4a822 to your computer and use it in GitHub Desktop.
Save amitpatelx/2a7f44e7b26c12c6237a76713cb4a822 to your computer and use it in GitHub Desktop.
Move sorting and pagination logic at common place
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
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