Print out only headers in Rails request

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)