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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With