-
Notifications
You must be signed in to change notification settings - Fork 1
/
sync.rb
44 lines (41 loc) · 1.61 KB
/
sync.rb
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
44
require 'algoliasearch'
require 'redcarpet'
require 'redcarpet'
module Middleman
# utility class for syncing articles with algolia
class AlgoliaSync < ::Middleman::Extension
def initialize(app, options_hash = {}, &block)
env_vars = YAML.safe_load(File.open('secrets.yml').read)
Algolia.init application_id: env_vars['application_id'],
api_key: env_vars['api_key']
@algolia_index = Algolia::Index.new('posts')
@redcarpet = Redcarpet::Markdown.new(Redcarpet::Render::HTML)
super
end
def after_build(builder)
Dir.glob('source/articles/*/*.markdown') do |markdown_file|
markdown_post = File.open(markdown_file).read
article_meta_data = YAML.safe_load(markdown_post.lines[1..3].join("\n"))
title = article_meta_data['title']
sanatized_title = title.downcase.tr(' ', '-').tr('/', '-')
article_link = "/#{sanatized_title}.html"
tags = article_meta_data['tags'].split(',')
date = article_meta_data['date']
unix_time = Date.parse(date).to_time.to_i
markdown_body = markdown_post.lines[5..-1].join("\n")
body_html = @redcarpet.render(markdown_body).tr("\n\n", ' ')
text = Nokogiri::HTML(body_html).text.squeeze(' ')
post =
{ objectID: Base64.encode64(title),
title: title, article_link: article_link,
tags: tags, text: text, date: unix_time }
begin
@algolia_index.save_object(post)
rescue => e
puts "error: #{e}"
end
end
end
end
end
::Middleman::Extensions.register(:sync, ::Middleman::AlgoliaSync)