Skip to content

Instantly share code, notes, and snippets.

@dguettler
Created June 19, 2011 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dguettler/1033736 to your computer and use it in GitHub Desktop.
Save dguettler/1033736 to your computer and use it in GitHub Desktop.
# app/controllers/books/base_controller.rb
class BooksController < ApplicationController
respond_to :html
before_filter :find_resource, :only => [:show, :edit, :update, :destroy]
def index
@books = context.page params[:page]
end
def show
end
def new
@book = context.new
end
def edit
end
def create
@book = context.new(params[:book])
# Save the last donor to speed up the process
session[:donor_id] = @book.donor_id
## Should be handled by Book class
# unless @book.isbn.blank?
# @book.attributes = OCLC.find_by_isbn(@book.isbn)
# @book.attributes = AMZN.find_by_isbn(@book.isbn)
# end
if @book.save
flash[:notice] = 'You successfully added a book.'
redirect_to :action => 'show', :id => @book.id
else
render :new
end
end
def update
if @book.update_attributes(params[:book])
flash[:notice] = case @book.recommendation
when 'keep'
"The book's recommendation has been updated to: keep."
when 'toss'
"The book's recommendation has been updated to: toss."
when 'undecided'
"The book's recommendation has been updated to: undecided."
else
"You successfully updated the book."
end
redirect_to :action => 'show', :id => @book.id
else
render :edit
end
end
def destroy
if @book.destroy
flash[:notice] = 'You successfully deleted the book.'
redirect_to :action => 'index'
else
flash[:error] = 'There was a problem removing the book. Please try again.'
redirect_to :action => 'index'
end
end
protected
def find_resource
@book = context.find(params[:id])
end
def current_context
if params[:bin_id]
Bin.find(params[:bin_id]).books
elsif params[:donor_id]
Donor.find(params[:donor_id]).books
else
Book
end
end
def context
@_context ||= current_scope ? current_context.send(current_scope) : current_context
end
def current_scope
Book.scopes.keys.include?(params[:scope].try(:to_sym)) ? params[:scope] : nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment