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”

  1. Rasmus Says:

    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..

  2. Andrew Grimm Says:

    What Rasmus said ... plus it breaks the normal control flow.

  3. David Lowenfels Says:

    @andrew and @rasmus: can you propose a better solution? as long as you remember to rescue things, there is no problem.

  4. Rene A. Says:

    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 ?

Sorry, comments are closed for this article.