Class: BookUtils::Convert

Inherits:
Object
  • Object
show all
Defined in:
lib/book_utils/convert.rb

Instance Method Summary collapse

Constructor Details

#initialize(dir) ⇒ Convert

Returns a new instance of Convert.



8
9
10
# File 'lib/book_utils/convert.rb', line 8

def initialize(dir)
  @dir = dir
end

Instance Method Details

#runObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/book_utils/convert.rb', line 12

def run
  files = Dir[File.expand_path("**/*", @dir)].sort.reject{|a| File.directory?(a)}

  Dir.mktmpdir do |path|
    assets_dir = File.expand_path("../../../assets/", __FILE__)

    # copy system files
    FileUtils.cp_r("#{assets_dir}/META-INF", path)
    FileUtils.cp_r("#{assets_dir}/OEBPS", path)
    FileUtils.cp("#{assets_dir}/mimetype", path)
    
    # colorize files
    files = files.select do |file|
      File.extname(file) == '.rb'
    end

    files.each do |file|
      File.open(path + "/OEBPS/" + file_basename(file) + ".html", "w") do |f|
        f.write colorize(file_basename(file), File.read(file))
      end
    end

    # process ERB templates
    %w(title.html.erb content.opf.erb).each do |template_name|
      template = "#{assets_dir}/templates/#{template_name}"
      File.open(path + "/OEBPS/" + File.basename(template, '.erb'), "w") do |f| 
        f.write process_template(File.read(template), File.basename(@dir), files.map{|f| file_basename(f)})
      end
    end  

    # zip book
    Dir.chdir path do
      system "zip -0Xq ebook.epub mimetype"
      system "zip -Xr9Dq ebook.epub *"
    end

    # move to work directory
    FileUtils.mv(path + "/ebook.epub", File.basename(@dir) + ".epub")
  end
end