From 7623cb7d1c6be61d6eb3f74bb71bad6218a307e5 Mon Sep 17 00:00:00 2001 From: Adam Coffman Date: Fri, 22 Dec 2017 16:30:02 -0600 Subject: [PATCH] Share sorting clause code between controllers. Fixes sorting events on user activity page. --- app/controllers/concerns/with_sorting.rb | 13 +++++++++++++ app/controllers/events_controller.rb | 16 +++------------- app/controllers/users_controller.rb | 3 ++- 3 files changed, 18 insertions(+), 14 deletions(-) create mode 100644 app/controllers/concerns/with_sorting.rb diff --git a/app/controllers/concerns/with_sorting.rb b/app/controllers/concerns/with_sorting.rb new file mode 100644 index 00000000..568ddf61 --- /dev/null +++ b/app/controllers/concerns/with_sorting.rb @@ -0,0 +1,13 @@ +module WithSorting + extend ActiveSupport::Concern + + def sort_direction(field_name) + if params["sorting"].blank? + 'DESC' + elsif params["sorting"][field_name].present? && params["sorting"][field_name].upcase == 'DESC' + 'DESC' + else + 'ASC' + end + end +end diff --git a/app/controllers/events_controller.rb b/app/controllers/events_controller.rb index c15ac1b7..e85ad239 100644 --- a/app/controllers/events_controller.rb +++ b/app/controllers/events_controller.rb @@ -1,24 +1,14 @@ class EventsController < ApplicationController + include WithSorting + actions_without_auth :index def index events = Event.includes(:originating_user, :subject) .page(params[:page]) .per(params[:count]) - .order("events.created_at #{sort_clause}") + .order("events.created_at #{sort_direction('timestamp')}") render json: EventsPresenter.new(events) end - - - private - def sort_clause - if params["sorting"].blank? - 'DESC' - elsif params["sorting"]["timestamp"].present? && params["sorting"]["timestamp"].upcase == 'DESC' - 'DESC' - else - 'ASC' - end - end end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 48e23335..2632b72e 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,5 +1,6 @@ class UsersController < ApplicationController include WithSoftDeletion + include WithSorting actions_without_auth :events, :show, :index, :username_suggestions, :username_status @@ -17,7 +18,7 @@ def events .includes(:subject) .page(params[:page]) .per(params[:count]) - .order('created_at DESC') + .order("events.created_at #{sort_direction('timestamp')}") render json: EventsPresenter.new(events) end