From a6a5c9bea0ad5d8ce5f45917a38c2b3cc4c82dba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christoffer=20M=C3=BCller=20Madsen?= Date: Thu, 26 Oct 2017 16:23:24 +0200 Subject: [PATCH] dir to be indexed is now an option to index.rb --- .gitignore | 7 +++++++ Gemfile | 2 ++ books.csv.erb | 1 + index.rb | 47 +++++++++++++++++++++++++++++++++++++++-------- 4 files changed, 49 insertions(+), 8 deletions(-) create mode 100644 .gitignore create mode 100644 Gemfile create mode 100644 books.csv.erb diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..17c3d06 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.bundle/ +Gemfile.lock +books.csv +books/ +index.html +tmp/ +vendor/ diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..6335331 --- /dev/null +++ b/Gemfile @@ -0,0 +1,2 @@ +source 'https://rubygems.org/' +gem 'gepub' diff --git a/books.csv.erb b/books.csv.erb new file mode 100644 index 0000000..3a19787 --- /dev/null +++ b/books.csv.erb @@ -0,0 +1 @@ +<% books.each do |b| %> \ No newline at end of file diff --git a/index.rb b/index.rb index eb93c1b..38569b6 100644 --- a/index.rb +++ b/index.rb @@ -1,14 +1,28 @@ require 'gepub' require 'erb' +require 'optparse' +require 'pathname' # Parse epubs -books = Dir["books/*.epub"].map do |f| - [f, GEPUB::Book.parse(File.new f)] -end +options = {:subdir => "books"} +OptionParser.new do |opts| + 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 @@ -25,15 +39,32 @@ title_sort_by = proc { |filename, book| 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) -template = File.read 'index.html.erb' +html_template = File.read 'index.html.erb' -result = ERB.new(template).result(bind) -File.open "index.html", "w+" do |f| - f << result +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