Created
June 1, 2016 11:40
-
-
Save KitaitiMakoto/a61d7740c0035f5f81bb6f6808faa2ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'English' | |
require 'epub/parser' | |
require 'epub/parser/cfi' | |
require 'nokogiri' | |
def usage | |
<<EOS | |
USAGE: | |
ruby #{$PROGRAM_NAME} ELEMENT EPUB | |
EOS | |
end | |
def main(argv) | |
elem_name = argv.shift | |
epub_path = argv.shift | |
if elem_name.nil? or epub_path.nil? | |
abort usage | |
end | |
spine_step = {:step => 6} | |
epub = EPUB::Parser.parse(epub_path) | |
epub.package.spine.each_itemref.with_index do |itemref, i| | |
itemref_step = { | |
:step => (i + 1) * 2, | |
:id => itemref.id | |
} | |
itemref.item.content_document.nokogiri.search(elem_name).each do |elem| | |
path = find_path(elem) | |
path_str = "/#{spine_step[:step]}/#{itemref_step[:step]}" | |
path_str << "[#{itemref_step[:id]}]" if itemref_step[:id] | |
path_str << "!" | |
path.each do |elem_step| | |
path_str << "/#{elem_step[:step]}" | |
path_str << "[#{elem_step[:id]}]" if elem_step[:id] | |
end | |
puts path_str | |
puts elem.content | |
puts | |
end | |
end | |
end | |
def find_path(elem) | |
steps = [] | |
until elem.parent.document? | |
index = elem.parent.element_children.index(elem) | |
steps.unshift({ | |
:step => (index + 1) * 2, | |
:id => elem["id"] | |
}) | |
elem = elem.parent | |
end | |
steps | |
end | |
main ARGV |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment