discourse/lib/oneboxer/github_blob_onebox.rb

50 lines
1.2 KiB
Ruby
Raw Normal View History

2013-02-05 14:16:51 -05:00
require_dependency 'oneboxer/handlebars_onebox'
module Oneboxer
class GithubBlobOnebox < HandlebarsOnebox
matcher /^https?:\/\/(?:www\.)?github\.com\/[^\/]+\/[^\/]+\/blob\/.*/
2013-02-05 14:16:51 -05:00
favicon 'github.png'
2013-02-25 11:42:20 -05:00
def translate_url
2013-02-05 14:16:51 -05:00
m = @url.match(/github\.com\/(?<user>[^\/]+)\/(?<repo>[^\/]+)\/blob\/(?<sha1>[^\/]+)\/(?<file>[^#]+)(#(L(?<from>[^-]*)(-L(?<to>.*))?))?/mi)
if m
@from = (m[:from] || -1).to_i
@to = (m[:to] || -1).to_i
@file = m[:file]
return "https://raw.github.com/#{m[:user]}/#{m[:repo]}/#{m[:sha1]}/#{m[:file]}"
end
nil
end
def parse(data)
2013-02-25 11:42:20 -05:00
if @from > 0
2013-02-05 14:16:51 -05:00
if @to < 0
@from = @from - 10
@to = @from + 20
end
if @to > @from
data = data.split("\n")[@from..@to].join("\n")
end
end
extension = @file.split(".")[-1]
@lang = case extension
when "rb" then "ruby"
when "js" then "javascript"
else extension
end
truncated = false
if data.length > SiteSetting.onebox_max_chars
data = data[0..SiteSetting.onebox_max_chars-1]
truncated = true
end
2013-02-25 11:42:20 -05:00
{content: data, truncated: truncated}
2013-02-05 14:16:51 -05:00
end
end
end