Search code examples
ruby-on-railsrubyrails-routingruby-on-rails-4.2

Check for the existing of a header attribute in rails before invoking an action


I am building an API in rails 4. Before invoking an action, I am trying first to check whether an attribute exist in the http header. Is there a way to do that instead of checking each in all actions of the controllers. The rails documentation mentions something like

constraints(lambda { |req| req.env["HTTP_CUSTOM_HEADER"] =~ /value/ }) do
  #controller, action mapping
end

but I still want to give the user consuming my API a feedback. something like sending a json with a message stating: missing the custom attribute in the header


Solution

  • You can add before_action to the controller and check a header attribute, for example:

    class SomeController < ApplicationController
      before_action :render_message, unless: :check_header
    
      def check_header
        request.env["HTTP_CUSTOM_HEADER"] =~ /foo/
      end
    
      def render_message
        render json: { message: "missing the custom attribute in the header" }
      end
    end
    

    If check_attribute filter returns nil, then render_message action render desired message.