Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print out only headers in Rails request

I know how to access a header in Rails

request.headers["HEADER_NAME"] 

However, I want to get all headers passed by a browser. I see that I can enumerate it

request.headers.each { |header| ... } 

However, this will spit out both headers and other environment variables. Is there a way to get only headers?

Update 1

My problem isn't interation. My problem is distinguising between environment variables and headers. Both of them will be reported while interation using each or keys.

like image 363
Victor Ronin Avatar asked Feb 26 '15 06:02

Victor Ronin


2 Answers

Solution

By convention, headers do not usually contain dots. Nginx even rejected requests with dots in headers by default. So I think it's quite a safe assumption to go with.

On contrary, all rails environment garbage is namespaced e.g. action_dispatch.show_exceptions, rack.input etc.

These two facts conveniently suggest a way to distinguish external headers from internal variables:

request.headers.env.reject { |key| key.to_s.include?('.') } 

Works neat.


Benchmarking a bit

Note, that include?('.') implementation works about 4 times faster than matching =~ /\./

Benchmark.measure { 500000.times { hsh.reject { |key| key.to_s =~ /\./ } } }  => real=2.09 Benchmark.measure { 500000.times { hsh.reject { |key| key.to_s.include?('.') } } }  => real=0.58 

Hope that helps.

like image 197
Oleg Afanasyev Avatar answered Sep 29 '22 09:09

Oleg Afanasyev


By using

request.headers.each { |key, value|  } 

This is iterating your requested header with (key+value), but if you want specific values you have to use key name like, HTTP_KEYNAME because whenever HTTP request come it will append HTTP to keys and be sure about uppercase because it is case sensitive.

for example:

if we have passed auth_token as header request parameter and want to access, we can use this.

request.headers["HTTP_AUTH_TOKEN"] 
like image 27
Patel Maimit Avatar answered Sep 29 '22 09:09

Patel Maimit