Using Sinatra 0.9.2 this is an easy to way to get an updating single tweet in your application. I am using the most recent HAML gem ( haml 3.0.5 ). I am also deploying this application with Heroku, not that it will make a difference, but it may help.

It did take a few hours to get the function to call correctly, and the HAML ( or Sinatra ) people may say that there better ways to instantiate this, but that is why I am writing this post.

You need to include two gems in your app.rb file in addition to the norm:

1
2
3
4
5
6
7
8
 
require 'rubygems'
require 'sinatra'
require 'haml'
 
# include these
require 'open-uri'
require 'json'

Open-URI is a Ruby library so you don’t need to install anything, just include it. I am also using Ruby 1.9 for this application. You will need to $ sudo install gem json if you haven’t already done so.

Then I created a div in my index.haml file with the following code:

54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
 
            %div#tweetbox
              %h2
                News
              %span
                via Twitter
              :ruby 
                def twitterApp
                  url =  "http://twitter.com/statuses/user_timeline/yourusername.json?count=1"
                  buffer = open(url, "UserAgent" => "Ruby-Wget").read
                  result = JSON.parse(buffer)
                  result.each do |subject|
                    return subject['text']
                  end
                end
              %p= twitterApp

Wammy! now you have a nice single post to add to your application. No frills or tacky Twitter icons. Just simple text. The cool part is that you can implement additional parts of the json feed by concatenating strings in the return statement.

Something like this:

64
65
66
 
 
     return subject['text'] + ' ' + subject['url'] + ' ' + subject['description']

It took me far too long to get this correct with the HAML, so I hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *