Skip to Content Skip to Search

# Action Text Markdown Conversion

Converts an HTML fragment into a Markdown string. Used by ‘ActionText::Content#to_markdown` and `ActionText::Fragment#to_markdown` to produce Markdown representations of rich text.

Example: ‘<h1>Release Notes</h1>` => `# Release Notes`, a markdown heading.

Note that this converter escapes text nodes so it won’t render as markdown.

Example: ‘<p># Release Notes</p>` => `# Release Notes`, not a heading.

Methods
E
M
N

Instance Public methods

escape_markdown_text(text)

Backslash-escapes CommonMark metacharacters in text so they are treated as literal characters by Markdown renderers.

MarkdownConversion.escape_markdown_text("**Important**")
# => "\\*\\*Important\\*\\*"
# File actiontext/lib/action_text/markdown_conversion.rb, line 46
def escape_markdown_text(text)
  text.gsub(MARKDOWN_METACHARACTERS) { |c| "\\#{c}" }
end

Returns a Markdown link: +[title](url)+. Escapes brackets and backslashes in title, and percent-encodes characters in url that would break the link syntax.

MarkdownConversion.markdown_link("photo", "https://example.com/photo_(large).png")
# => "[photo](https://example.com/photo_%28large%29.png)"

node_to_markdown(node)

Converts a Nokogiri HTML node into a Markdown string.

node = Nokogiri::HTML4.fragment("<p>Hello <strong>world</strong></p>")
MarkdownConversion.node_to_markdown(node) # => "Hello **world**"
# File actiontext/lib/action_text/markdown_conversion.rb, line 25
def node_to_markdown(node)
  BottomUpReducer.new(node).reduce do |n, child_values|
    markdown_for_node(n, child_values)
  end.strip
end