Skip to content

Instantly share code, notes, and snippets.

@callumlocke
Forked from Darep/item.rb
Created October 18, 2013 11:50
Show Gist options
  • Save callumlocke/7040471 to your computer and use it in GitHub Desktop.
Save callumlocke/7040471 to your computer and use it in GitHub Desktop.
# app/models/item.rb
require 'concerns/sortable'
class Item < ActiveRecord::Base
include Sortable
attr_accessible :title
end
# app/controllers/items_controller.rb
class ItemsController < ApplicationController
def index
@items = Item.sorted(params[:sort], params[:direction])
respond_to do |format|
format.html
format.json { render json: @items }
end
end
end
# app/models/concerns/sortable.rb
require 'active_support/concern'
module Sortable
extend ActiveSupport::Concern
module ClassMethods
def sorted(column, direction = nil)
column = map_column(column)
# Create a string to sort with (e.g. "title ASC")
sort_string = [column, direction].reject(&:blank?).join(' ')
order(sort_string)
end
private
def map_column(column)
mapping = {
# param => table column
'name' => 'title'
# etc...
}
column = mapping[column]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment