Showing posts with label Ruby On Rails. Show all posts
Showing posts with label Ruby On Rails. Show all posts
 Ruby on Rails Tutorial



Rails Logo

Ruby on Rails is an extremely productive web application framework written in Ruby by David Heinemeier Hansson.
This is a open source Ruby framework for developing database-backed web applications.
This tutorial will give you a complete understanding on Ruby on Rails.

Ruby on Rails 2.1.x Tutorial

Rails Logo

Ruby on Rails is an extremely productive web application framework written in Ruby by David Heinemeier Hansson.
This is a open source Ruby framework for developing database-backed web applications.
This tutorial will give you a complete understanding on Ruby on Rails 2.1.x.

Ruby on Rails 2.1 - Applications' Unit Testing

Introduction:

Before proceeding let's have a quick look of few definitions:
  • The Tests - They are test applications that produce consistent result and prove that a Rails application does what it is expected to do. Tests are developed concurrently with the actual application.
  • The Assertion - This is a one line of code that evaluates an object (or expression) for expected results. For example, is this value = that value? is this object nil?
  • The Test Case - This is a class inherited from Test::Unit::TestCase containing a testing strategy comprised of contextually related tests.
  • The Test Suite - This is a collection of test cases. When you run a test suite, it will, in turn, execute each test that belongs to it.

Rails Testing:

When you run the helper script script/generate to create controllers and models, Rails generate a framework for unit and functional tests. You can get pretty good test coverage by filling in the framework with tests for the functionality you write. There are two important points to test in a Rails application:
  • Testing the Models.
  • Testing the Controllers.
This tutorial will cover both the testings in brief. So let's create one testapp to understand the concept.
C:\ruby> rails -d mysql testapp

Database Setup:

Till now we have used only Rails application's development database, but now you needed to make sure that the testing database is also created and appropriate section of your config/database.yml file was set up correctly.
Let's create development and testing databases as follows:
mysql> create database testapp_test;
Query OK, 1 row affected (0.01 sec)

mysql> create database testapp_development;
Query OK, 1 row affected (0.01 sec)

mysql> use testapp_test;
Database changed

mysql> grant all privileges on testapp_test.* 
          to 'root'@'localhost' identified by 'password';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

Configuring database.yml:

Configure your config/database.yml as follows:
development:
  adapter: mysql
  encoding: utf8
  database: testapp_development
  username: root
  password: password
  host: localhost
test:
  adapter: mysql
  encoding: utf8
  database: testapp_test
  username: root
  password: password
  host: localhost
production:
  adapter: mysql
  encoding: utf8
  database: testapp_production
  username: root
  password: password
  host: localhost

Generate Migration:

Assume you have a table containing books, including their titles, price and a small description. The following migration sets up this table:
testapp > ruby script/generate migration books
Now modify the testapp/db/migrate/20080616170315_books.rb file as follows:
class Books < ActiveRecord::Migration
  def self.up
     create_table :books do |t|
        t.string     :title, :limit => 32, :null => false
        t.float      :price
        t.text       :description
        t.timestamp  :created_at
     end
  end
  def self.down
    drop_table :books
  end
end
Now run the migration as follows:
testapp > rake db:migrate
This will create books table in testapp_development database. Now after this we need to set up your test database using rake command as follows:
C:\ruby\testapp > rake db:test:clone_structure
This will clone testapp_development database into testapp_test database. It means whatever you have in development database, now you will have in test database as well.

Testing Models:

When you generate a model with the generate script, Rails also generates a unit test script for the model in the test directory. It also creates a fixture, a YAML file containing test data to be loaded into the testapp_test database. This is the data against which your unit tests will run:
testapp > ruby script/generate model Book
      exists  app/models/
      exists  test/unit/
      exists  test/fixtures/
      create  app/models/book.rb
      create  test/unit/book_test.rb
      create  test/fixtures/books.yml
      create  db/migrate
      create  db/migrate/20080616164236_create_books.rb
As you write code in the model classes, you'll write corresponding tests in these files. So let's create two test book records using YAML in test/fixtures/books.yml as follows:
perl_cb:
  id: 1
  title: 'Ruby Tutorial'
  price: 102.00
  description : 'This is a nice Ruby tutorial'
java_cb:
  id: 2
  title: 'Java Programming'
  price: 62.00
  description : 'Java Programming for the beginners'
Now let's relace exsiting code in book unit test file test/unit/book_test.rb with the following code:
require File.dirname(__FILE__) + '/../test_helper'

class BookTest < ActiveSupport::TestCase
  fixtures :books

  def test_book

    perl_book = Book.new :title => books(:perl_cb).title, 
                         :price => books(:perl_cb).price,
                         :description => books(:perl_cb).description,
                         :created_at => books(:perl_cb).created_at

    assert perl_book.save

    perl_book_copy = Book.find(perl_book.id)

    assert_equal perl_book.title, perl_book_copy.title

    perl_book.title = "Ruby Tutorial"

    assert perl_book.save
    assert perl_book.destroy
  end

end
Finally, run the test method as follows:
testapp > ruby test/unit/book_test.rb
Here's the output of running the successful test case:
testapp > ruby test/unit/book_test_crud.rb 
Loaded suite ./test/unit/book_test
Started
.
Finished in 0.0625 seconds.

1 tests, 4 assertions, 0 failures, 0 errors
What has happend here:
  • The BookTest method starts off by creating a new Book object using the title and other fields from the first record in the text fixture/books.yml. The resulting object is stored in the perl_book instance variable.
  • The first assertion tests that saving the Book object was successful.
  • Next, the book object is retrieved using the find method and stored in another instance variable named perl_book_copy. The success of this retrieval is tested in the next assertion, which compares the titles of both book objects. At this point, we've tested the ability to create and read a database record.
  • The solution tests updating by assigning a new title to the object stored in perl_book and then asserts that saving the change is successful.
  • Finally, the ability to destroy a Book object is tested.
This is how we can test our Rails Models.

Testing Controllers:

Controller testing is also known as functional testing. Functional testing tests the following type of functionalities of the controllers:
  • Is the response redirected as expected ?
  • Is the expected template rendered?
  • Is the routing as expected
  • Does the response contain the expected tags?
Rails framework supports 5 types of requests and to write a functional test, you need to simulate any of the five HTTP request types that your controller will process. :
  • get
  • post
  • put
  • head
  • delete
Request type "get" and "post" are the most commonly used in controller testing. All these methods take four arguments:
  • The action of a controller
  • An optional hash of request parameters
  • An optional session hash
  • An optional flash hash
In this tutorial, we will see how to use get method to test our controller. You can test rest of the methods in similar way.
When you generate a controller with generate, Rails creates a functional test script for the controller as follows:
testapp > ruby script/generate controller Book
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/book
      exists  test/functional/
      create  app/controllers/book_controller.rb
      create  test/functional/book_controller_test.rb
      create  app/helpers/book_helper.rb
As you write code in the controller classes, you'll write corresponding tests in these files. Before that let's define our controller functions list, show, and search insideapp/controllers/book_controller.rb as follows:
class BookController < ApplicationController
  def list
    @book_pages, @books = paginate :books, :per_page => 10
  end

  def show
    @book = Book.find(params[:id])
  end

  def search
    @book = Book.find_by_title(params[:title])
    if @book
      redirect_to :action => 'show', :id => @book.id
    else    
      flash[:error] = 'No such book available'
      redirect_to :action => 'list'
    end
  end
end
NOTE: You would need two views templates for show and list method. You can define those views and test them, but right we will proceed without defining those views.
Now let's reuse our test fixture which is in test/fixtures/books.yml file as follows:
perl_cb:
  id: 1
  title: 'Ruby Tutorial'
  price: 102.00
  description : 'This is a nice Ruby tutorial'
java_cb:
  id: 2
  title: 'Java Programming'
  price: 62.00
  description : 'Java Programming for the beginners'
Add the following test_search_book and test_search_not_found methods totest/functional/book_controller_test.rb to test the functionality of the Book Controller's search action.
require File.dirname(__FILE__) + '/../test_helper'
require 'book_controller'

# Re-raise errors caught by the controller.
class BookController
   def rescue_action(e) 
      raise e 
   end
end

class BookControllerTest < Test::Unit::TestCase
  fixtures :books
  def setup
    @controller = BookController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
  end

  def test_search_book
    get :search, :title => 'Ruby Tutorial'
    assert_not_nil assigns(:book)
    assert_equal books(:perl_cb).title, assigns(:book).title
    assert_valid assigns(:book)
    assert_redirected_to :action => 'show'
  end

 def test_search_not_found
    get :search, :title => 'HTML Tutorial'
    assert_redirected_to :action => 'list'
    assert_equal 'No such book available', flash[:error]
  end
end
Now run your test cases as follows:
testapp > ruby test/functional/book_controller_test.rb 
This gives following output:
Loaded suite test/functional/book_controller_test
Started
..
Finished in 0.422 seconds.

2 tests, 7 assertions, 0 failures, 0 errors
Let's see what has happened here:
  • The setup method is a default method to create controller, request and response objects. They would be used by Rails internally.
  • The first test method test_search_book generates a get request to the search action, passing in a title parameter.
  • The next two assertions verify that a Book object was saved in an instance variable called @book and that the object passes any Active Record validations that might exist.
  • The final assertion inside first method tests that the request was redirected to the controller's show action.
  • The second test method, test_search_not_found, performs another get request but passes in an invalid title.
  • The first assertions test that a redirect to the list action was issued.
  • If the proceeding assertions passed, there should be a message in the flashhash which you can test with assert_equal.

Using Rake for testing:

You can use rake utility to test your applications. Here are few important commands.
  • $rake test - Test all unit tests and functional tests (and integration tests, if they exist).
  • $rake test:functionals - Run all functional tests.
  • $rake test:units - Run all unit tests.
  • $rake test:integration - Run all integration tests.
  • $rake test:plugins - Run all test in ./vendor/plugins/**/test.
  • $rake test:recent - Run tests for models and controllers that have been modified in the last 10 minutes:
  • $rake test:uncommitted - For projects in Subversion, run tests for models and controllers changes since last commit:

Ruby on Rails 2.1 Routes System

Rails parses the URL to determine the controller, action, and parameters for the request. With Rails routing, parts of the URL can specify additional parameters, and the entire routing process is under your control. Routing rules work the same on any web server.
The config/routes.rb file is at the heart of the Rails routing system. This file contains rules that try to match the URL path of a request and determine where to direct that request. The rules are tested in the order that they're defined in the file. The first rule to match a request's URL path determines the fate of that request.
The routing system actually does two things:
  • It maps requests to action methods inside the controllers.
  • It writes URLs for you for use as arguments to methods like link_to, redirect_to, and form_tag.
Thus, the routing system knows how to turn a visitor's request URL into a controller/action sequence. It also knows how to manufacture URL strings based on your specifications.
Consider the following route, installed by Rails when you generate your application:
map.connect ':controller/:action/:id'
This route states that it expects requests to consist of a :controller followed by an :action that in turn is fed some :id.
So if you get an incoming request for "http://localhost:3000/book/edit/2", then it will map as follows:
params = { :controller => 'book',
           :action     => 'edit',
           :id         => '2'
          }
Thus the default routing (if you don't modify the routing rules) is
http://<base-url>/<controller>/<action>/<id>
So a URL like http://www.example.com/book/update/20 calls the update method (the action) in the BooksController class (the controller) with an id parameter set to the value 20.
Following will set up book as the default controller if no other is specified. This means visiting '/' would invoke the book controller.
ActionController::Routing:Routes.draw do |map|
   map.connect ':controller/:action/:id', :controller => 'book'
 end
You can also define a default action if no action is specified in the given URL:
ActionController::Routing:Routes.draw do |map|
   map.connect ':controller/:action/:id', 
                :action => 'edit', :controller => 'book'
 end
Now you can all edit method inside the book controller to edit book with ID as 20 as follows:
http://localhost:3000/2

Route priority:

Routes have priority defined by the order of appearance of the routes in the routes.rb file. The priority goes from top to bottom.
The last route in that file is at the lowest priority and will be applied last. If no route matches, 404 is returned.

Modifying the Default Route:

You can change default route as per your requirement. In the following example we are going to interchange controller and action as follows:
# Install the default route as the lowest priority.
map.connect ':action/:controller/:id'
Now to call action from the given controller you would have to write your URL as follows:
http://localhost:3000/action/controller/id
It's not particularly logical to put action and controller in such sequence. The original default (the default default) route is better and recommended.

The Ante-Default Route:

The 'ante-default' route) looks like this:
map.connect ':controller/:action/:id.:format'
The .:format at the end matches a literal dot and a wildcard "format" value after the id field. That means it will match, for example, a URL like this:
http://localhost:3000/book/show/3.xml
Here, inside the controller action your params[:format] will be set to xml.

The Empty Route:

The empty route is sort of the opposite of the default route. In a newly generated routes.rb file, the empty route is commented out, because there's no universal or reasonable default for it. You need to decide what this nothing URL should do for each application you write.
Here are some examples of fairly common empty route rules:
map.connect '', :controller => "main", :action => "welcome"
map.connect '', :controller => "main"
Here is the explaination of the above rules:
  • The first one will search for welcome action inside main controller even if you type just http://localhost:3000
  • That last one will connect to http://localhost:3000/main/index. Here indexis the default action when there's none specified.
Rails 2.0 introduces a mapper method named root which becomes the proper way to define the empty route for a Rails application, like this:
map.root :controller => "homepage"
Defining the empty route gives people something to look at when they connect to your site with nothing but the domain name.

Named routes:

As you continue developing your application, you will probably have a few links that you use throughout your application. For example, you will probably often be putting a link back to the main listings page. Instead of having to add the following line throughout your application, you can instead create a named route that enables you to link to a shorthand version of that link:
link_to 'Home', :controller => 'classified', :action => 'list'
You can define named routes as follows. Here instead of using connect, you are using a unique name that you can define. In this case, the route is called home. The rest of the route looks similar to the others you have created.
map.home '', :controller => 'classified', :action => 'list'
Now you can use this in the controllers or views as follows:
<%= link_to 'Back', home_url %>
Here, instead of listing the :controller and :action to which you will be linking, you are instead putting the name of the route followed by _url. Your user shouldn't notice any difference. Named routing is merely a convenience for the Rails developer to save some typing. Above case can be written without named route as follows:
<%= link_to 'Back', {:action => 'list'} %>

Pretty URLs:

Routes can generate pretty URLs. For example:
map.connect 'articles/:year/:month/:day',
             :controller => 'articles',
             :action     => 'find_by_date',
             :year       => /\d{4}/,
             :month      => /\d{1,2}/,
             :day        => /\d{1,2}/

 # Using the route above, the url below maps to:
 # params = {:year => '2005', :month => '11', :day => '06'}
 # http://localhost:3000/articles/2005/11/06

Ruby on Rails 2.1 - Exception Handling

The execution and the exception always go together. If you are opening a file which does not exist then if you did not handle this situation properly then your program is considered to be of bad quality.
The program stops if an exception occurs. So exceptions are used to handle various type of errors which may occur during a program execution and take appropriate action instead of halting program completely.
Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/endblock and use rescue clauses to tell Ruby the types of exceptions we want to handle.

Syntax :

begin  
# -  
rescue OneTypeOfException  
# -  
rescue AnotherTypeOfException  
# -  
else  
# Other exceptions
ensure
# Always will be executed
end
Everything from begin to rescue is protected. If an exception occurs during the execution of this block of code, control is passed to the block between rescue andend.
For each rescue clause in the begin block, Ruby compares the raised Exception against each of the parameters in turn. The match will succeed if the exception named in the rescue clause is the same as the type of the currently thrown exception, or is a superclass of that exception.

Where to log errors ?

There are three option you have when an exception is thrown:
  • log to an internal log file (logger.error).
  • Display an appropriate message to the user.
  • redisplay the original page to continue.
The error reporting to the application is done to a structure called a flash. Theflash is a hash bucket to contain your message until the next request before being deleted automatically. You can access it with the @flash variable. Following is the simplest form of using logger module to log error messages in an internal file.
begin
.........
rescue Exception => exc
   logger.error("Message for the log file #{exc.message}")
   flash[:notice] = "Store error message"
   redirect_to(:action => 'index')
end
You can display all the messages from @flash in your view or layout (.html.erb), you can add the following:
<% @flash[:notice] -%>
<div id="notice"><%= @flash[:notice] %></div>
<% end -%>

Rails 2.1 - HTTP Basic Authentication

Rails provide various ways of implementing authentication and authorization. But the simplest one is a new module which has been added in Rails 2.0. This module turned out to be a great way to do API authentication over SSL.
To use this authentication you will need to use SSL for traffic transportation. In out tutorial we are going to test it without a SSL.
Let us start with our library example we have discussed throughout of the tutorial. We do not have much to do to implement authentication. I'm going to add few lines in blue in our ~library/app/controllers/book_controller.rb:
Finally your book_controller.rb file will look like as follows:
class BookController < ApplicationController
   
   USER_ID, PASSWORD = "zara", "pass123"
 
   # Require authentication only for edit and delete operation
   before_filter :authenticate, :only => [ :edit, :delete ]
   
   def list
      @books = Book.find(:all)
   end
   def show
      @book = Book.find(params[:id])
   end
   def new
      @book = Book.new
      @subjects = Subject.find(:all)
   end
   def create
      @book = Book.new(params[:book])
      if @book.save
            redirect_to :action => 'list'
      else
            @subjects = Subject.find(:all)
            render :action => 'new'
      end
   end
   def edit
      @book = Book.find(params[:id])
      @subjects = Subject.find(:all)
   end
   def update
      @book = Book.find(params[:id])
      if @book.update_attributes(params[:book])
         redirect_to :action => 'show', :id => @book
      else
         @subjects = Subject.find(:all)
         render :action => 'edit'
      end
   end
   def delete
      Book.find(params[:id]).destroy
      redirect_to :action => 'list'
   end
   def show_subjects
      @subject = Subject.find(params[:id])
   end
   
private
   def authenticate
      authenticate_or_request_with_http_basic do |id, password| 
          id == USER_ID && password == PASSWORD
      end
   end
   
end
Let me explain these new lines:
  • First line is just to define user ID and password to access various pages.
  • Second line, I have put before_filter which is used to run the configured method authenticate before any action in the controller. A filter may be limited to specific actions by declaring the actions to include or exclude. Both options accept single actions (:only => :index) or arrays of actions (:except => [:foo, :bar]). So here we have put authentication for edit and delete operations only.
  • Because of second line, whenever you would try to edit or delete a book record, it will execute private authenticate method.
  • A private authenticate method is callingauthenticate_or_request_with_http_basic method which comprises of a block and displays a dialogue box to ask for User ID and Password to proceed. If you enter a correct user ID and password then it will proceed otherwise it would display access denied.
Now try to edit or delete any available record, to do so you would have to go through authentication process using following dialogue box.
Http Basic Authentication

Ruby on Rails 2.1 - RMagick

Rails provide a bindings to ImageMagick and GraphicsMagick which are popular and stable C libraries. The RMagick library provides the same interface against ImageMagick and GraphicsMagick, so it does not matter which one you use.
You can get RMagick by installing the rmagick gen on Unix or rmagick-win32 gem on Windows. Let's install it on a Unix machine as follows:
$ gem install rmagick
The RMagick module comes along with class Magick::Image which lets you resize images four different methods:
  • resize(width, height)
  • scale(width, height)
  • sample(width, height)
  • thumbnail(width, height)
All these methods accept a pair integer values, corresponding to the width and height in pixels of the thumbnail you want.

Example

Here's an example that uses resize() method to resize the image. It takes the filetmp.jpg and makes a thumbnail of it 100 pixels wide by 100 pixels tall:
require 'rubygems'
require 'RMagick'

class ImageController < ApplicationController

   def createThubnail
     width, height = 100, 100

     img =  Magick::Image.read('tmp.jpg').first
     thumb = img.resize(width, height)
    
     # If you want to save this image use following
     # thumb.write("mythumbnail.jpg")

     # otherwise send it to the browser as follows
     send_data(thumb.to_blob, :disposition => 'inline', 
                           :type => 'image/jpg')
   end
end
Here are the steps to create a thumbnail:
  • Here the class method Image.read receives an image filename as an argument and returns an array of Image objects. You obtain the first element of that array which is obviously our tmp.jpg image.
  • Next we are calling method resize with the desired arguments which is creating a thumbnail.
  • Finally we are directing this image to browser. You can also use methodthumb.write("mythumbnail.jpg") to store this image locally are your machine.

Converting Image Formats:

This is very easy to convert an image file from one format to another format. The RMagick handles is very smartly. You can just read in the file and write it out with a different extension.

Example:

Following example converts a JPEG file into a GIF file:
require 'rubygems'
require 'RMagick'

class ImageController < ApplicationController

   def changeFormat

     img =  Magick::Image.read('tmp.jpg').first
    
     # If you want to save this image use following
     # img.write("mythumbnail.gif")

     # otherwise send it to the browser as follows
     send_data(img.to_blob, :disposition => 'inline', 
                           :type => 'image/gif')
   end
end
Similar way you can change format based on your requirement as follows:
img = Magick::Image.read("tmp.png").first
img.write("tmp.jpg")                 # Converts into JPEG
img.write("tmp.gif")                 # Converts into GIF
img.write("JPG:tmp")                 # Converts into JPEG
img.write("GIF:tmp")                 # Converts into GIF

Send Email using Rails 2.1

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 an emails project using following command.
C:\ruby> rails -d mysql emails
Here we are using -d mysql option to specify our interest to use MySQL database. We can specify any other database name like oracle or postgressusing -d option. By default Rails uses SQLite database.

Setting up the Database:

Even though we are not using a database in our application but Rails needs it to proceed. So let's perform these additional steps.
Here is the way to create database:
mysql> create database emails;
Query OK, 1 row affected (0.01 sec)

mysql> grant all privileges on emails.*
 to 'root'@'localhost' identified by 'password';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
To tell Rails how to find the database, edit the configuration file ~\upload\config\database.yml and change the database name to cookbook. When you finish, it should look something like:
development:
  adapter: mysql
  encoding: utf8
  database: emails
  username: root
  password: password
  host: localhost
test:
  adapter: mysql
  encoding: utf8
  database: emails
  username: root
  password: password
  host: localhost
production:
  adapter: mysql
  encoding: utf8
  database: emails
  username: root
  password: password
  host: localhost

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.smtp_settings = {
   :address => "smtp.tutorialspoint.com",
   :port => 25,
   :domain => "tutorialspoint.com",
   :authentication => :login,
   :user_name => "username",
   :password => "password",
}
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
end
Now let's create one method inside ActionMailer::Base class as follows.
class Emailer < ActionMailer::Base
   def contact(recipient, subject, message, sent_at = Time.now)
      @subject = subject
      @recipients = recipient
      @from = 'no-reply@yourdomain.com'
      @sent_on = sent_at
   @body["title"] = 'This is title'
     @body["email"] = 'sender@yourdomain.com'
      @body["message"] = message
      @headers = {}
   end
end
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.

Creating Controller:

Now we will create a controller for this application as follows:
C:\ruby\emails> ruby script/generate controller Emailer
Now lets define a controller method sendmail in app/controllers/emailer_controller.rb which will call Model method to send actual email as follows:
class EmailerController < ApplicationController
   def sendmail
      recipient = params[:email]
      subject = params[:subject]
      message = params[:message]
      Emailer.deliver_contact(recipient, subject, message)
      return if request.xhr?
      render :text => 'Message sent successfully'
   end
end
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 let's define one screen method index in controller and then in next section we will define all the required views:
Add following code in emailer_controller.rb file
def index
      render :file => 'app\views\emailer\index.htm.erb'
   end

Defining Views:

Define a view in app\views\emails\index.html.erb. This will be called as the default page for the application and will allow user to enter message and send required email:
<h1>Send Email</h1>
<% form_tag :action => 'sendmail' do %>
<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 %>
Apart from the above view, we need one more template which will be used by the Emailer's contact method while sending message. This is just text with standard Rails <%= %> placeholders scattered throughout.
So just put the following code in app/views/contact.html.erb file
Hi!

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

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

Thanks

Rest for Testing:

Before starting your testing make sure your machine is connected to internet and your Email Server is up and running, Also your Webserver should be up and running well.
Now test your application by using http://127.0.0.1:3000/Emailer/index. This displays following screen and by using this screen now you will be able to send your message to anybody.
Send Email
This will send your message and will display text message that "Message sent successfully"

Sending HTML Emails using Rails:

To send mail as HTML, make sure your view (the .erb file) generates HTML and set the content type to html in your emails/app/models/emailer.rb file as follows:
class Emailer < ActionMailer::Base
   def contact(recipient, subject, message, sent_at = Time.now)
      @subject = subject
      @recipients = recipient
      @from = 'no-reply@yourdomain.com'
      @sent_on = sent_at
   @body["title"] = 'This is title'
     @body["email"] = 'sender@yourdomain.com'
      @body["message"] = message
      @headers = {content_type => 'text/html'}
   end
end

Site Search