Wednesday, October 2, 2013

Share Code Snippets in Blogger

Hi folks,
From time to time, I wanted to share code snippets in Blogger which is pretty crappy for said task...
until... I found out about gists from github...

Gists are a great way to share code snippets. You can create them on github, and just like all code repos, they are versioned and backed up...

You can make your code look as pretty as this:

and this:
require 'nokogiri'
require 'open-uri'
require 'net/http'
require 'cgi'
class Snippet < ActiveRecord::Base
before_save :send_to_gist
def gist_url
"http://gist.github.com/#{self.gist_id}"
end
def gist_url=(url)
id = url.match(/[http:\/\/gist.github.com\/]?(\d+)\/?/)
unless id.nil?
p id[1]
self.gist_id = id[1]
gist_url = "http://gist.github.com/#{gist_id}"
doc = Nokogiri::HTML.parse(open(gist_url))
raw_gist_url = "http://gist.github.com" + doc.xpath('//a[text()="raw"]').first.attributes['href'].to_s
self.code = open(raw_gist_url).read
end
end
def send_to_gist
if self.gist_id.blank?
response = Net::HTTP.post_form(URI.parse('http://gist.github.com/api/v1/xml/new'), { "files[#{title.downcase.gsub(' ', '_')}.rb]" => "#{code}" })
doc = Nokogiri::XML.parse(response.body)
repo_id = doc.xpath('//repo').first.content
write_attribute(:gist_id, repo_id)
end
end
end
view raw snippet.rb hosted with ❤ by GitHub
@snippet = Snippet.new({:title => 'a new snippet'})
@snippet.gist_url = 12345
@snippet.save
view raw usage.rb hosted with ❤ by GitHub
and this:
!SLIDE
# gist-slideを試してみる
[これ](http://gist-slide.appspot.com/1191887/gist-slide)
!SLIDE
## どーよ
``` scala
object Hello extends App {
println("Hello")
}
```
view raw gist-slide-test hosted with ❤ by GitHub
Check out https://gist.github.com/discover

No comments:

Post a Comment