Home arrow Ruby-on-Rails arrow Page 4 - Web Forms and Ruby on Rails
RUBY-ON-RAILS

Web Forms and Ruby on Rails


In this fifth article of a six-part series covering web development and Ruby on Rails, you'll learn how to create an AJAX form and more. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Copyright 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 4 stars4 stars4 stars4 stars4 stars / 33
April 19, 2007
TABLE OF CONTENTS:
  1. · Web Forms and Ruby on Rails
  2. · 15.17 Creating an Ajax Form
  3. · 15.18 Exposing Web Services on Your Web Site
  4. · 15.19 Sending Mail with Rails

print this article
SEARCH DEVARTICLES

Web Forms and Ruby on Rails - 15.19 Sending Mail with Rails
(Page 4 of 4 )

Problem

You want to send an email from within your Rails application: perhaps a confirmation of an order, or notification that some action has been taken on a user's behalf.

Solution

The first is to generate some mailer infrastructure. Go to the application's base directory and type this command: 

  ./script/generate mailer Notification welcome
        exists  app/models/
        create  app/views/notification 
        exists  test/unit/
        create  test/fixtures/notification
        create  app/models/notification.rb
        create  test/unit/ notification_test.rb
        create  app/views/notification/ welcome.rhtml
        create  test/fixtures/notification/ welcome

We're giving the name "Notification" to the mailing center of the application; it's some-what analogous to a controller in the web interface. The mailer is set up to generate a single email, called "welcome": this is analagous to an action with a view template.

Now open app/models/notification.rb and edit it to look like this:

  class Notification < ActionMailer::Base
   
def welcome(user, sent_at=Time.now)
      @subject = 'A Friendly Welcome'
      @recipients = user.email
      @from = 'admin@mysite.com'
      @sent_on = sent_at
      @body = {
       
:user => user,
        :sent_on => sent_at
      } 
      
attachment 'text/plain' do |a|  
        a.body = File.read('rules.txt') 
      end
    end
  end

The subject of the email is "A Friendly Welcome", and it's sent to the user's email address from the address "admin@mysite.com". It's got an attachment taken from the disk file rules.txt (relative to the root directory of your Rails application).

Although the file notification.rb is within the models/ directory, it acts like a controller in that each of its email messages has an associated view template. The view for the welcome email is in app/views/notification/welcome.rhtml, and it acts almost the same as the view of a normal controller.

The most important difference is that mailer views do not have access to the instance variables of the mailer. To set instance variables for mailers, you pass a hash of those variables to the body method. The keys become instance variable names and the values become their values. In notification.rb , we make two instance variables available to the welcome view, @user and @sent_on. Here's the view itself:

  <!-- app/views/notification/welcome.rhtml -->

  Hello, <%= @user.name %>, and thanks for signing up at <%= @sent_on
  %>. Please print out the attached set of rules and keep them in a
  prominent place; they help keep our community running smoothly. Be
  sure to pay special attention to sections II.4 ("Assignment of
  Intellectual Property Rights") and XIV.21.a ("Dispute Resolution
  Through Ritual Combat").

To send the welcome email from your Rails application, add the following code to either a controller, a model, or an observer:

  Notification.deliver_welcome(user)

Here, the user variable can be any object that implements #name and #email, the two methods called in the welcome method and in the template.

Discussion

You never call the Notification#welcome method directly. In fact, Notification#welcome is not even available, since it's an instance method, and you never instantiate a Notification object directly. The ActionMailer::Base class defines a method_missing implementation that looks at all calls to undefined class methods. This is why you call deliver_welcome even though you never defined it.

The welcome.rhtml template given above generates plaintext email. To send HTML emails, simply add the following code to Notification#welcome:

  content_type 'text/html'

Now your templates can generate HTML; email clients will recognize the format of the email and render it appropriately.

Sometimes you'll want more control over the delivery process--for example, when you're unit-testing your ActionMailer classes. Instead of calling deliver_welcome to send out an email, you can call create_welcome to get the email as a Ruby object. These "create" methods return TMail objects, which you can examine or manipulate as necessary.

If your local web server is incapable of sending email, you can modify environment.rb to contact a remote SMTP server:

  Rails::Initializer.run do |config|
   
config.action_mailer.server_settings = {
     
:address => 'someserver.com',
     
:user_name => 'uname',
     
:password => 'passwd',
     
:authentication => 'cram_md5'
   
}
  end

See Also

  1. Recipe 10.8, "Responding to Calls to Undefined Methods"
  2. Recipe 14.5, "Sending Mail," has more on ActionMailer and SMTP settings

Please check back next week for the conclusion to this article.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials