How To: Fetch GitHub Updates in Jekyll

2015 January 2

Fetching recent commits from the GitHub API during Jekyll build with Ruby and Peter Murach’s GitHub API gem.

  1. Install Peter Murach's GitHub API Ruby gem.

    gem install github_api
  2. Check out the happy unicorn/rainbow.

  3. Get recent commits to a given repo like so:

    commit_coll = Github.repos.commits.all 'myusername', 'myrepo'
  4. Create a Jekyll collection on the fly.

    jekyll_coll = Jekyll::Collection.new(site, 'commits')
    site.collections['commits'] = jekyll_coll
  5. Add some fake/virtual documents to the collection:

    commit_coll.each do |commit|
    msg = commit[:commit][:message]
    sha = commit['sha']
    path = "_blurbs/" + sha + ".md"
    path = site.in_source_dir(path)
    doc = Jekyll::Document.new(path, 
       { :site => site, :collection => jekyll_coll })
    doc.data['title'] = msg
    doc.data['exturl'] = commit[:html_url]
    if msg.lines.count > 1
       doc.data['title'] = msg.lines.first
       doc.content = msg.lines.drop(1).join()
    end
    jekyll_coll.docs << doc
  6. Access the collection from the template:

    {% for blurb in site.collections['commits'].docs limit: 5 %}
    <div class="post-card github">
      <h2>{{ blurb.title }}</h2>
      <p>{{ blurb.content }}</p>
    </div>
    {% endfor %}