# Copyright (c) 2007 John Rollin Wulff # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module CrudActions def index redirect_to :action => 'list' end def list items_per_page = (params[:items_per_page]||10).to_i page = (params[:page]||1).to_i klass.with_scope :find => { :limit => items_per_page, :offset => (items_per_page * (page - 1)) } do records = klass.find :all pset records end @paginator = ActionController::Pagination::Paginator.new self, klass.count, items_per_page, page @title = klass.to_s.humanize.pluralize end def show record = klass.find params[:id] set record @title = record.to_s end def new set klass.new(params[symbol]) @title = "New #{klass.to_s.humanize}" end def edit record = klass.find(params[:id]) set record @title = "Edit #{record}" end def create record = klass.new params[symbol] set record begin record.save! flash[:message] = "#{klass} #{record} successfully created" redirect_to :action => 'show', :id => record, :format => params[:format] rescue ActiveRecord::RecordInvalid flash[:error] = record.errors.full_messages render :action => 'new' end end def update record = klass.find params[symbol][:id] set record begin record.attributes = params[symbol] record.save! flash[:message] = "#{klass} #{record} successfully updated." redirect_to :action => 'show', :id => record, :format => params[:format] rescue ActiveRecord::RecordInvalid flash[:error] = record.errors.full_messages render :action => 'edit' end end def destroy record = klass.find params[:id] record = record.destroy flash[:message] = "#{klass} #{record} successfully destroyed." redirect_to :action => 'list' end private def pset(val) set(val, true) end def set(val, plural = false) str = klass.to_s.underscore str = str.pluralize if plural self.instance_variable_set '@' + str, val end def klass eval self.class.to_s.gsub('Controller', '') end def symbol klass.class_name.underscore.to_sym end end