Step by Step Twitter OAuth Integration with Rails

There are many articles posted under this topic but none of them have all information or a Step by Step guide of how to integrate OAuth for use with Twitter Apps and Rails.

So thought of posting one here. Here are few steps which you should follow. The code below is same as provided by the twitter wiki but i have made couple of changes and organized it to make it simple to understand

Step 1 : = You need to get your consumer key and consumer secret # from the twitter OAuth site under this link twitteroauth.

Step 2 := Install OAuth Gem with “gem install oauth” command on ur terminal

Step 3 := Generate a Scaffold using the following command and then migrate the table called “users” to ur database

ruby script/generate scaffold user screen_name:string token:string secret:string

rake db:migrate

Step 4 := Add the following code to your User Controller. Replace the key and secret code with yours 😀

def self.consumer

# The readkey and readsecret below are the values you get during registration“OmwO7wsjtYHjquu6bd6C4w”, “j1kZ6yzsqChkeQtToErUx2LnPQMsSPkXMkiy4F82sPA”,{ :site=>”” })


def create

@request_token = UsersController.consumer.get_request_token

session[:request_token] = @request_token.token

session[:request_token_secret] = @request_token.secret

# Send to to authorize

redirect_to @request_token.authorize_url



Now this is an important part where you need to set the call back url Which u will define while you register your app at twitter OAuth site. Again add this to the UserController

def callback
@request_token =,
# Exchange the request token for an access token.
@access_token = @request_token.get_access_token
@response = UsersController.consumer.request(:get, ‘/account/verify_credentials.json’,
@access_token, { :scheme => :query_string })
case @response
when Net::HTTPSuccess
user_info = JSON.parse(@response.body)
unless user_info[‘screen_name’]
flash[:notice] = “Authentication failed”
redirect_to :action => :index

# We have an authorized user, save the information to the database.
@user ={ :screen_name => user_info[‘screen_name’],:token => @access_token.token,:secret => @access_token.secret })!
# Redirect to the show page
RAILS_DEFAULT_LOGGER.error “Failed to get user info via OAuth”
# The user might have rejected this application. Or there was some other error during the request.
flash[:notice] = “Authentication failed”
redirect_to :action => :index

As you can see from the comments this callback action exchanges the request token for an access token. Since the user is going to need to type in the username and password at Twitter I avoid prompting for it and instead we fetch that using a call to verify_credentials. This saves duplicate entry and makes it easier on the user. This also prevents users with multiple accounts from giving you one username and then using another when they login to twitter. The access token and secret are what is needed to act on behalf of a user, so those are saved to the database. The show action then uses this information to display some data like so:

def show
@user = User.find(params[:id])
# Get this users favorites via OAuth
@access_token =, @user.token, @user.secret)
RAILS_DEFAULT_LOGGER.error “Making OAuth request for #{@user.inspect} with #{@access_token.inspect}”
@response = UsersController.consumer.request(:get, ‘/favorites.json’, @access_token,
{ :scheme => :query_string })
case @response
when Net::HTTPSuccess
@favorites = JSON.parse(@response.body)
respond_to do |format|
format.html # show.html.erb
RAILS_DEFAULT_LOGGER.error “Failed to get favorites via OAuth for #{@user}”
# The user might have rejected this application. Or there was some other error during the request.
flash[:notice] = “Authentication failed”
redirect_to :action => :index

Finally the views

<b>Screen name:</b>
<%=h @user.screen_name %>
<% @favorites.each do |fav| %>
<li><b><%= fav[‘user’][‘screen_name’]  %></b>: <%=h fav[‘text’]  %></li>
<% end %>


the new.html.erb

<h1>New user</h1>

<% form_for(@user) do |f| %>
<%= f.error_messages %>
We’ll be sending you to Twitter in a moment to login and grant us access.
Once you allow us in we’ll give you the super-cool feature
you’bve heard about.
<%= f.submit “Grant Access” %>
<% end %>
<%= link_to ‘Back’, users_path %>

Also Add validates_presence_of to the User model for screen_name, token and secret.

And in the routes.rb set the following route

map.connect ‘/callback’, :controller => ‘users’, :action => ‘callback’

Thats it you are ready for the twitter Login. Start the server and open localhost:3000/users
and you will see the magic.

These are all the steps. Post me a comment if you still face any isssues.

Please note : – This method might not function correctly now since the method of authentication has changed. Thanks

Be Sociable, Share!

localization or internationalization in rails

Most of the new websites are having the feature of localization or internationalization on their site. With introduction of rails 2.3 this feature is provided by default But if you are still working in rails 2.0 or 2.1 then GlobalLite is the solution for you..

How ever while implement it in one of my projects I noticed that the localized date time module used in the plugin has a problem when you have time_select tag in your form.

So when you use a time_select tag in your form it will generate an error message “Can’t convert nil into string”. The problem is in the file called localized_action_view.rb which you will find in plugins/globalite/lib/rails folder.

Apply the code below to get it fixed

def select_month(date, options = {}, html_options = {})
if options[:locale]
@original_locale = Locale.code
Locale.code = options[:locale]
val = date ? (date.kind_of?(Fixnum) ? date : date.month) : ”
if options[:use_hidden]
hidden_html(options[:field_name] || ‘month’, val, options)
month_options = []
monthnames = :date_helper_month_names.l
abbr_monthnames = :date_helper_abbr_month_names.l
month_names = options[:use_month_names] || (options[:use_short_month] ? abbr_monthnames : monthnames)
month_names.unshift(nil) if month_names.size < 13
1.upto(12) do |month_number|
month_name = if options[:use_month_numbers]
elsif options[:add_month_numbers]
month_number.to_s + ‘ – ‘ + month_names[month_number]

month_options << ((val == month_number) ?
%(<option value=”#{month_number}” selected=”selected”>#{month_name}</option>\n) :
%(<option value=”#{month_number}”>#{month_name}</option>\n)
@selector = select_html(options[:field_name] || ‘month’, month_options, options)
Locale.code = @original_locale if options[:locale]
return @selector
#  Locale.code = @original_locale if options[:locale]
#  return @selector

You may even Comment the date module in the code  plugins/globalite/lib/rails/localized_action_view.rb

this will make use of default rails date time. so nothing will get affected if you do this. But the solution mentioned about is a better one.

Njoi the power of Internationalization and make sure site global.

Be Sociable, Share!

File column plugin not working with rails 2.2

Older version of file_coulmn plugin is not working in rails 2.2.

If you want to get working in rails 2.2 then you need to modify file_coulmn.rb file.

Update the line #619 in vendor/plugins/file_column/lib/file_column.rb from


Or you can download the latest plugin from the

If you are looking to implement the old File column plugin you may visit

Be Sociable, Share!

Google Charts in Rails (gc4r)

Well I m going to cover the topic how to generate charts using rails. there are number of options available such as follows

Here are the plugins through which we can generate charts in rails

1) Gruff charts

2) Sparklines

3) Scruffy charts

4) Ziya plugin (flash charts)

I found google charts the best of these..( ofcourse that suited my requirements). The gc4r plugin in rails is really helpful for easy integration of google charts in your rails application.

Here is how Charts are generated by Google API.

Install: ruby script/plugin install

Supported features:
1.line chart chart (vertical and horizontal)
3.pie chart (both 2D and 3D)
4.title, title color and size colors and legend scaling
7.multiple axis


#In method of controller

Default Chart or Hello World Chart
@chart =

Set the width of chart
@chart = :width => 300, :height => 200

Set the data
dataset = :data => [10,50,4,10,16]
data = :datasets => dataset
@chart = :width => 300, :height => 200 = data

add a chart title
dataset = :data => [10,50,4,10,16]
data = :datasets => dataset
@chart = :width => 200, :height => 150, :title => ‘Java vs. Ruby Montly Job Opportunities’ = data

Set title in array instead of string
dataset = :data => [10,50,4,10,16]
data = :datasets => dataset
@chart = :width => 200, :height => 150, :title => [‘Java vs. Ruby’, ‘Montly Job Opportunities’] = data

Multiple data in chart
dataset1 = :data => [10,50,4,10,16]
dataset2 = :data => [99, 81, 25, 54, 80]
data = :datasets => [dataset1, dataset2]
@chart = :width => 200, :height => 150, :title => [‘Java vs. Ruby’, ‘Montly Job Opportunities’] = data

Add colors
dataset1 = :data => [10,50,4,10,16],:color => ‘FF0000?
dataset2 = :data =>[99,81,25,54,80],:color => ‘0000FF’
data = :datasets => [dataset1, dataset2]
@chart = :width => 200, :height => 150, :title => [‘Java vs. Ruby’, ‘Montly Job Opportunities’] = data

Define legend
dataset1 = :data =>[10,50,4,10,16],:color => ‘FF0000?, :title => ‘Java’
dataset2 = :data=>[99,81,25,54,80],:color => ‘0000FF’, :title => ‘Ruby’
data = :datasets => [dataset1, dataset2]
@chart = :width => 200, :height => 150, :title => [‘Java vs. Ruby’, ‘Montly Job Opportunities’] = data

Define Axis
dataset1 = :data =>[10,50,4,10,16],:color => ‘FF0000?, :title => ‘Java’
dataset2 = :data=>[99,81,25,54,80],:color => ‘0000FF’, :title => ‘Ruby’
data = :datasets => [dataset1, dataset2]
axis = :axis  => [GoogleChartAxis::LEFT, GoogleChartAxis::BOTTOM]
@chart = :width => 250, :height => 150, :title => [‘Java vs. Ruby’, ‘Montly Job Opportunities’] = data
@chart.axis = axis

Define Right and X Axis
dataset1 = :data=> [10,50,4,10,16],:color => ‘FF0000?,  :title => ‘Java’
dataset2 = :data=>[99,81,25,54,80],:color => ‘0000FF’, :title => ‘Ruby’
data = :datasets => [dataset1, dataset2]
axis = :axis  => [GoogleChartAxis::LEFT, GoogleChartAxis::BOTTOM,  GoogleChartAxis::RIGHT, GoogleChartAxis::BOTTOM]
@chart = :width => 300, :height => 200, :title => [‘Java vs. Ruby’, ‘Montly Job Opportunities’] = data
@chart.axis = axis

Define Bar Chart:
@chart = :width => 300, :height => 200, :title => [‘Java vs. Ruby’, ‘Montly Job Opportunities’]

Define 3D Pie Chart:
@chart = :width => 400, :height => 200, :title => [‘Java vs. Ruby’, ‘Montly Job Opportunities’], :chart_type  => GooglePieChart::PIE_3D

<%= image_tag @chart.to_url %>

Be Sociable, Share!

Stress/Benchmark Testing on rails with httperf

Want to do benchmark or stress testing on your rails applications? Then look @ httpref

What is httpref?

Httperf is a tool for measuring web server performance. It provides a flexible facility for generating various HTTP workloads and for measuring server performance. The focus of httperf is not on implementing one particular benchmark but on providing a robust, high-performance tool that facilitates the construction of both micro- and macro-level benchmarks. The three distinguishing characteristics of httperf are its robustness, which includes the ability to generate and sustain server overload, support for the HTTP/1.1 and SSL protocols, and its extensibility to new workload generators and performance measurements.

Source url : –

Steps to do

1) download httpref from

2) install the tool

3) check out commands on

Thats all

Find out how many http requests your site can handle..


For more info you can post comments here

Be Sociable, Share!

Export data to Excel (xls) in Ruby on Rails

The code Below will help to export the data in excel in Ruby on Rails


class UserController < ApplicationController
  def export
    headers['Content-Type'] = "application/"
    headers['Content-Disposition'] = 'attachment; filename="report.xls"'
    headers['Cache-Control'] = ''
    @users = User.find(:all)



<%= link_to "Export as Excel", export_person_url %>


<table border="1">
  <% @users.each do |u| %>
   <td><%= %></td>
  <% end %>

Please note :- This method might might be deprecated. You may visit for more info. Thanks

Be Sociable, Share!
1 2 3 4