Created
February 17, 2011 19:28
-
-
Save benlodotcom/832449 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def highlight_gists(text) | |
#We set up the regexp we want to find in the string and replace it by the highlighted code | |
#This regular expression detects the code used to emebed a gist and extract the id of the gist, | |
#the file (for a multifile gist) and the language (the language attribute has to be added to the | |
#embed code) | |
regex = /<script src=\"(http|https):\/\/gist.github.com\/(\d+).js(\?file=(\S+))?\"(\s*lang=\"(.+)\")?>\s*<\/script>/ | |
text.gsub(regex) do | |
if $6 | |
highlight_gist($2,$4,$6) | |
else | |
#In case no lang attribute is specified | |
highlight_gist($2,$4) | |
end | |
end | |
end | |
def highlight_gist(gist_id, gist_file, gist_lang = "objc") | |
require 'open-uri' | |
#This is the base address of the gist service on github | |
gist_base_url = 'https://gist.github.com/' | |
#complete gist url | |
gist_url = gist_base_url + gist_id | |
#url to the text version of the gist (two versions depending if we show only one file or all the gist) | |
if (!gist_file.nil?) | |
gist_raw_url = gist_base_url + 'raw' + '/' + gist_id + '/' + gist_file | |
else | |
gist_raw_url = gist_url+'.txt' | |
gist_file = "gist" | |
end | |
#get gist raw code from github | |
gist_code = URI.parse(gist_raw_url).read | |
#create the highlighter using albino | |
syntaxer = Albino.new(gist_code, gist_lang) | |
#output html | |
html = "<div class=\"code\">"+ | |
"<div class=\"syntax\">"+syntaxer.colorize+"</div>"+ | |
"<span class=\"code_links\">"+link_to(gist_file, gist_url)+" - "+link_to("Get raw code", gist_raw_url)+"</span>"+ | |
"</div>" | |
html.html_safe | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Highlighter | |
def self.highlight(language, code) | |
command = "pygmentize -f html -l #{language}" | |
IO.popen(command, mode = 'r+') do |pygments| | |
pygments << code | |
pygments.close_write | |
pygments.read | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment