Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/28735777/print-out-only-headers-in-rails-request

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...