Method: Bookmaker::Parser::Epub#write_sections!

Defined in:
lib/bookmaker/parser/epub.rb

#write_sections!Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/bookmaker/parser/epub.rb', line 51

def write_sections!
  # First we need to get all ids, which are used as
  # the anchor target.
  links = sections.inject({}) do |buffer, section|
    section.html.css("[id]").each do |element|
      anchor = "##{element["id"]}"
      buffer[anchor] = "#{section.filename}#{anchor}"
    end

    buffer
  end

  # Then we can normalize all links and
  # manipulate other paths.
  #
  sections.each do |section|
    section.html.css("a[href^='#']").each do |link|
      href = link["href"]
      link.set_attribute("href", links.fetch(href, href))
    end

    # Replace all srcs.
    #
    section.html.css("[src]").each do |element|
      src = File.basename(element["src"]).gsub(/\.svg$/, ".png")
      element.set_attribute("src", src)
      element.set_attribute("alt", "")
      element.node_name = "img"
    end

    FileUtils.mkdir_p(tmp_dir)

    # Save file to disk.
    #
    File.open(section.filepath, "w") do |file|
      body = section.html.css("body").to_xhtml.gsub(%r[<body>(.*?)</body>]m, "\\1")
      file << render_chapter(body)
    end
  end
end