How to access request headers only in rails 2 application?

Rails provides a request.headers method that returns both headers and a lot of extra information other than the header ... I would like to access only the request headers, how can I do this?

Hi

+3
source share
1 answer

You essentially need to highlight all environment entries that have a prefix HTTP_or CONTENT_that match your HTTP headers, for example:

# CONTENT_LENGTH -> Content-Length
# HTTP_COOKIE -> Cookie
# HTTP_USER_AGENT -> User-Agent
@headers |= request.env.inject({}) { |h, (k, v)|
  if k =~ /^(HTTP|CONTENT)_/ then
    h[k.sub(/^HTTP_/, '').dasherize.gsub(/([^\-]+)/) { $1.capitalize }] = v 
  end
  h
}

HTTP-, , , , CONTENT_BLA HTTP_DUMMY.

@headers |= %w[ CONTENT_LENGTH CONTENT_TYPE HTTP_ACCEPT
HTTP_REFERER HTTP_USER_AGENT ].inject({}) { |h, k|
  if v = request.env[k] then
    h[k.sub(/^HTTP_/, '').dasherize.gsub(/([^\-]+)/) { $1.capitalize }] = v 
  end
  h
}

actionpack/lib/action_controller/request.rb, , .

+5

Source: https://habr.com/ru/post/1734714/


All Articles