Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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