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
4 Responses to “rails flash error notifications from the model”
Sorry, comments are closed for this article.

May 4th, 2008 at 03:02 PM
In my opinion you shouldn't use exceptions in the "normal flow" of the application. Exceptions are... well.. exceptions. The pop up when something is not right.
Using exceptions to raise a FlashSuccess is rather.. well... Not nice..
May 7th, 2008 at 11:47 PM
What Rasmus said ... plus it breaks the normal control flow.
May 22nd, 2008 at 07:21 PM
@andrew and @rasmus: can you propose a better solution? as long as you remember to rescue things, there is no problem.
July 21st, 2008 at 02:59 PM
Better then nothing.
I just hit the problem myself - I'm using a before_destroy callback handle and want to pass an "ok"/"not okay" message up from the model.
Since there is no flash available - what else can you do, then just Raise an Exception ?