Rake Publish

Octoblog (the engine behind this blog) uses Jekyll. As such, it also supports the publish flag. I a previous post I detailed how I added this feature back to Octopress. Here I will show you a little rake task to easily publish an unpublished post.

Requirements

For a post to be published I wanted a few things to happen:

  1. published: true was set in the YAML front-matter
  2. date: <todays date> was set in the YAML front-matter
  3. The file was moved to today.

Here is what I came up with for my Rakefile.

 1 desc "Publishes an unpublished entry by changing its name, updating its internal timestamp, and setting published: true"
 2 task :publish, :pattern do |t, args|
 3   require 'tempfile'
 4   require 'fileutils'
 5 
 6   files = Dir[File.join(source_dir,posts_dir,args[:pattern])]
 7   raise "No files found matching pattern" if files.size == 0
 8   raise "Too many files match pattern" if files.size > 1
 9 
10   name_time = Time.now.strftime('%Y-%m-%d')
11   file_time = Time.now.strftime('%Y-%m-%d %H:%M')
12 
13   file = files.first
14   name = File.basename file
15   new_name = name.gsub(/\d+-\d+-\d+/,name_time)
16   w        = Tempfile.new('publish')
17 
18   File.open file do |f|
19     scan = false
20     f.readlines.each do |line|
21       # limit scanning to the YAML front matter
22       scan = !scan if line == "---\n"
23       unless scan
24         w.write line
25         next
26       end
27 
28       line.gsub!(/published.*/,"published: true")
29       line.gsub!(/date.*/, "date: #{file_time}")
30 
31       w.write line
32     end
33   end
34   w.close
35 
36   FileUtils.rm file
37   FileUtils.mv w.path, File.join(source_dir,posts_dir,new_name)
38 end

Line 6: I take a argument and get a list of files matching the pattern

Line 7 & 8: I found it was too easy to screw up a pattern and publish too few or too many posts. For that reason I am explicit about the failure.

Line 15: Calculates its name for today.

Line 16 & 37: Generate a temp file to write to. I found that bad things happened if you published a post that you wrote the same day. Solution was to write to a temp file and then move the temp file later.

Line 19 && 22: An inelegant solution to isolating scanning to only the YAML front-matter.

Line 28 & 29: Update the YAML front-matter.

comments powered by Disqus