Have you ever wanted to refactor something into the model ( skinny controller, fat model ) but didn’t know how to deal with your flash notifications?
Here’s a solution that I cooked up:
module FlashExceptions
class FlashException < StandardError; end
class FlashError < FlashException; end
class FlashNotice < FlashException; end
class FlashSuccess < FlashException; end
end
###########################################
class Model < ActiveRecord::Base
include FlashExceptions
def self.do_something! opts = {}
raise FlashError, opts[:error] if opts[:error]
raise FlashNotice, opts[:notice] if opts[:notice]
raise FlashSuccess, opts[:success] if opts[:success]
end
end
###########################################
class Controller < ApplicationController
def action
Model.do_something! :error => 'oops!', :notice => 'ahem.', :success => 'yay!'
rescue FlashException => e
flash[ e.class.underscore.split('_').last ] = e.message
end
end
