Skip to content

Instantly share code, notes, and snippets.

@vdurmont
Forked from gsong/gist.rb
Created January 6, 2014 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vdurmont/8289311 to your computer and use it in GitHub Desktop.
Save vdurmont/8289311 to your computer and use it in GitHub Desktop.
require 'cgi'
require 'open-uri'
# Require the ActiveSupport::Cache module
require 'active_support/cache'
module Fiftyfive
module Liquid
class GistTag < ::Liquid::Tag
def initialize(tag_name, gist_ref, tokens)
@gist_ref = gist_ref.strip
@gist_id, @filename = @gist_ref.split('/')
super
end
# A simple file-based cache in ./_tmp shared by all GistTag instances
def cache
@@cache ||= ActiveSupport::Cache::FileStore.new("_tmp/gist")
end
# Return from cache if possible; otherwise fetch and add it to cache
def fetch_gist(raw_gist_uri)
cache.fetch(raw_gist_uri) do
open(raw_gist_uri).read.chomp
end
end
def render(context)
raw_uri = "https://gist.github.com/raw/#{@gist_id}/#{@filename}"
script_uri = "https://gist.github.com/#{@gist_id}.js?file=#{@filename}"
<<MARKUP.strip
<div id="gist-#{@gist_ref.gsub(/[^a-z0-9]/i,'-')}">
<script src="#{script_uri}"></script>
<noscript>
<pre>#{CGI.escapeHTML(fetch_gist(raw_uri))}</pre>
</noscript>
</div>
MARKUP
end
end
end
end
Liquid::Template.register_tag('gist', Fiftyfive::Liquid::GistTag)
<div>
<!-- For browsers that know JavaScript -->
<script src="https://gist.github.com/12345.js?file=abc.txt"></script>
<!-- For browsers or RSS readers that don't deal with JavaScript -->
<noscript>
<pre>
Raw content of a Gist file.
</pre>
</noscript>
</div>
<div id="gist-12345-abc-txt">
<script src="https://gist.github.com/12345.js?file=abc.txt"></script>
<noscript>
<pre>Raw content of a Gist file.</pre>
</noscript>
</div>
require 'cgi'
require 'open-uri'
module Fiftyfive
module Liquid
class GistTag < ::Liquid::Tag
def initialize(tag_name, gist_ref, tokens)
@gist_ref = gist_ref.strip
# gist_ref is in the form of `gist_id` or `gist_id/filename`
@gist_id, @filename = @gist_ref.split('/')
super
end
def render(context)
raw_uri = "https://gist.github.com/raw/#{@gist_id}/#{@filename}"
script_uri = "https://gist.github.com/#{@gist_id}.js?file=#{@filename}"
<<MARKUP.strip
<div id="gist-#{@gist_ref.gsub(/[^a-z0-9]/i,'-')}">
<script src="#{script_uri}"></script>
<noscript>
<pre>#{CGI.escapeHTML(open(raw_gist_uri).read.chomp)}</pre>
</noscript>
</div>
MARKUP
end
end
end
end
Liquid::Template.register_tag('gist', Fiftyfive::Liquid::GistTag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment