Skip to content

Instantly share code, notes, and snippets.

@jtsagata
Created March 23, 2012 02:25
Show Gist options
  • Save jtsagata/2166281 to your computer and use it in GitHub Desktop.
Save jtsagata/2166281 to your computer and use it in GitHub Desktop.
DRY Controller Example

A DRY Controller Example

  • DRY with respond_with and respond_to
  • Use responder for i18n flash messages
  • USe responder for expiration headers
  • Default pagination
  • Use has_scope for model scopes
  • Custom record not found error
  • CSV export
<!-- app/views/gizmos_not_found.html.erb -->
<h1> Gizmo not found </h1>
<p>Can't find Any Gismo with id <%= params[:id] %> </p>
<%= link_to 'Cheaper than 10', gizmos_path(:cheap => 10) %>
<%= link_to 'recent', gizmos_path(:recent => "1") %>
<%= link_to "All Gizmos", gizmos_path %>
gem 'responders'
gem 'has_scope'
gem 'kaminari'
# TODO: Find a better gem
gem 'csv_builder'
class Gizmo < ActiveRecord::Base
scope :cheap, lambda {|price|
where("price < ?", price)
}
scope :recent, lambda { |d|
d ||= 2
where("gizmos.created_at > ?", d.to_i.days.ago)
}
end
class GizmosController < ApplicationController
has_scope :recent, :allow_blank => true
has_scope :cheap, :allow_blank => true do |contr, scope, value|
value = (value || 100).to_i
scope.cheap(value)
end
has_scope :page, default: 1, :only => :index, :unless => :csv_request?
responders :flash, :http_cache
respond_to :html, :json, :xml
respond_to :csv, :only => :index
rescue_from ActiveRecord::RecordNotFound, :with => :rescue_not_found
def index
@gizmos = apply_scopes(Gizmo).scoped
@filename = 'gizmos.csv'
@output_encoding = 'UTF-8'
@csv_options = { :force_quotes => true, :col_sep => ',' }
respond_with(@gizmos)
end
def show
@gizmo = Gizmo.find(params[:id])
respond_with(@gizmo)
end
def new
@gizmo = Gizmo.new
respond_with(@gizmo)
end
def edit
@gizmo = Gizmo.find(params[:id])
end
def create
@gizmo = Gizmo.new(params[:gizmo])
@gizmo.save
respond_with(@gizmo)
end
def update
@gizmo = Gizmo.find(params[:id])
@gizmo.update_attributes(params[:gizmo])
respond_with(@gizmo)
end
def destroy
@gizmo = Gizmo.find(params[:id])
@gizmo.destroy
respond_with(@gizmo)
end
protected
def rescue_not_found
render :partial => 'not_found', :status => :not_found
end
def csv_request?
request.format.to_s.downcase == 'text/csv'
end
end
csv << ["Name", "Price"]
@gizmos.each do |row|
csv << [row.name, row.price]
end
<%= link_to 'Cheaper than 10', gizmos_path(:cheap => 10) %>
<%= link_to 'recent', gizmos_path(:recent => "1") %>
<%= link_to "All Gizmos", gizmos_path %>
<%= link_to 'Gizmos AS CSV', gizmos_path(:format => :csv) %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment