Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Page 4 - Web Forms and Ruby on Rails
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
RUBY-ON-RAILS

Web Forms and Ruby on Rails
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 8
    2007-04-19

    Table of Contents:
  • Web Forms and Ruby on Rails
  • 15.17 Creating an Ajax Form
  • 15.18 Exposing Web Services on Your Web Site
  • 15.19 Sending Mail with Rails

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

       · This article is an excerpt from the "Ruby Cookbook," published by O'Reilly. We hope...
     

    Buy this book now. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Check it out today at your favorite bookstore. Buy this book now.

    RUBY-ON-RAILS ARTICLES

    - Iterating and Incrementing Strings in Ruby
    - Comparing and Manipulating Strings in Ruby
    - Strings in Ruby
    - Ruby On Rails: Making Your First Dynamic Site
    - Ruby on Rails: Beginning Rails
    - Ruby: Modules, Mixins, Fixins, and Rails
    - Controlling Information Access with the Rail...
    - URLs, Filters and the Rails Action Controller
    - Flash and the Rails Action Controller
    - Rails Action Controller
    - Dropping and Sorting with AJAX and script.ac...
    - Drag and Drop with script.aculo.us and Rails
    - Introducing script.aculo.us
    - Ruby Classes and Objects
    - Ruby Loops







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek