dir to be indexed is now an option to index.rb

This commit is contained in:
Christoffer Müller Madsen 2017-10-26 16:23:24 +02:00
parent b8c449d9c9
commit a6a5c9bea0
4 changed files with 49 additions and 8 deletions

7
.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
.bundle/
Gemfile.lock
books.csv
books/
index.html
tmp/
vendor/

2
Gemfile Normal file
View File

@ -0,0 +1,2 @@
source 'https://rubygems.org/'
gem 'gepub'

1
books.csv.erb Normal file
View File

@ -0,0 +1 @@
<% books.each do |b| %>

View File

@ -1,14 +1,28 @@
require 'gepub' require 'gepub'
require 'erb' require 'erb'
require 'optparse'
require 'pathname'
# Parse epubs # Parse epubs
books = Dir["books/*.epub"].map do |f| options = {:subdir => "books"}
[f, GEPUB::Book.parse(File.new f)] OptionParser.new do |opts|
end opts.banner = "Usage: index.rb [options]"
books = books.to_h 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 # Collection of sort_by procs
@ -25,15 +39,32 @@ title_sort_by = proc { |filename, book|
books = books.sort_by &title_sort_by 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 # Generate 'index.html' from template
bind = binding bind = binding
bind.local_variable_set(:books, books) bind.local_variable_set(:books, books)
template = File.read 'index.html.erb' html_template = File.read 'index.html.erb'
result = ERB.new(template).result(bind) html_result = ERB.new(html_template).result(bind)
File.open "index.html", "w+" do |f| File.open "#{options[:dir]}/index.html", "w+" do |f|
f << result 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 end