Print out only headers in Rails request
ruby-on-rails
Solution
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.
Problem
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.