Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mattsan
Created December 24, 2018 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattsan/d61240ee5a3f7feae1d0a43ddcf0b729 to your computer and use it in GitHub Desktop.
Save mattsan/d61240ee5a3f7feae1d0a43ddcf0b729 to your computer and use it in GitHub Desktop.
ブログ記事「Markdown から EPUB を作る」より
require 'redcarpet'
require 'nokogiri'
require 'securerandom'
require 'gepub'
Chapter = Struct.new("Chapter", :title, :body)
def split_md_into_chapters(source)
result = []
title = nil
begin
body, next_title, rest = source.partition(%r{^# .*\n})
result << Chapter.new(title, "# #{title}\n#{body}") unless body.empty?
title, source = next_title[2..-2], rest
end until source.empty?
result
end
def convert_to_xhtml(chapter)
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new, autolink: true, tables: true, fenced_code_blocks: true, prettify: true)
html = Nokogiri::HTML.parse( markdown.render(chapter.body))
html.title = chapter.title
html.to_xhtml
end
def generate_epub_from_markdown(source)
book = GEPUB::Book.new {|book|
book.identifier = "md2epub-#{SecureRandom.uuid}"
book.title = 'md2epub - Markdown から EPUB を作る'
book.ordered do
split_md_into_chapters(source).each_with_index do |chapter, index|
xhtml = convert_to_xhtml(chapter)
book.add_item("text/#{index}.xhtml")
.add_content(StringIO.new(xhtml))
.toc_text(chapter.title)
end
end
}
book.generate_epub('md2epub.epub')
end
generate_epub_from_markdown(<<~MARKDWON)
# Markdown を分割する
レベル 1 の見出しを一つの章として扱うように分割します。
# 各章を XHTML に変換する
gem [redcarpet](https://github.com/vmg/redcarpet) と [nokogiri](https://www.nokogiri.org) を利用して markdown から XHTML に変換します。
```ruby
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new, autolink: true, tables: true)
html = Nokogiri::HTML.parse(markdown.render(source))
html.title = title
xhtml = html.to_xhtml
```
# XHTML をまとめて EPUB で出力する
gem [gepub](https://github.com/skoji/gepub) を利用して XHTML から EPUB に変換します。
MARKDWON
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment