aboutsummaryrefslogtreecommitdiff
path: root/bin/pg_jekyll.rb
blob: 464dcf9944d7b5e0332838e55397172a593b1cc1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env ruby
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.

# frozen_string_literal: true

require 'pg'

connection = PG.connect(user: ENV['user'], dbname: ENV['DBNAME'])
query = <<~SQL
  SELECT articles.*, categories.name
  FROM articles
  INNER JOIN categories on categories.id = articles.category_id
SQL
connection.exec query do |result|
  result.each do |row|
    post_contents = <<~POST
      ---
      layout: post
    POST

    date = row['created_at'].gsub /\.[[:digit:]]+$/, '' # Remove milliseconds from the value.
    post_contents << "date: #{date}\n"
    category = row['name']
    post_contents << "tags: #{category}\n"

    if row['title'].include? '"'
      post_contents << "title: |\n  #{row['title']}\n"
    else
      post_contents << "title: #{row['title']}\n"
    end

    post_contents << "teaser:\n  #{row['teaser']}\n" unless row['teaser'].nil?
    post_contents << "---\n"
    post_contents << "#{row['description'].delete("\r")}\n"

    post_path = (Pathname.new('posts') + row['slug']).sub_ext('.html')

    post_path.dirname.mkpath
    post_path.write post_contents
  end
end