开发者

perform a render from an application controller method

开发者 https://www.devze.com 2023-01-12 19:06 出处:网络
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

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' i开发者_开发百科n 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!


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
0

精彩评论

暂无评论...
验证码 换一张
取 消