Created
December 10, 2021 20:05
-
-
Save agarie/44d92cd1dfec911be66ce0e7ce26fe39 to your computer and use it in GitHub Desktop.
This script receives (from a filename argument or stdin) a CSV, with headers, containing columns post_title, post_date and post_content and converts each entry into a markdown post with Liquid front matter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# Convert the entries from a CSV with headers | |
# - post_title | |
# - post_date (must include year-month-day) | |
# - post_content | |
# into markdown posts with Liquid's front matter and the correct naming | |
# structure. Reminder that valid HTML posts are also valid markdown. | |
require "csv" | |
def remove_escapes(string) | |
string.gsub(/\\'/, "'").gsub(/\\"/, "\"").gsub(" -- ", " – ").gsub(" --- ", " — ") | |
end | |
def front_matter(title) | |
<<~EOFM | |
--- | |
layout: post | |
title: "#{remove_escapes(title)}" | |
--- | |
EOFM | |
end | |
def post_filename(title, date) | |
_date = /(\d{4}-\d{2}-\d{2})/.match(date)[1] | |
_title = title.downcase.gsub(/\s+/, "-").gsub(/[^[:alnum:]-]/, "").sub(/-+$/, "") | |
"#{_date}-#{remove_escapes(_title)}.md" | |
end | |
def post(title, content) | |
<<~EOPOST | |
#{front_matter(title)} | |
#{remove_escapes(content.gsub(/\\n/, "\n"))} | |
EOPOST | |
end | |
def create_post(title, date, content) | |
File.open(post_filename(title, date), "w") do |file| | |
file.puts post(title, content) | |
end | |
end | |
csv = CSV.new(ARGF, headers: true) | |
csv.each do |row| | |
create_post(row["post_title"], row["post_date"], row["post_content"]) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment