ebook-index/index.rb

71 lines
1.5 KiB
Ruby

require 'gepub'
require 'erb'
require 'optparse'
require 'pathname'
# Parse epubs
options = {:subdir => "books"}
OptionParser.new do |opts|
opts.banner = "Usage: index.rb [options]"
opts.on("-d", "--dir DIR", "directory to index (subdir specified with '-s' will be indexed)") do |d|
options[:dir] = d
end
opts.on("-s", "--subdir DIR", "subdirectory to search for books") do |s|
options[:subdir] = s
end
end.parse!
raise OptionParser::MissingArgument unless options[:dir]
books = Dir["#{options[:dir]}/#{options[:subdir]}/*.epub"].map do |f|
[Pathname.new(f).relative_path_from(Pathname.new(options[:dir])), GEPUB::Book.parse(File.new f)]
end.to_h
# Collection of sort_by procs
author_surname_sort_by = proc { |filename, book|
book.creator.content.split(" ")[-1]
}
title_sort_by = proc { |filename, book|
book.title.content
}
# Sort books by one of the above
books = books.sort_by &title_sort_by
i = 0
book_ids = books.map { |filename, book| [filename, i += 1] }.to_h
i = nil
# Generate 'index.html' from template
bind = binding
bind.local_variable_set(:books, books)
html_template = File.read 'index.html.erb'
html_result = ERB.new(html_template).result(bind)
File.open "#{options[:dir]}/index.html", "w+" do |f|
f << html_result
end
# Generate 'books.csv'
File.open "#{options[:dir]}/books.csv", "w+" do |f|
f << "id\ttitle\tauthor\tfilename\n"
books.each do |filename, book|
f << "#{book_ids[filename]}\t"
f << "#{book.title.content}\t"
f << "#{book.creator.content}\t"
f << "#{filename}\t"
f << "\n"
end
end