Commit ab3dabe3

mo khan <mo@mokhan.ca>
2014-10-02 03:41:58
sort sessions by different fields.
1 parent 393a28e
Changed files (3)
app
controllers
models
views
admin
app/controllers/admin/sessions_controller.rb
@@ -1,12 +1,44 @@
 module Admin
   class SessionsController < AdminController
     def index
-      @user_sessions = UserSession.includes(:user, :location).order(created_at: :desc).all
+      @user_sessions = sessions.filter_by(search_filters)
+      @direction = params[:direction].present? ? directions[params[:direction].to_sym] : :asc
     end
 
     def destroy
       UserSession.find(params[:id]).revoke!
       redirect_to admin_sessions_path
     end
+
+    private
+
+    def sessions
+      UserSession.includes(:user, :location)
+    end
+
+    def search_filters
+      [sort_filter]
+    end
+
+    def sort_filter
+      direction = params[:direction].present? ? params[:direction].to_sym : :asc
+      case params[:sort].try(:downcase)
+      when "ip"
+        ->(sessions) { sessions.order(ip: direction) }
+      when 'city'
+        ->(sessions) { sessions.joins(:location).order("locations.city #{direction}") }
+      when 'ua'
+        ->(sessions) { sessions.order(user_agent: direction) }
+      else
+        ->(sessions) { sessions.order(created_at: :desc) }
+      end
+    end
+
+    def directions
+      {
+        asc: :desc,
+        desc: :asc,
+      }
+    end
   end
 end
app/models/user_session.rb
@@ -35,6 +35,10 @@ class UserSession < ActiveRecord::Base
     def authenticate(key)
       self.active.find_by(key: key)
     end
+
+    def filter_by(filters)
+      filters.inject(all) { |chain, filter| filter.call(chain) }
+    end
   end
 
   private
app/views/admin/sessions/index.html.erb
@@ -8,13 +8,13 @@
       <thead>
         <tr>
           <td>user</td>
-          <td>ip</td>
-          <td>city</td>
-          <td>user agent</td>
+          <td><%= link_to "ip", admin_sessions_path(sort: 'ip', direction: @direction) %></td>
+          <td><%= link_to "city", admin_sessions_path(sort: 'city', direction: @direction) %></td>
+          <td><%= link_to "user agent", admin_sessions_path(sort: 'ua', direction: @direction) %></td>
+          <td>device</td>
           <td>browser</td>
+          <td>os</td>
           <td>version</td>
-          <td>platform</td>
-          <td>platform version</td>
           <td>accessed at</td>
           <td>revoked at</td>
           <td></td>