Class: EPUB::OCF::PhysicalContainer::ArchiveZip

Inherits:
EPUB::OCF::PhysicalContainer show all
Defined in:
lib/epub/ocf/physical_container/archive_zip.rb

Instance Method Summary collapse

Methods inherited from EPUB::OCF::PhysicalContainer

adapter, adapter=, open, read

Constructor Details

#initialize(container_path) ⇒ ArchiveZip

Returns a new instance of ArchiveZip.



7
8
9
10
11
# File 'lib/epub/ocf/physical_container/archive_zip.rb', line 7

def initialize(container_path)
  super
  @entries = {}
  @last_iterated_entry_index = 0
end

Instance Method Details

#openObject



13
14
15
16
17
18
19
20
21
22
# File 'lib/epub/ocf/physical_container/archive_zip.rb', line 13

def open
  Archive::Zip.open @container_path do |archive|
    @archive = archive
    begin
      yield self
    ensure
      @archive = nil
    end
  end
end

#read(path_name) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/epub/ocf/physical_container/archive_zip.rb', line 24

def read(path_name)
  target_index = @entries[path_name]
  if @archive
    @archive.each.with_index do |entry, index|
      if target_index
        if target_index == index
          return entry.file_data.read
        else
          next
        end
      end
      next if index < @last_iterated_entry_index
      # We can force encoding UTF-8 becase EPUB spec allows only UTF-8 filenames
      entry_path = entry.zip_path.force_encoding('UTF-8')
      @entries[entry_path] = index
      @last_iterated_entry_index = index
      if entry_path == path_name
        return entry.file_data.read
      end
    end
  else
    open {|container| container.read(path_name)}
  end
end