Find Web browser user agent using rails 3

Hi friends,

In rails 3 there is a easy way to Detect the web browser user agent . 🙂

By adding the one line in the controller page, we can get the UA.(@user_agent = request.env[‘HTTP_USER_AGENT’])

In /app/controllers/users_controller.rb

def index
 @users = User.all
  @user_agent = request.env['HTTP_USER_AGENT']

In /app/views/users/index.html.erb

<%= @user_agent %>

That’s All !!!  🙂 🙂 🙂

GitHub Link:

Live Example On Heroku:

Ex snaps for various Web browsers:

This slideshow requires JavaScript.

Multiple File uploading in Rails3 Application using “Papercilp”

Hi friends,

Lets see how to upload multiple files in a rails 3 application.

First create a new rails project and go inside of the project directory.

$ rails new fileuploading
$ cd fileuploading

Add the Gms in  following “Gemfile”

gem ‘nifty-generators’
gem ‘paperclip’

source ''

gem 'rails', '3.0.3'
gem 'nifty-generators'
gem 'paperclip'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://'.....

And  bundle install it.

Now we have to create a scaffold. Do a following commands.

 $ rails g nifty:scaffold Post title:string
 $ rails g nifty:layout

It asks a Permission to Overwrite the layout file. just press “y”.  It shoes like,
Overwrite /home/suresh/deal_projects/paperclip-test/app/views/layouts/application.html.erb? (enter “h” for help) [Ynaqdh]

Again migrate with db.

 $ rake db:migrate
 $ rm public/index.html
Then, Add the following line in  your /config/routes.rb , root :to => “posts#index”
Then, create a model called “Asset”
$ rails g model Asset asset_file_name:string asset_content_type:string asset_file_size:integer asset_upload_at:datetime post_id:integer
$ rake db:migrate

Now in model folder, there is a file called “asset.rb”. Add the following lines into this file.

class Asset < ActiveRecord::Base
belongs_to  :post
has_attached_file  :asset, :styles => {  :large => "640*480",  :medium => "300*300>",  :thumb => "100*100>" }


And add the following lines into “posts.rb” file

class Post < ActiveRecord::Base
attr_accessible :title, :content,  :assets_attributes
has_many  :assets
accepts_nested_attributes_for  :assets,  :allow_destroy  => true

Edit app/controller/posts_controller.rb (Note the new and edit part)

def new
@post =
5.times { }


def edit
@post = Post.find(params[:id])
5.times { }

Edit and add the following lines in your app/view/post/_form.html.erb

<%= form_for @post, :html => { :multipart => true } do |f| %>
<%= f.error_messages %>
<%= f.label :title %><br />
<%= f.text_field :title %>

<% f.fields_for :assets do |asset_fields| %>

<% if asset_fields.object.new_record? %>
<%= asset_fields.file_field :asset %>

<% end %>
<% end %>

<% f.fields_for :assets do |asset_fields| %>
<%unless asset_fields.object.new_record? %>


<%= link_to image_tag(asset_fields.object.asset.url(:thumb)), asset_fields.object.asset.url(:original) %>

<%= asset_fields.check_box :_destroy %>

<% end %>
<% end %>

<p><%= f.submit %></p>
<% end %>

That’s All .

In tour terminal run ” rails s” command and open the “http://localhost:3000” in your browser. 🙂

Selecting the files
Uploaded into project 🙂
GitHub Link:
My hearty thanks to:

Linux 20-years celebration video in tamil

Hi friends,

At 1991, Linus Torvalds, released his Kernel as open source. After that, the Linux Revolution happened.

To celebrate the 20 years of Linux, The Linux Foundation, is doing various activities.
Explore it here.
It released an animation video.

My Brother T.Shrinivasan wanted to translate the video in tamil. So he asked his friend to transcribe the audio as English text. He then also asked me to  convert the English text into Tamil text.

Here the original English version video:

Here the tamil version of the above video:

More info:

🙂 🙂 🙂

Google maps in Rails3 Application — Sample Application

Hi friends,

(New update: For new version(0.9.1) check Jay’s comment below)

(Update: this tutorial works only on gem version 0.7.7 and won’t work on latest gem version 0.8.7)

Using a gmaps4rails gem to display a map in our application

create a rails application using,

$ rails new gmaps

$ cd gmaps

Add this Gem in your Gemfile

gem ‘gmaps4rails’, ‘0.7.7’

Now bundle it ($ bundle install )and migrate with db ( $ rake db:migrate)

Create a scaffold using,

$ rails g scaffold Location name:string address:string longitude:float latitude:float

remove the longitude and latitude fields in _form.html.erb

After that, add this in app/view/layout

<%= yield :head %> (in your header) <%= yield :scripts %> (in your footer)


  <%= stylesheet_link_tag :all %>
  <%= javascript_include_tag :defaults %>
  <%= csrf_meta_tag %>
  <%= yield :head %>
<%= yield %>
<%= yield :scripts %>

In model /app/models/location.rb to add

class Location < ActiveRecord::Base
      def gmaps4rails_address
       def gmaps4rails_infowindow
         "<h4>#{name}</h4>" << "<h4>#{address}</h4>"

add the line in controller /app/controllers/locations_controller.rb

def index
    @locations = Location.all
    @json = Location.all.to_gmaps4rails

In your view app/views/locations/index.html.erb to add a last line as

<%= gmaps4rails(@json) %>

then start the server(http://localhost:3000/locations) to put the name and address, longitude and latitude as set automatically, then will be show the markers as corresponding address and click the marker will shows infowindow as name and address

That’s it!! If you have any questions please feel free to contact me. I will be happy to help where I can.  🙂

Map View

My Sample Application:


Ref Link:

Sending One Time Password via SMS Using Rails3 and SMSAPI

Hi friends,

My need was send one time password via e-mail/sms ,who registered with their E-mail/mobile no.

Lets see “How to send SMS using Rails3 application and smsAPI”

At first we need a smsapi to send SMS via Rails3 application. There is a site, which provides FREE API to send SMS via programming. So, here we need to register with your Domain and mail-id. They also provide codes for various languages 🙂

EX code for RUBY:

require 'net/http'
require 'uri'
Net::HTTP.get_print URI.parse('')

We just modify the code, what ever our application needs,

require 'net/http'
require 'uri'
pass = "Hi+This+is+ur+one+time+passwd:" + rand(999999).to_s
mobile = ARGV.shift
url = "{pass}&senderid=slash&recipient=#{mobile}"
Net::HTTP.get_print URI.parse(url)
Then create a new rails project using,
  $ rails new sms
Go to project directory using,
  $ cd sms
Create scoffold using,
  $ rails generate scaffold name:string phone:string
Now, we have to edit the user controller
  $ gedit /app/controller/users_controller.rb
# POST /users
# POST /users.xml
def create
@user =[:user])


respond_to do |format|
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml  { render :xml => @user, :status => :created, :location => @user }
format.html { render :action => "new" }
format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
Now, we have to write a small def function into that “usres_controller.rb” file
# POST /users
# POST /users.xml
def create
@user =[:user])

smspasswd  #Note this Function

respond_to do |format|
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml  { render :xml => @user, :status => :created, :location => @user }
format.html { render :action => "new" }
format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }

def smspasswd
name =
pass = "Hi+#{name},+This+is+ur+one+time+passwd:" + rand(999999).to_s
phone =
url = "{pass}&senderid=slash&recipient=#{phone}"
Net::HTTP.get_print URI.parse(url)

That’s all
Sample Application:
Download from GitHub link:
      But, This “freesmsapi” does not work with the numbers who activated DND support. 😦

Power of PYTHON and RUBY languages

Hi friends,

Since last week i had worked with Send SMS via rails application. After long search, i found a site called “” which provides API and sends SMS. This site  is very much helpful in sending automated SMS.

They also provide  codes for different languages like “Python, Ruby, PHP, Perl, Java, C, C#, VB.NET”

When i compared the same code for different languages, I was surprised (shocked 😛 )to see that PYTHON and RUBY has the minimal and very efficient code. 🙂


require 'net/http'
require 'uri'
Net::HTTP.get_print URI.parse('<a href=""></a>')


from urllib
import urlopen
print urlopen('').read()

Here are the codes for other languages.


echo file_get_contents("".urlencode('YOUR MESSAGE')."&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBERS");


use strict;

use LWP::UserAgent;

my $ua = new LWP::UserAgent;
my $url='';
my $request = new HTTP::Request('GET', $url);
my $response = $ua->request($request);
my $content = $response->content();
print $content;



public class JavaGetUrl {
public static void main(String[] args) throws Exception {
URL myurl = new URL("");
BufferedReader in = new BufferedReader(
new InputStreamReader(

String inputLine;

while ((inputLine = in.readLine()) != null)



#include <curl/curl.h>

void main() {

long http_code = 0;
CURL *curl;
CURLcode res;

//Initializing the CURL module
curl = curl_easy_init();

if(curl) {

curl_easy_setopt(curl, CURLOPT_URL, "");
res = curl_easy_perform(curl);

if(CURLE_OK == res) {
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);

if(http_code == 200) {
puts("Received 200 status code");
} else {
puts("Did not received 200 status code");
} else {
puts("Could not initialize curl");


using System.IO;
using System.Net;
string connectionString = "";
System.IO.Stream SourceStream = null;
System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);
myRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse webResponse = (HttpWebResponse)myRequest.GetResponse();
SourceStream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
string str = reader.ReadLine();
catch (Exception ex)
Imports System.IO
Imports System.Net
Dim connectionString As String = ""
Dim SourceStream As System.IO.Stream
Dim myRequest As System.Net.HttpWebRequest = WebRequest.Create(connectionString)
myRequest.Credentials = CredentialCache.DefaultCredentials
Dim webResponse As WebResponse = myRequest.GetResponse
SourceStream = webResponse.GetResponseStream()
Dim reader As StreamReader = New StreamReader(webResponse.GetResponseStream())
Dim str As String = reader.ReadLine()

Catch ex As Exception
End Try


Sending SMS via “”

Hi friends,

I found a site which sends sms via website and programs.

They provides their own API and programing codes in ruby,,c,c#., etc.,

First we have to signup with our own domain and register with mail-id and phone number. that’s all. 🙂

Ex code in ruby:

require 'net/http'
require 'uri'
Net::HTTP.get_print URI.parse('<a href="" target="_blank">http://s1.<wbr><wbr>skey=<wbr>8c0185641435ac8a43cf10230a1417<wbr>ac&message=Password:7876&<wbr>senderid=fsmsapi&recipient=<wbr>9943239066</wbr></wbr></wbr></wbr></wbr></wbr></a>')

Now i’m trying to integrate this code into rails3 🙂

How to Send a mail using Gmail account with Rails3, ActionMailer and SMTP

Hi friends,

Action Mailer:

Action Mailer is a framework for building e-mail services. You can use Action Mailer to receive and process incoming email and send simple plain text or complex multipart emails based on flexible templates.

Lets see how to setup the actionmailer with Gmail SMTP.

First we have to create a rails application using

   $ rails new action_mailer

Next we’ll generate a scaffold for a User model with name and email attributes to act as a simple user-registration page.

$ rails genetate scaffold user name:string email:string

Now we have to migrate with DB.

$ rake db:migrate

The generated scaffolding code includes a page for creating users. We want to create a new user and then send them a confirmation email when the form on this page is submitted.

Now, just run the rails server command,

$ rails s

Then, open the “http://localhost:3000

Adding New User

The first thing we’ll do is create a new initializer file called setup_mail.rb and put some configuration options in it. ActionMailer will use sendmail if it’s set up on your machine but we can instead specify SMTP settings in the initializer.

  $ cd /config/initializers/

  $ gedit setup_mail.rb

ActionMailer::Base.smtp_settings = {  
      :address              => "",  
      :port                 => 587,  
      :domain               => "",  
     :user_name            => "thasuresh", #Your user name
      :password             => "actionmailer", # Your password
      :authentication       => "plain",  
      :enable_starttls_auto => true  

You’ll probably want to use a different approach in a production application but this is a good enough approach while our application is in development. Obviously you’ll want to change the domain, user_name and password options to suit your own Gmail account.

Now that we’ve completed the configuration we can generate a new mailer with the following code:

  $ rails generate mailer user_mailer

$ cd /app/mailer

  $ gedit user_mailer.rb

class UserMailer < ActionMailer::Base
default :from => ""

def registration_confirmation(user)
mail(:to =>, :subject => "Registered")

Now we have to create a file called registration_confirmation.text.erb under app/views/user_mailer.

  $ gedit app/views/user_mailer/registration_confirmation.text.erb

Thank you for registering!

/app/controllers/users_controller.rb  (Note the 6th line)

def create
@user =[:user])

respond_to do |format|
UserMailer.registration_confirmation(@user).deliver  #include this line in your users_controller.rb file
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml  { render :xml => @user, :status => :created, :location => @user }
format.html { render :action => "new" }
format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }

mail sent by "ActionMailer"

If you want add user name at the mail, add the following line into registration_confirmation.text.erb


<%= %>,

Thank you for registering!

Added User name

Now if you want add any attachments in the mail add this line into /app/mailer/user_mailer.rb

def registration_confirmation(user)
@user = user
attachments["rails.png"] ="#{Rails.root}/public/images/rails.png")
mail(:to => "#{} <#{}>", :subject => "Registered")

Here my need is send a numeric password, when a user subscribe with his mail id. The password will send by actionmailer. So i added the a single ruby command into

Hi <%= %>,

This is the one time password, You can login into our site using the password given below

Password: <%=rand(999999)%>

Thank You For Registering!

Final output 🙂

That’s all !!!

Here sample “actionmailer” application and which deployed in heroku

GitHub Account link: