Rails DRY mechanism to render flash messages to JSON response

dry, ruby-on-rails

Solution

I found just rendering the flash hash directly for the JSON response works well enough...

def do_stuff
  if params['stuff']

    begin
      Helper.do_stuff params['stuff']
    rescue Exception => ex
      flash[:error] = msg
    else
      flash[:success] = 'Stuff done'
    end

  else
    flash[:error] = 'No stuff provided'
  end

  respond_to do |format|
    format.html { redirect_to :action => 'index' }
    format.json do
      render json: flash
    end
  end
end

Problem

I have a very basic API in my app which also has an index page to allow testing/demonstrating various API functions. Due to this index HTML page all the functions should be able to respond in either HTML (which just re-renders the index page with flash messages attached) or JSON (which just sends back a simple status/message object). Each function currently looks a little like this... ``` def do_stuff if params['stuff'] begin Helper.do_stuff params['stuff'] rescue Exception => ex msg = ex.message status = 'error' flash[:error] = msg else msg = 'Stuff done' status = 'success' flash[:success] = msg end else msg = 'No stuff provided' status = 'error' flash[:error] = msg end respond_to do |format| format.html { render 'api/index' } format.json do render json: {:status => status, :message => msg} end end end ``` What would people recommend to DRY this up? It seems it would be good to somehow construct the JSON status object from the flash hash. I'm thinking either using a Helper or would there be something more elegant by having the logic to parse the flash hash from a JSON layout?

Original source