Allow pages to render .txt requests (#20547)

* Allow pages to render .txt requests

* Adjust routes
This commit is contained in:
Ben Halpern 2024-01-22 11:12:22 -05:00 committed by GitHub
parent b593ecd323
commit d86689f63d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 28 additions and 5 deletions

View file

@ -4,10 +4,12 @@ class PagesController < ApplicationController
def show
@page = Page.find_by!(slug: params[:slug])
not_found unless FeatureFlag.accessible?(@page.feature_flag_name, current_user)
not_found_conditions
set_surrogate_key_header "show-page-#{params[:slug]}"
case @page.template
when "txt"
render plain: @page.processed_html, content_type: "text/plain"
when "json"
render json: @page.body_json
when "css"
@ -129,4 +131,9 @@ class PagesController < ApplicationController
redirect_to(notifications_path)
end
end
def not_found_conditions
not_found unless FeatureFlag.accessible?(@page.feature_flag_name, current_user)
not_found if params[:format] == "txt" && @page.template != "txt"
end
end

View file

@ -1,6 +1,6 @@
class Page < ApplicationRecord
extend UniqueAcrossModels
TEMPLATE_OPTIONS = %w[contained full_within_layout nav_bar_included json css].freeze
TEMPLATE_OPTIONS = %w[contained full_within_layout nav_bar_included json css txt].freeze
TERMS_SLUG = "terms".freeze
CODE_OF_CONDUCT_SLUG = "code-of-conduct".freeze

View file

@ -394,8 +394,10 @@ Rails.application.routes.draw do
get "/:username/:slug", to: "stories#show"
get "/:sitemap", to: "sitemaps#show",
constraints: { format: /xml/, sitemap: /sitemap-.+/ }
get "/:username", to: "stories#index", as: "user_profile"
get "/:username", to: "stories#index", as: "user_profile", # No txt format
constraints: { format: /html/ }
get "/:slug", to: "pages#show",
constraints: { format: /txt/ }
root "stories#index"
end
end

View file

@ -45,6 +45,20 @@ RSpec.describe "Pages" do
end
end
describe "GET /:slug.txt" do
it "renders proper text file when template is txt" do
page = create(:page, title: "Text page", body_html: "This is a test", template: "txt")
get "/#{page.slug}.txt"
expect(response.body).to include(page.processed_html)
expect(response.media_type).to eq("text/plain")
end
it "renders not found when .txt request does not have txt template" do
page = create(:page, title: "Text page", body_html: "This is a test", template: "contained")
expect { get "/#{page.slug}.txt" }.to raise_error(ActiveRecord::RecordNotFound)
end
end
describe "GET /about" do
it "has proper headline" do
get "/about"