views:

22

answers:

1

I need to do API version checks and so I've implemented a check in my controller method like:

if request.header["api_version"] != 1
  respond_to do |format|
    format.json {render :json => expiredMessage}
  end
  return
end

Works fine, I'm returning in the control statement so Rails doesn't complain about double render. I tried to DRY these up into an application controller method as a before_filter, but then I get the multiple renders complaint from Rails. It seems that the scope has changed such that the 'return' in the control statement no longer returns from the original controller method?

I'm wondering how I can do a render from the application controller method, or if there's a better way how can I implement this functionality? Thanks!

+1  A: 

A before filter is called before each controller action, returning from it just allows that action to proceed. I would use exceptions. (following code is untested)

class FrontEndController < ApplicationController
  rescue_from Exception do |exception|
    if exception.is_a? ExpiredException
      respond_to do |format|
        format.json {render :json => expiredMessage}
        return
      end
    end
  end

  before_filter :check_api_version
  def check_api_version
    raise ExpiredException if request.header["api_version"] != 1
  end
end

class ExpiredException < Exception; end
fullware
ah very cool, thanks
ambertch