Skip to content

Instantly share code, notes, and snippets.

@jorgemanrubia
Created October 4, 2015 09:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorgemanrubia/d6f490f578d98f3b2508 to your computer and use it in GitHub Desktop.
Save jorgemanrubia/d6f490f578d98f3b2508 to your computer and use it in GitHub Desktop.
Script to convert reading list in csv format
require 'csv'
require 'date'
require 'ostruct'
require 'open-uri'
require 'fileutils'
class BooksConverter
OUTPUT_FOLDER = "output"
attr_reader :file, :covers_map
def initialize(file)
@file = file
@covers_map = {}
FileUtils.mkdir_p("#{OUTPUT_FOLDER}/covers")
end
def convert
CSV.foreach(file) do |row|
id, added_at, started_at, finished_at_string, title, nice_title, author, nice_author, cover_image_url, asin = row
next if id.strip == 'B Id'
finished_at = Date.parse(finished_at_string) rescue puts("No finished at date for '#{title}'")
book = OpenStruct.new(title: title, finished_at: finished_at, author: author, asin: asin, cover_image_url: cover_image_url, nice_title: nice_title)
generate_book(book)
end
end
private
def generate_book(book)
return unless book.finished_at
file_name = "#{book.finished_at}-#{book.nice_title}"
puts "Generating #{file_name}..."
download_cover(book, file_name)
generate_book_entry(book, file_name)
end
def generate_book_entry(book, file_name)
finished_at_string = book.finished_at.strftime
cover_entry = if covers_map[book.id]
"cover_url: #{covers_map[book.id]}"
else
''
end
File.open("#{OUTPUT_FOLDER}/#{file_name}.md", "w") do |file|
file << <<-EOS.gsub(/^ /, '')
---
title: "#{book.title}"
finished_at: #{finished_at_string}
author: "#{book.author}"
categories: books
asin: #{book.asin}
#{cover_entry}
---
EOS
end
end
def download_cover(book, file_name)
puts "Downloading cover for #{file_name} from #{book.cover_image_url}..."
extension = File.extname(book.cover_image_url)
image_file_name = "#{OUTPUT_FOLDER}/covers/#{file_name}#{extension}"
File.open(image_file_name, 'wb') do |fo|
fo.write open(book.cover_image_url).read
covers_map[book.id] = image_file_name.gsub("#{OUTPUT_FOLDER}", '')
end rescue handle_cover_not_downloadable(image_file_name)
end
def handle_cover_not_downloadable(file_name)
puts "\tCover image not downloadable #{file_name}"
FileUtils.rm file_name
end
end
BooksConverter.new("books.csv").convert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment