class GithubToCanvasQuiz::MarkdownBuilder

Custom DSL for building a Markdown string

Attributes

blocks[RW]

Public Class Methods

build() { |builder| ... } click to toggle source

Provides a custom DSL for building a Markdown string Usage:

MarkdownBuilder.build do |md|
  md.h1('Hello')
  md.ul('item 1', 'item 2')
  md.blockquote('comment')
end

# => "# Hello\n\n- item 1\n- item 2\n\n> comment\n"
# File lib/github_to_canvas_quiz/markdown_builder.rb, line 16
def self.build
  raise ArgumentError, 'no block given' unless block_given?

  builder = new
  yield(builder)
  builder.to_s
end
new() click to toggle source
# File lib/github_to_canvas_quiz/markdown_builder.rb, line 26
def initialize
  @blocks = []
end

Public Instance Methods

blockquote(text) click to toggle source

Adds a blockquote @param text [String] blockquote text

# File lib/github_to_canvas_quiz/markdown_builder.rb, line 61
def blockquote(text)
  text = text.gsub("\n", "\n> ")
  blocks << "> #{text}"
end
frontmatter(hash) click to toggle source

Adds a frontmatter block @param hash [Hash] the data to covert to YAML for the frontmatter

# File lib/github_to_canvas_quiz/markdown_builder.rb, line 37
def frontmatter(hash)
  blocks << "#{hash.to_yaml.strip}\n---"
end
h1(text) click to toggle source

Adds a H1 heading @param text [String] heading text

# File lib/github_to_canvas_quiz/markdown_builder.rb, line 43
def h1(text)
  blocks << "# #{text}"
end
h2(text) click to toggle source

Adds a H2 heading @param text [String] heading text

# File lib/github_to_canvas_quiz/markdown_builder.rb, line 49
def h2(text)
  blocks << "## #{text}"
end
html_to_markdown(html) click to toggle source

TODO: This doesn’t belong here…

# File lib/github_to_canvas_quiz/markdown_builder.rb, line 79
def html_to_markdown(html)
  ReverseMarkdown.convert(html, github_flavored: true).strip
end
md(markdown) click to toggle source

Adds a block of arbitrary markdown @param markdown [String] markdown string

# File lib/github_to_canvas_quiz/markdown_builder.rb, line 74
def md(markdown)
  blocks << markdown.strip
end
p(text) click to toggle source

Adds a paragraph @param text [String] paragraph text

# File lib/github_to_canvas_quiz/markdown_builder.rb, line 55
def p(text)
  blocks << escape(text)
end
to_s() click to toggle source

@return [String] markdown produced by joining all blocks

# File lib/github_to_canvas_quiz/markdown_builder.rb, line 31
def to_s
  "#{blocks.join("\n\n")}\n"
end
ul(*texts) click to toggle source

Adds multiple list items @param texts* [Strings] a list of text to convert to list items

# File lib/github_to_canvas_quiz/markdown_builder.rb, line 68
def ul(*texts)
  blocks << texts.map { |text| "- #{escape(text)}" }.join("\n")
end

Private Instance Methods

escape(text) click to toggle source

TODO: What needs escaping??

# File lib/github_to_canvas_quiz/markdown_builder.rb, line 86
def escape(text)
  text.gsub('_', '\_')
end