28 May 2014

Including code references in technical blogs is important to explain and demonstrate coding concepts. The typical way to do this is to embed Gists into your posts. However, I am writing several posts that all reference a public Github repo, not snippets that are inside Gists. Also, being able to reference code in a larger code base can help provide additional context if necessary. Taking inspiration from an existing Liquid Gist Tag, I created the Github Sample Tag.

The Github Sample Tag is a Jekyll tag that allows bloggers to include a sample of a file hosted on Github. Here is an example of it in use:

lib/jekyll_github_sample/code_tag.rb view raw
 1 def determine_line_numbers(first, last)
 2   if first.nil? && last.nil?
 3     first = 0
 4     last  = -1
 5   elsif last.nil?
 6     last = first
 7   end
 8 
 9   [first.to_i, last.to_i]
10 end

This example is actually 3 different tags in play, two from Github Sample Tag and one built-in. The first is the github_sample tag, which on it’s own just retrieves a portion of a raw Github file:

def determine_line_numbers(first, last)
  if first.nil? && last.nil?
    first = 0
    last  = -1
  elsif last.nil?
    last = first
  end

  [first.to_i, last.to_i]
end

The second is the builtin highlight block with the appropriate language format set:

 1 def determine_line_numbers(first, last)
 2   if first.nil? && last.nil?
 3     first = 0
 4     last  = -1
 5   elsif last.nil?
 6     last = first
 7   end
 8 
 9   [first.to_i, last.to_i]
10 end

The third piece is the github_sample_ref tag, which can be used on it’s own like so:

lib/jekyll_github_sample/code_tag.rb view raw

All three work well together and I can use a Github Sample from Jekyll Github Sample README file of the syntax:

README.md view raw
{% github_sample_ref /bwillis/versioncake/989237901cb873f96df12be48cbf1239be496bd7/Appraisals %}
{% highlight ruby %}
{% github_sample /bwillis/versioncake/989237901cb873f96df12be48cbf1239be496bd7/Appraisals 0 5 %}
{% endhighlight %}
Hey! It is best to use the link to the file with a commit hash in it so every time your Jekyll blog is recompiled it will not change your code sample.

Please leave questions and comments in the repo issues.

Read more »