delpha
delpha

Reputation: 970

Display or get the HTTP header attributes in Rails 4

I have an application developed in Rails and I am trying to see the attributes in the HTTP header.

Is there any way to read these attributes? Where are they stored?

Someone mentioned request.headers. Is this correct? I am not able to see any attributes inside this array.

Upvotes: 18

Views: 21238

Answers (4)

zachaysan
zachaysan

Reputation: 1816

I've noticed in Rails 5 they now expect headers to be spelled like this in the request:

Access-Token

Before they are transformed into:

HTTP_ACCESS_TOKEN

In Rails. Doing ACCESS_TOKEN will no longer work.

Upvotes: 7

BitOfUniverse
BitOfUniverse

Reputation: 6011

You can see hash of actual http headers using @_headers in controller.

Upvotes: -3

Aetherus
Aetherus

Reputation: 8888

request.headers does not return a hash, but an instance of ActionDispatch::Http::Headers, which is a wrapper around rack env.

ActionDispatch::Http::Headers implements many methods like [] and []= which make it behave like a hash, but it doesn't override the default inspect, hence you can't see the key-value pairs by just p or pp it.

You can, however, see the request headers in the rack env:

pp request.headers.env.select{|k, _| k =~ /^HTTP_/}

Remember that the request headers in rack env are the upcased, underscored and HTTP_ prefixed version of the original http request headers.

UPDATE

Actually there are a finite set of request headers that are not prefixed HTTP_. These (capitalized and underscored) header names are stored in ActionDispatch::Http::Headers::CGI_VARIABLES. I list them below:

    AUTH_TYPE
    CONTENT_LENGTH
    CONTENT_TYPE
    GATEWAY_INTERFACE
    HTTPS
    PATH_INFO
    PATH_TRANSLATED
    QUERY_STRING
    REMOTE_ADDR
    REMOTE_HOST
    REMOTE_IDENT
    REMOTE_USER
    REQUEST_METHOD
    SCRIPT_NAME
    SERVER_NAME
    SERVER_PORT
    SERVER_PROTOCOL
    SERVER_SOFTWARE

So the full version of listing request headers would be

pp request.headers.env.select{|k, _| k.in?(ActionDispatch::Http::Headers::CGI_VARIABLES) || k =~ /^HTTP_/}

Upvotes: 48

delpha
delpha

Reputation: 970

This code solved my question request.env["HTTP_MY_HEADER"]. The trick was that I had to prefix my header's name with HTTP

Upvotes: 9

Related Questions