How to make embeddable snippets with Rails

Embedding a gist is a doddle - you create the gist, and copy the snippet, and BAM you end up with something like this:

I wanted to add this ability to Spoiler Tweet so that people can embed spoilers on their blogs (and also in the hopes that one day I'll get access to #newtwitter 's right hand side pane.)

Here's an example of a Spoiler Tweet embed:

How'd I do that? Well, with Rails it's incredibly simple. In Spoiler Tweet I have a TweetsController for displaying Tweets.

# app/controllers/tweets_controller.rb
class TweetsController < ApplicationController
  def show
    @tweet = Tweet.find(params[:id])

All I had to do to get an embeddable snippet to appear was to add a show.js.erb template file:

document.write('<%= escape_javascript(render(:partial> "embedded_tweet")) %>');

What this does is insert a javascript snippet into the page that does two things:

  • include a custom stylesheet (for styling your embed). Make sure that this css file is compact and specifically targets your markup.

  • inject a partial onto the page

Note the escape_javascript method - this ensures that your partial parsed in a way that js can understand.

Now to embed the file, just simply have your users put something like this in their template files:

<script src=""></script>

Pretty simple!

Subscribe via RSS

Back to all blog posts