Skip to content

Instantly share code, notes, and snippets.

@pjaspers
Created August 7, 2012 18:55
Show Gist options
  • Save pjaspers/3288317 to your computer and use it in GitHub Desktop.
Save pjaspers/3288317 to your computer and use it in GitHub Desktop.
Seen here: https://gist.github.com/1042725 (extracted for use with gasoline gem)
/*
Display Gists inline.
This responder illustrates using Propane's requestJSON service to request
JSON from remote (non-authenticated) servers and have the results passed
to a callback of your choosing.
*/
var displayGists = true;
if (displayGists) {
Campfire.GistExpander = Class.create({
initialize: function(chat) {
this.chat = chat;
var messages = this.chat.transcript.messages;
for (var i = 0; i < messages.length; i++) {
this.detectGistURL(messages[i]);
}
},
detectGistURL: function(message) {
/* we are going to use the messageID to uniquely identify our requestJSON request
so we don't check pending messages */
if (!message.pending() && message.kind === 'text') {
var links = message.bodyElement().select('a:not(image)');
if (links.length != 1) {
return;
}
var href = links[0].getAttribute('href');
var match = href.match(/^https?:\/\/gist.github.com\/[A-Za-z0-9]+\/?$/);
if (!match) return;
var id = match[0].replace(/^https?:\/\/gist.github.com\/([A-Za-z0-9]+)\/?$/, '$1');
window.propane.requestJSON(message.id(), 'https://api.github.com/gists/' + id, 'window.chat.gistexpander', 'onEmbedDataLoaded', 'onEmbedDataFailed');
}
},
onEmbedDataLoaded: function(messageID, data) {
var message = window.chat.transcript.getMessageById(messageID);
if (!message) return;
var files = data['files'];
for (f in files) {
var file = files[f];
var content = file['content'].replace(/&/g,'&amp;').
replace(/>/g,'&gt;').
replace(/</g,'&lt;').
replace(/"/g,'&quot;').
match(/^.*([\n\r]+|$)/gm).
slice(0,5).
join("");
var link = file['raw_url'];
var file_name = file['filename'];
message.resize((function() {
message.bodyCell.insert({bottom: '<div style="width:100%; margin-top:5px; padding-top: 5px; border-top:1px dotted #ccc;border-bottom:1px dotted #ccc;"><a href="' + link + '" target="_blank">' + file_name + '</a><pre><code>' + content + '</code></pre></div>'});
}).bind(this));
}
},
onEmbedDataFailed: function(messageID) {
/* No cleanup required, we only alter the HTML after we get back a succesful load from the data */
},
onMessagesInsertedBeforeDisplay: function(messages) {
for (var i = 0; i < messages.length; i++) {
this.detectGistURL(messages[i]);
}
},
onMessageAccepted: function(message, messageID) {
this.detectGistURL(message);
}
});
Campfire.Responders.push("GistExpander");
window.chat.installPropaneResponder("GistExpander", "gistexpander");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment