Skip to content

Commit

Permalink
Provide <title> tags for doc pages
Browse files Browse the repository at this point in the history
  • Loading branch information
pablobm committed Feb 13, 2020
1 parent 650a2d6 commit 8710d09
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
41 changes: 36 additions & 5 deletions spec/example_app/app/controllers/docs_controller.rb
Expand Up @@ -18,7 +18,11 @@ def render_page(name)
path = full_page_path(name)

if File.exist?(path)
render layout: "docs", html: render_markdown(path).html_safe
contents = parse_markdown(path)
@page_title = contents.title
# rubocop:disable Rails/OutputSafety
render layout: "docs", html: contents.body.html_safe
# rubocop:enable Rails/OutputSafety
else
render file: "#{Rails.root}/public/404.html",
layout: false,
Expand All @@ -30,11 +34,38 @@ def full_page_path(page)
Rails.root + "../../#{page}.md"
end

def render_markdown(path)
def parse_markdown(path)
text = File.read(path)
renderer = Redcarpet::Render::HTML
markdown = Redcarpet::Markdown.new(renderer, REDCARPET_CONFIG)
MarkdownParser.new(text)
end

class MarkdownParser
def initialize(source_text)
@source_text = source_text
end

def body
@body ||=
begin
renderer = Redcarpet::Render::HTML
markdown = Redcarpet::Markdown.new(renderer, REDCARPET_CONFIG)

markdown.render(source_text)
end
end

def title
@title ||=
begin
h1_match = @source_text.scan(/^# (.*)$/).first
raise "Please provide an H1 heading for the page" if h1_match.empty?

h1_match.first
end
end

private

markdown.render(text)
attr_reader :source_text
end
end
1 change: 1 addition & 0 deletions spec/example_app/app/views/layouts/docs.html.erb
Expand Up @@ -2,6 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<title><%= @page_title %></title>
<%= stylesheet_link_tag "docs", media: "all" %>
<link href='//fonts.googleapis.com/css?family=Lato|Source+Code+Pro|Fjalla+One' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">
Expand Down

0 comments on commit 8710d09

Please sign in to comment.