Will_paginate Customization

Will_paginate will give the neatful form of pagination as seen in the earlier. Here we can see the
the some customized form displaying the pagination displays,

<%= will_paginate @display_data %>

— will  display the normal pagination navigation icon as seen.

<%= will_paginate @display_data, :page_links => false %>

— will  display the normal previous and Next icon exlcuding the page numbers.


Find Record/Information Time Line

In Rails, we can find the last updated record date/time information with the current date/time information. This can be done as seen below,

def self.didwhen(old_time)
val = Time.now – old_time
if val < 10 then
result = ‘just a moment ago’
elsif val < 40  then
result = ‘less than ‘ + (val * 1.5).to_i.to_s.slice(0,1) + ‘0 seconds ago’
elsif val < 60 then
result = ‘less than a minute ago’
elsif val < 60 * 1.3  then
result = “1 minute ago”
elsif val < 60 * 50  then
result = “#{(val / 60).to_i} minutes ago”
elsif val < 60  * 60  * 1.4 then
result = ‘about 1 hour ago’
elsif val < 60  * 60 * (24 / 1.02) then
result = “about #{(val / 60 / 60 * 1.02).to_i} hours ago”
result =old_time.strftime(“%H:%M %p %B %d, %Y”)

By passing the created_dt value to the above function from the rails view section to get printed.The synatax is like,

<% timenow1 = ModelName.didwhen(tablename.created_at)    %>

Customized URL-Rewriting

In my rails application, i did custom URL rewrite since then my project navigation will look like this,

http://localhost:3000/   — redirecting to index page

For doing this you have to write  the map condition in your rails rout.rb files. The will be like this,

As in my application just want to show simplified custom url as above for that in the route.rb i wrote like this,

map.home ‘/home’,:controller=>”signup”, :action=>”update”

map.profile ‘/profile’,:controller=>”signup”, :action=>”profile”

In my view section for those  navigation, i.e link_to tage look like this,

<%= link_to “Home” , {:controller => “signup”, :action => “signup”} %>

<%= link_to “Profile” , {:controller => “signup”, :action => “profile”} %>

That’s all to get the desired Custom URL.


For more info on URL rewrite can get here :

Rails Booklet

Here is the quick guide to know the basic of Ruby on Rails. Please click the link to download,

Ruby on Rails Book-Let

find_by in rails

Using find_by method, we can have Database interaction on easy as like other language. In rails there are different types of find mehtods, they are


Used to find the particular the value with all the field in the row.

Used to find the particular the value specified in fieldname on the table.


3. find_by_sql():
This method will give the user to manage the query customization as the user like.

Signup.find_by_sql(“select * from signups where f.userid=’#{session[:user_id]}’ and s.id=f.followid limit 30”)


pagination_mainRuby on Rails pagination functionalities done by installing the simple will_paginate plugin. This can be installed by using the following  command executed on your ruby for Windows,

Once installed, you need to include the plugin library as

c:\wamp\Ruby>gem install will_paginate

require ‘will_paginate’

in the config/environment.rb bottom after the  below code in the  .rb file,

Rails::Initializer.run do |config|

Live pagination in code:

Add the below code in your model to access by all the controller methods,

def display_data
if (page!=”)
 paginate(:all,:page => page, :conditions => [“user_id = ?”, id], :per_page =>10)
 paginate(:all,:page => 1, :conditions => [“user_id = ?”, id], :per_page =>10)

call the below function in your controller to invoke the paginate from the disaply_data as follows,

  @display_data = MessageHistory.more_update(params[:date],params[:page],session[:user_id])

Now here we need to show the pagination in the User view, for that we need to add the below code to invoke the pagination from the controller.

 <%= will_paginate @display_data %>

 Thats all  We have Compeleted the pagination. Once the above run sucessfully you will get the pagination like in the below format on your web page.

For the CSS updates goto this links and copy the CSS  and place it in your project folder (public/stylesheet)


Uploading File

Action Mailer is the Rails component that enables applications to send and receive e-mail. In this chapter we will see how to send an email using Rails. So lets start with creating a emails project using following command.

C:\ruby\> rails emails

This will create required framework to proceed. Now we will start with configuring Action Mailer.

Action Mailer – Configuration

Following are the steps you have to follow to complete your configuration before proceeding with actual work:

Go into config folder of your emails project and open environment.rb file and add the following line at the bottom of this file.

ActionMailer::Base.delivery_method = :smtp

This tells ActionMailer that you want to user SMTP server. You can also set it to be :sendmail if you are using a Unix-based operating system such as Mac OS X or Linux.

Add the following lines of code to the bottom of your environment.rb as well.

ActionMailer::Base.server_settings = {
   :address => “smtp.yourdomain.com”,
   :port => 25,
   :domain => “yourdomain.com”,
   :authentication => :login,
   :user_name => “username”,
   :password => “password”,
For the above smtp info i am using google smtp details. For more information on the smtp see my old post.

Replace each hash value with proper settings for your Simple Mail Transfer Protocol (SMTP) server. You can take this information from your Internet Service Provider if you already don’t know. You don’t need to change port number 25 and authentication type if you are using standard SMTP server.

You may also change the default email message format. If you prefer to send email in HTML instead of plain text format, add the following line to config/environment.rb as well:

ActionMailer::Base.default_content_type = “text/html”

ActionMailer::Base.default_content_type could be set to “text/plain”, “text/html”, and “text/enriched”. The default value is “text/plain”.

Next step will be to create a mailer

Generate a mailer:
Use the following command to generate a mailer as follows:

C:\ruby\> cd emails
C:\ruby\emails> ruby script/generate mailer Emailer

This will create a file emailer.rb in app\models directory. Check the content of this file is as follows:

class Emailer < ActionMailer::Base


Let’s create one method as follows.

class Emailer < ActionMailer::Base
   def contact(recipient, subject, message, sent_at = Time.now)
      @subject = subject
      @recipients = recipient
      @from =
      @sent_on = sent_at
   @body[“title”] = ‘This is title’
     @body[“email”] =
      @body[“message”] = message
      @headers = {}

The contact method has four parameters a recipient, subject, message and a sent_at, which defines when the e-mail is sent. The method also defines six standard parameters that are a part of every ActionMailer method:

  • subject defines the e-mail subject.
  • body is a Ruby hash that contains values with which you can populate the mail template. You created three key-value pairs: title, email, and message
  • recipients is a list of the people to whom the message is being sent.
  • from defines who the e-mail is from.
  • sent_on takes the sent_at parameter and sets the timestamp of the e-mail.
  • headers is another hash that enables you to modify the e-mail headers. For example, you can set the MIME type of the e-mail if you want to send either plain text or HTML e-mail.

Now we will create a mailer template which is just text with standard Rails <%= %> placeholders scattered throughout.

Put following code in app/views/contact.rhtml file


You are having one email message from <%= @email %> with a tilte

<%= @title %>
and following is the message:
<%= @message %>


Next we will create a controller for this application as follows:

C:\ruby\emails> ruby script/generate controller Emailer

Now lets define a controller method in emailer_controller.rb which will call Model method to send actual email as follows:

class EmailerController < ApplicationController
   def sendmail
      email = @params[“email”]
   recipient = email[“recipient”]
   subject = email[“subject”]
   message = email[“message”]
      Emailer.deliver_contact(recipient, subject, message)
      return if request.xhr?
      render :text => ‘Message sent successfully’


To deliver e-mail using the mailer’s contact method, you have to add deliver_ to the beginning of the method name. You add a return if request.xhr? so that you can escape to Rails Java Script (RJS) if the browser does not support JavaScript and then tell the method to render a text message.

You are almost done except to prepare a screen from where you will get user information to send email. So lets define one screen method index in controller and corresponding view:

Add following code in emailer_controller.rb file

   def index
      render :file => ‘app\views\emailer\index.rhtml’

Now let’s define our view in app\views\emails\index.rhtml

<h1>Send Email</h1>
<%= start_form_tag :action => ‘sendmail’ %>
<p><label for=”email_subject”>Subject</label>:
<%= text_field ’email’, ‘subject’ %></p>
<p><label for=”email_recipient”>Recipient</label>:
<%= text_field ’email’, ‘recipient’ %></p>
<p><label for=”email_message”>Message</label><br/>
<%= text_area ’email’, ‘message’ %></p>
<%= submit_tag “Send” %>
<%= end_form_tag %>

Now test your application by using This displays following screen and by using this screen now you will be able to send your message to anybody.


This will send your message and will display text message that “Message sent successfully”

For more information on how to send email using Rails, look at ActionMailer.

Orginal Post From:


Running Successfully the above code in your ruby server the Action Mailer extension should enble already. Enabling the Action Mailer please see the previous post.

Installing Rails on Windows

In order to have a fully working development environment, you can use your PC. You will need to install:

Ruby – the language Ruby
Gems – the plug-in manager for Ruby
Scite or FreeRIDE – IDE for Ruby
MySQL – the database
MySQL query builder / MySQL admin tools – GUI to create databases, add users and create tables Rails Framework

Here i am going to give you the detail information on how to install ruby on rail framework, and i am assuming that you already installed the Wamp/MYSQL in you system. The WAMP/MYSQL is must to run the ruby on rail framework.

1. Installing Ruby

This is easy. Just get the latest One-click Installer for Windows (http://rubyinstaller.rubyforge.org/wiki/wiki.pl)(currently 1.8.2-15). Installation is simple, and indeed one-click. Once the installation is complete, check that path to ruby\bin directory is in your PATH variable (Run “cmd”, then type “path” at the prompt and check that the path is there.

The great thing about the one-click installer is that it comes with Ruby Gems, Scite and FreeRIDE preinstalled. The thing to watch out for is that one-click installer does not have the very latest version of Ruby, so when you are reading Ruby Docs, make sure you know which version of Ruby you have (run “ruby -v” in the command prompt).

2. Installing Rails

2.1. Go into the ruby bin directory and run this command from the command prompt:
gem install rails –include-dependencies

(If this command gives you an error, you do not have the latest version of gems installed. Run “gem -v”, it should be 0.8.10. If it’s an earlier version, I recommend to reinstall the newest package – see beginning of the tutorial).

This command will install rails 1.0 and RDoc documentation for it. It should take up to 5-10 minutes, so do not worry when for a couple of minutes you just see a message “Updating Gem source index for: http://gems.rubyforge.org/” – there is no progress bar or any other indication of activity, but it is doing the work.

At the end you should see something like this:

2.2. After that, create a directory for all of your projects. I just have one in the ruby directory. Go into this directory by using the “cd c:\ruby/myprojectsdir” and run

rails firstproject

You should see something similar:

2.3. Finally, “cd firstproject” and run

ruby script/server

This will run the file “server” (no extension) in the script subdirectory of “firstproject directory”, which will in turn run the Rails built-in web server WEBrick. Test the web server by opening the following address in your browser:

You should see the following pic:

One of the drawbacks of having a Ruby-based web server is that WEBrick needs to run in its separate command prompt window, so you should be careful not to close the window down incidentally, or you will need to restart the web server.

Congratulations! YOU ARE ALMOST DONE!

Now you have to create a project in follownig way,

3. Rails in action

3.1. Now that the database model was prepared, we need to switch it on for our project. Go into your rails project subdirectory (you remember where you created it, right?). In the “config” subfolder you will find file database.yml. Open it and find the “development” section. In it, change database name to “firstproject”, username to “rails”, password to rails user password. Leave socket unchanged. Here is how it will look like:

dapter: mysql
database: firstproject
username: mysql_admin
password: mysql_pass
socket: /path/to/your/mysql.sock

In order for those changes to work, you will need to restart the WEBrick server. Close the WEBrick window and run the server command again:

ruby script/server

3.2. You have the database schema defined and you configured Rails to access your database. Now, what we need is to create the class called “Story”. The easiest way to go is to create a scaffold, which is basically a default script to work with the standard database operations under the acronym of CRUD (Create Read Update Delete or in SQL terms: INSERT, SELECT, UPDATE and DELETE). To do this, again go to your script’s directory and run this command:

ruby script\generate scaffold Story

Make sure that you use the capital “S” – this is actually a Ruby rule that you need to follow – class names need to be capitalized. So, this is where the magic happens – you do not need to define the class in Ruby the “hard-way”. You define the class variables (so-called states) only once – in the database, and then those variables are automatically recognized by Rails and a standard CRUD framework is applied, which you can replace with your own code as you go.

3.3. Finally, check that everything works by going to this link:

For fun, try creating, updating and deleting records and see how the table records are automatically updated in the MySQL CC or Query Browser.

One of the drawbacks of having a Ruby-based web server is that WEBrick needs to run in its separate command prompt window, so you should be careful not to close the window down incidentally, or you will need to restart the web server.

Congratulations! YOU ARE ALMOST DONE!
Original Post from :

Importing Contacts from GMAIL,Yahoo,MSN & Hotmail

This is another post by me, hope this post will help you, if you are struck in fetching or grab contacts from Yahoo, Gmail and Hotmail. This is possible using gem ‘contacts’.

So here I am posting my code, I know there are lot of things and code available for this, but this is the exact code which I am using.

If you are running an application or want to create a new go ahead, I am writing a new application here but you can add it in your existing code as well.

open your command or console prompt and go into your application directory, here I am creating new:

rails contact

this will create a particular set of files and directories in your application. Now go into your directory, before start working any further be sure that you have installed ‘contacts’ gem with the latest version i.e 1.0.13, to install ‘contacts’ type :

for linux users : sudo gem install contacts

for windows : gem install contacts

if already have but older version update it : sudo gem update contacts

Now open your environemnt.rb file and below this line write

Rails::Initializer.run do |config|


require ‘contacts’

be sure to restart your server.

Now open the controllers folder and create this method in any controller if you have or where you want to display this. In my case I am writing this in my account_controller.rb

def invite_friends
#@user = User.find(params[:id])

def import
@users = User.find(params[:id])
@sites = {”gmail”  => Contacts::Gmail, “yahoo” => Contacts::Yahoo, “hotmail” => Contacts::Hotmail}
@contacts = @sites[params[:from]].new(params[:login], params[:password]).contacts
@users , @no_users = [], []
@contacts.each do |contact|
#if u = User.find(:first , :conditions => @users.email = ‘#{contact[1]}’ , :include =>[:user])
if u = User.find(:first , :conditions => “email = ‘#{contact[1]}’” )
@users << u
@no_users << {:name => contact[0] , :email => contact[1]}
respond_to do |format|
format.html {render :template => ’shared/_contact_list’, :layout => false}
format.xml {render :  xml => @contacts.to_xml}

before creating this two method, just be sure that you are giving the user id from invite_friends method to import method.

Open up your invite_friends.html.erb and paste this code :

<% form_tag :action => ‘import’, :id => @user do %>

<select name=”from” id=”from”>
<option value=””>Select Id</option>
<option value=”gmail”>Gmail</option>
<option value=”yahoo”>Yahoo</option>
<option value=”hotmail”>Hotmail</option>

<BR />
<p>Please Enter Your Email Address Below : <BR />
<input type=”text” name=”login”></p>
<p>Enter Your Password :<BR />
<input type=”password” name=”password”></p>

<p><h4>Note : we are not going to save your Password anywhere </h4></p>
<p><%= submit_tag ‘Find My Friends’ %>

<% end %>

Now start your server, open up firefox and type the address (in my case it is) : http://localhost:3000/account/invite_friends

Select any service like Yahoo, Hotmail or Gmail give the corresponding username and Password and hit submit.

You will get an error message that missing template, to remove that create a folder ’shared’ in /app/views/ and create a new file name ‘_contact_list.html.erb’ and paste the below code :

<% for i in @contacts %>
<input type=”checkbox” name=”email[]” id=”email_<%= i %>” value=”<%= i %>” /><%= i %><br>
<% end %>

this will help you to take further actions on fetched email addresses, that’s it. You have done..

If you are facing any problems, leave a comment, I will get back in touch with you, and if your code works, don’t forget to leave a comment.

Thanks to ‘contacts’ and thanks to you all also.


Here in the above code you are including the ‘Contacts’. Its a GEM library need to install in your ruby server if not exist already,

C:\> gem install contacts

follow the steps to install the GEMS,

Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/ferret-0.11.6

You have to install the ferret-0.11.6 from the following link available as a zip file


download and extract the file and paste it in the c:/ruby/lib/ruby/gems/1.8/gems/ folder.

After installing it try to run

gem install contacts

Your gem should install.
Original Post From:


Sending Mail Using GMAIL SMTP

Sending mails using the GMAIL SMTP can done using rails smtp_tls plug-in available in the below links.Before downloding the plug-in you should install the action mailer plug-in to support rails mail sending.


Download the latested vertion of smtp_tls from the list available, Extract the zip file and navigate to the folder location \lib\smtp_tls.rb. Copy the file and paste it in your aplication lib folder (app\lib)

In your application, open environment.rb file and paste the below content on the bottom of the file

require “smtp_tls”

ActionMailer::Base.smtp_settings = {
:address => “smtp.gmail.com”,
:port => 587,
:domain => ‘gmail.com’,
:user_name => “
:password => “password”,
:authentication => :plain

ActionMailer::Base.default_content_type = “text/html”

            The Action mailer setting is not limited to the GMAIL account only. You can use this Action mailer setting for other third party smtp server (YAHOO,HotMail etc) as changing the address,port,username, password and authendication of the above.

« Older entries