Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 822
delpha Avatar asked Sep 05 '15 12:09

delpha


1 Answers

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.

like image 55
Philidor Avatar answered Sep 30 '22 05:09

Philidor