Skip to content

Instantly share code, notes, and snippets.

@Darep
Created January 24, 2013 19:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Darep/4626622 to your computer and use it in GitHub Desktop.
Save Darep/4626622 to your computer and use it in GitHub Desktop.
Ruby on Rails concern example: making an ActiveRecord item sortable. Adapted from: http://say26.com/show-us-your-production-code-1-concerns
# 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