In my rails 4 app I'd like to response with html both for html and js request. At the moment when the request is html type the rendering works fine, but when the request is js then the html file doesn't get rendered on the screen (although in the command line it says it's rendered).
There are different scenarios for limiting requests so the throttle code can be triggered by html POST and js POST request as well.
Rack::Attack.throttle(key, limit: from_config(key, :limit), period: from_config(key, :period)) do |req|
if req.path.ends_with?(from_config(key, :path).to_s) && from_config(key, :method) == req.env['REQUEST_METHOD']
### This is the snippet I try to change the req type with but not working
if req.media_type == 'application/javascript'
req.media_type = 'text/html'
end
##### till here
req.ip
end
end
Here is what I'm trying to render. As you see this is html response.
Rack::Attack.throttled_response = lambda do |env|
[429, {}, [ActionView::Base.new.render(file: 'public/429.html', content_type: 'text/html')]]
end
What should I do?
UPDATE
This is my newest version, but can't figure out how to check the request content_type:
Rack::Attack.throttled_response = lambda do |env|
retry_after = (env['rack.attack.match_data'] || {})[10]
if env['rack.attack.content_type'] == 'text/html'
[429, {'Retry-After' => retry_after.to_s}, [ActionView::Base.new.render(file: 'public/429.html', content_type: 'text/html')]]
elsif env['rack.attack.content_type'] == 'application/javascript'
[429, {'Retry-After' => retry_after.to_s}, window.location.href = '/429.html']
end
end