6

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

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
delpha
  • 931
  • 1
  • 8
  • 23

3 Answers3

7

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.

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
  • I have many controllers and I don't want to use that in each controller. I basicaly have 4 controllers and each one of them has to do this checking – delpha Sep 05 '15 at 14:58
  • ok, thanks, I think adding your code to the action controller will work perfectly. thanks for the inspiration :) – delpha Sep 05 '15 at 15:00
1

You can check controller actions using before_action filter:

For example in APIController:

class APIController < ApplicationController
  before_action :check_headers

  private

  def check_header
    # do whatever is required here
  end
end
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
dimakura
  • 7,575
  • 17
  • 36
0

If the header existence acts as an authentication mechanism there is no point to hit backend for that, try to avoid it earlier on reverse-proxy side:

nginx.conf

server {
  location / {
    if ($http_x_custom_header) {
      return 200 'missing the custom attribute in the header'; 
    }
    proxy_pass...
  }
}
Anatoly
  • 15,298
  • 5
  • 53
  • 77
  • well since I am building an api for that, I would not want to do that as the api might get changed in the next versions. I still want to have full controll in my code base – delpha Sep 09 '15 at 19:40
  • 1
    Ok, makes sense to have the header detection on application layer if it behaves beyond than simple check and may change later – Anatoly Sep 09 '15 at 20:03