Class: EpubTools::PackEbook

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

Overview

Packages an EPUB directory into a .epub file

Instance Method Summary collapse

Methods included from Loggable

#log

Constructor Details

#initialize(options = {}) ⇒ PackEbook

Initializes the class

Options Hash (options):

  • :input_dir (String)

    Path to the EPUB directory (containing mimetype, META-INF, OEBPS) (required)

  • :output_file (String)

    Path to resulting .epub file (default: <input_dir>.epub)

  • :verbose (Boolean)

    Whether to print progress to STDOUT (default: false)



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/epub_tools/pack_ebook.rb', line 15

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

Instance Method Details

#runObject

Runs the packaging process and returns the resulting file path



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/epub_tools/pack_ebook.rb', line 28

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
  log "EPUB created: #{@output_file}"
  @output_file
end