Class: EpubTools::PackEbook

Inherits:
Object
  • Object
show all
Defined in:
lib/epub_tools/pack_ebook.rb

Overview

Packages an EPUB directory into a .epub file

Instance Method Summary collapse

Constructor Details

#initialize(input_dir, output_file = nil, verbose: false) ⇒ PackEbook

input_dir: path to the EPUB directory (containing mimetype, META-INF, OEBPS) output_file: path to resulting .epub file; if nil, defaults to <input_dir>.epub



10
11
12
13
14
15
16
17
18
19
# File 'lib/epub_tools/pack_ebook.rb', line 10

def initialize(input_dir, output_file = nil, verbose: false)
  @input_dir = File.expand_path(input_dir)
  default_name = "#{File.basename(@input_dir)}.epub"
  @output_file = if output_file.nil? || output_file.empty?
                   default_name
                 else
                   output_file
                 end
  @verbose = verbose
end

Instance Method Details

#runObject

Run the packaging process



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/epub_tools/pack_ebook.rb', line 22

def run
  validate_input!
  Dir.chdir(@input_dir) do
    # determine the output path: absolute stays as-is, otherwise sibling to input_dir
    target = Pathname.new(@output_file).absolute? ? @output_file : File.join('..', @output_file)
    FileUtils.rm_f(target)
    Zip::File.open(target, Zip::File::CREATE) do |zip|
      # Add mimetype first and uncompressed
      add_mimetype(zip)

      # Add all other files with compression, preserving paths
      Dir.glob('**/*', File::FNM_DOTMATCH).sort.each do |entry|
        next if ['.', '..', 'mimetype'].include?(entry)
        next if File.directory?(entry)
        zip.add(entry, entry)
      end
    end
  end
  puts "EPUB created: #{@output_file}" if @verbose
end