docbrown/app/controllers/sitemaps_controller.rb
Ben Halpern bff4050c35
Add dynamic monthly sitemaps (#6704) [deploy]
* Initial sitemap work

* More sitemap progress

* Remove files

* Finalize monthly sitemap

* Update spec/models/organization_spec.rb

Co-Authored-By: Vaidehi Joshi <vaidehi.sj@gmail.com>

* Clean up approach

* Change tests

* Fix test not sure what problem was

Co-authored-by: Vaidehi Joshi <vaidehi.sj@gmail.com>
2020-03-19 17:20:23 -04:00

32 lines
1.1 KiB
Ruby

class SitemapsController < ApplicationController
before_action :set_cache_control_headers, only: %i[show]
SITEMAP_REGEX = /\Asitemap-(?<date_string>[A-Z][a-z][a-z]-\d{4})\.xml\z/.freeze
def show
match = params[:sitemap].match(SITEMAP_REGEX)
not_found unless match && match[:date_string]
begin
date = Time.zone.parse(match[:date_string]).at_beginning_of_month
rescue ArgumentError
not_found
end
@articles = Article.published.where("published_at > ? AND published_at < ? AND score > ?", date, date.end_of_month, 3).pluck(:path, :last_comment_at)
set_surrogate_controls(date)
response.headers["Surrogate-Control"] = "max-age=#{@max_age}, stale-while-revalidate=#{@stale_while_revalidate}, stale-if-error=#{@stale_if_error}"
render layout: false
end
private
def set_surrogate_controls(date)
@stale_if_error = "86400"
if date > 1.month.ago
@max_age = "8640" # one hour
@stale_while_revalidate = "43200" # half a day
else
@max_age = "259200" # three days
@stale_while_revalidate = "432000" # five days
end
end
end