Merge branch 'master' of git://github.com/rails/rails

Conflicts:
	activemodel/README
	activemodel/lib/active_model/errors.rb
	activemodel/lib/active_model/serialization.rb
	railties/guides/source/3_0_release_notes.textile
This commit is contained in:
Mikel Lindsaar 2010-02-02 14:04:23 +11:00
commit 12681c2a71
29 changed files with 285 additions and 344 deletions

@ -11,7 +11,6 @@ if RUBY_VERSION < '1.9'
end
# AR
gem "arel", ">= 0.2.0"
gem "sqlite3-ruby", ">= 1.2.5"
group :test do

@ -1,4 +1,4 @@
Copyright (c) 2004-2009 David Heinemeier Hansson
Copyright (c) 2004-2010 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

@ -1,5 +1,5 @@
#--
# Copyright (c) 2004-2009 David Heinemeier Hansson
# Copyright (c) 2004-2010 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the

@ -1,4 +1,4 @@
Copyright (c) 2004-2009 David Heinemeier Hansson
Copyright (c) 2004-2010 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

@ -1,5 +1,5 @@
#--
# Copyright (c) 2004-2009 David Heinemeier Hansson
# Copyright (c) 2004-2010 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the

@ -9,17 +9,18 @@ module ActionDispatch
# mod_rewrite rules. Best of all, Rails' Routing works with any web server.
# Routes are defined in <tt>config/routes.rb</tt>.
#
# Consider the following route, installed by Rails when you generate your
# application:
# Consider the following route, which you will find commented out at the
# bottom of your generated <tt>config/routes.rb</tt>:
#
# map.connect ':controller/:action/:id'
# match ':controller(/:action(/:id(.:format)))'
#
# This route states that it expects requests to consist of a
# <tt>:controller</tt> followed by an <tt>:action</tt> that in turn is fed
# some <tt>:id</tt>.
# <tt>:controller</tt> followed optionally by an <tt>:action</tt> that in
# turn is followed optionally by an <tt>:id</tt>, which in turn is followed
# optionally by a <tt>:format</tt>
#
# Suppose you get an incoming request for <tt>/blog/edit/22</tt>, you'll end up
# with:
# Suppose you get an incoming request for <tt>/blog/edit/22</tt>, you'll end
# up with:
#
# params = { :controller => 'blog',
# :action => 'edit',
@ -29,7 +30,7 @@ module ActionDispatch
# Think of creating routes as drawing a map for your requests. The map tells
# them where to go based on some predefined pattern:
#
# ActionController::Routing::Routes.draw do |map|
# AppName::Applications.routes.draw do |map|
# Pattern 1 tells some request to go to one place
# Pattern 2 tell them to go to another
# ...
@ -42,60 +43,16 @@ module ActionDispatch
#
# Other names simply map to a parameter as in the case of <tt>:id</tt>.
#
# == Route priority
#
# Not all routes are created equally. Routes have priority defined by the
# order of appearance of the routes in the <tt>config/routes.rb</tt> 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.
#
# Within blocks, the empty pattern is at the highest priority.
# In practice this works out nicely:
#
# ActionController::Routing::Routes.draw do |map|
# map.with_options :controller => 'blog' do |blog|
# blog.show '', :action => 'list'
# end
# map.connect ':controller/:action/:view'
# end
#
# In this case, invoking blog controller (with an URL like '/blog/')
# without parameters will activate the 'list' action by default.
#
# == Defaults routes and default parameters
#
# Setting a default route is straightforward in Rails - you simply append a
# Hash at the end of your mapping to set any default parameters.
#
# Example:
#
# ActionController::Routing:Routes.draw do |map|
# map.connect ':controller/:action/:id', :controller => 'blog'
# end
#
# This sets up +blog+ as the default controller if no other is specified.
# This means visiting '/' would invoke the blog controller.
#
# More formally, you can include arbitrary parameters in the route, thus:
#
# map.connect ':controller/:action/:id', :action => 'show', :page => 'Dashboard'
#
# This will pass the :page parameter to all incoming requests that match this route.
#
# Note: The default routes, as provided by the Rails generator, make all actions in every
# controller accessible via GET requests. You should consider removing them or commenting
# them out if you're using named routes and resources.
#
# == Named routes
#
# Routes can be named with the syntax <tt>map.name_of_route options</tt>,
# Routes can be named by passing an <tt>:as</tt> option,
# allowing for easy reference within your source as +name_of_route_url+
# for the full URL and +name_of_route_path+ for the URI path.
#
# Example:
#
# # In routes.rb
# map.login 'login', :controller => 'accounts', :action => 'login'
# match '/login' => 'accounts#login', :as => 'login'
#
# # With render, redirect_to, tests, etc.
# redirect_to login_url
@ -104,10 +61,10 @@ module ActionDispatch
#
# redirect_to show_item_path(:id => 25)
#
# Use <tt>map.root</tt> as a shorthand to name a route for the root path "".
# Use <tt>root</tt> as a shorthand to name a route for the root path "".
#
# # In routes.rb
# map.root :controller => 'blogs'
# root :to => 'blogs#index'
#
# # would recognize http://www.example.com/ as
# params = { :controller => 'blogs', :action => 'index' }
@ -116,20 +73,14 @@ module ActionDispatch
# root_url # => 'http://www.example.com/'
# root_path # => ''
#
# You can also specify an already-defined named route in your <tt>map.root</tt> call:
#
# # In routes.rb
# map.new_session :controller => 'sessions', :action => 'new'
# map.root :new_session
#
# Note: when using +with_options+, the route is simply named after the
# Note: when using +controller+, the route is simply named after the
# method you call on the block parameter rather than map.
#
# # In routes.rb
# map.with_options :controller => 'blog' do |blog|
# blog.show '', :action => 'list'
# blog.delete 'delete/:id', :action => 'delete'
# blog.edit 'edit/:id', :action => 'edit'
# controller :blog do
# match 'blog/show' => :list
# match 'blog/delete' => :delete
# match 'blog/edit/:id' => :edit
# end
#
# # provides named routes for show, delete, and edit
@ -139,12 +90,13 @@ module ActionDispatch
#
# 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}/
# match '/articles/:year/:month/:day', :constraints => {
# :controller => 'articles',
# :action => 'find_by_date',
# :year => /\d{4}/,
# :month => /\d{1,2}/,
# :day => /\d{1,2}/
# }
#
# Using the route above, the URL "http://localhost:3000/articles/2005/11/06"
# maps to
@ -154,42 +106,34 @@ module ActionDispatch
# == Regular Expressions and parameters
# You can specify a regular expression to define a format for a parameter.
#
# map.geocode 'geocode/:postalcode', :controller => 'geocode',
# :action => 'show', :postalcode => /\d{5}(-\d{4})?/
# controller 'geocode' do
# match 'geocode/:postalcode' => :show', :constraints => {
# :postalcode => /\d{5}(-\d{4})?/
# }
#
# or, more formally:
#
# map.geocode 'geocode/:postalcode', :controller => 'geocode',
# :action => 'show', :requirements => { :postalcode => /\d{5}(-\d{4})?/ }
#
# Formats can include the 'ignorecase' and 'extended syntax' regular
# Constraints can include the 'ignorecase' and 'extended syntax' regular
# expression modifiers:
#
# map.geocode 'geocode/:postalcode', :controller => 'geocode',
# :action => 'show', :postalcode => /hx\d\d\s\d[a-z]{2}/i
# controller 'geocode' do
# match 'geocode/:postalcode' => :show', :constraints => {
# :postalcode => /hx\d\d\s\d[a-z]{2}/i
# }
# end
#
# map.geocode 'geocode/:postalcode', :controller => 'geocode',
# :action => 'show',:requirements => {
# :postalcode => /# Postcode format
# \d{5} #Prefix
# (-\d{4})? #Suffix
# /x
# }
# controller 'geocode' do
# match 'geocode/:postalcode' => :show', :constraints => {
# :postalcode => /# Postcode format
# \d{5} #Prefix
# (-\d{4})? #Suffix
# /x
# }
# end
#
# Using the multiline match modifier will raise an ArgumentError.
# Encoding regular expression modifiers are silently ignored. The
# match will always use the default encoding or ASCII.
#
# == Route globbing
#
# Specifying <tt>*[string]</tt> as part of a rule like:
#
# map.connect '*path' , :controller => 'blog' , :action => 'unrecognized?'
#
# will glob all remaining parts of the route that were not recognized earlier.
# The globbed values are in <tt>params[:path]</tt> as an array of path segments.
#
# == Route conditions
# == HTTP Methods
#
# With conditions you can define restrictions on routes. Currently the only valid condition is <tt>:method</tt>.
#
@ -200,10 +144,8 @@ module ActionDispatch
#
# Example:
#
# map.connect 'post/:id', :controller => 'posts', :action => 'show',
# :conditions => { :method => :get }
# map.connect 'post/:id', :controller => 'posts', :action => 'create_comment',
# :conditions => { :method => :post }
# get 'post/:id' => 'posts#show'
# post 'post/:id' => "posts#create_comment'
#
# Now, if you POST to <tt>/posts/:id</tt>, it will route to the <tt>create_comment</tt> action. A GET on the same
# URL will route to the <tt>show</tt> action.
@ -212,7 +154,7 @@ module ActionDispatch
#
# You can reload routes if you feel you must:
#
# ActionController::Routing::Routes.reload
# Rails::Application.reload_routes!
#
# This will clear all named routes and reload routes.rb if the file has been modified from
# last load. To absolutely force reloading, use <tt>reload!</tt>.

@ -1,5 +1,5 @@
#--
# Copyright (c) 2004-2009 David Heinemeier Hansson
# Copyright (c) 2004-2010 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the

@ -1,5 +1,5 @@
#--
# Copyright (c) 2004-2009 David Heinemeier Hansson
# Copyright (c) 2004-2010 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the

@ -104,7 +104,7 @@ def build_path(name, details, prefix, partial)
end
def query(path, exts)
query = "#{@path}/#{path}"
query = File.join(@path, path)
exts.each do |ext|
query << '{' << ext.map {|e| e && ".#{e}" }.join(',') << '}'
end

@ -1,4 +1,4 @@
Copyright (c) 2004-2009 David Heinemeier Hansson
Copyright (c) 2004-2010 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

@ -1,13 +1,13 @@
= Active Model - defined interfaces for Rails
Prior to Rails 3.0, if a plugin or gem developer wanted to be able to have
an object interact with Action Pack helpers, it was required to either
copy chunks of code from Rails, or monkey patch entire helpers to make them
handle objects that did not look like Active Record. This generated code
duplication and fragile applications that broke on upgrades.
Active Model is a solution for this problem.
Active Model provides a known set of interfaces that your objects can implement
to then present a common interface to the Action Pack helpers. You can include
functionality from the following modules:
@ -75,7 +75,7 @@ functionality from the following modules:
person.name = 'robert'
person.save
person.previous_changes # => {'name' => ['bob, 'robert']}
{Learn more}[link:classes/ActiveModel/Dirty.html]
* Adding +errors+ support to your object
@ -84,22 +84,22 @@ functionality from the following modules:
helpers seamlessly...
class Person
def initialize
@errors = ActiveModel::Errors.new(self)
end
attr_accessor :name
attr_reader :errors
def validate!
errors.add(:name, "can not be nil") if name == nil
end
def ErrorsPerson.human_attribute_name(attr, options = {})
"Name"
end
end
... gives you...
@ -153,19 +153,6 @@ functionality from the following modules:
s.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
{Learn more}[link:classes/ActiveModel/Serialization.html]
* Turning your object into a finite State Machine
ActiveModel::StateMachine provides a clean way to include all the methods
you need to transform your object into a finite State Machine...
light = TrafficLight.new
light.current_state #=> :red
light.change_color! #=> true
light.current_state #=> :green
{Learn more}[link:classes/ActiveModel/StateMachine.html]
* Integrating with Rail's internationalization (i18n) handling through
ActiveModel::Translations...
@ -183,11 +170,13 @@ functionality from the following modules:
attr_accessor :first_name, :last_name
validates_each :first_name, :last_name do |record, attr, value|
record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
end
end
person = Person.new(:first_name => 'zoolander')
person.valid? #=> false
@ -214,5 +203,3 @@ functionality from the following modules:
p.valid? #=> true
{Learn more}[link:classes/ActiveModel/Validator.html]

@ -1,5 +1,5 @@
#--
# Copyright (c) 2004-2009 David Heinemeier Hansson
# Copyright (c) 2004-2010 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the

@ -273,6 +273,7 @@ def undefine_attribute_methods
@attribute_methods_generated = nil
end
# Returns true if the attribute methods defined have been generated.
def generated_attribute_methods #:nodoc:
@generated_attribute_methods ||= begin
mod = Module.new

@ -62,8 +62,6 @@ class Errors < ActiveSupport::OrderedHash
# @errors = ActiveModel::Errors.new(self)
# end
# end
#
#
def initialize(base)
@base = base
super()

@ -58,7 +58,7 @@ def test_model_naming
#
# Returns an object that has :[] and :full_messages defined on it. See below
# for more details.
#
# Returns an Array of Strings that are the errors for the attribute in
# question. If localization is used, the Strings should be localized
# for the current locale. If no error is present, this method should

@ -2,7 +2,6 @@
require 'active_support/core_ext/hash/slice'
module ActiveModel
# Provides a basic serialization to a serializable_hash for your object.
#
# A minimal implementation could be:

@ -1,4 +1,4 @@
Copyright (c) 2004-2009 David Heinemeier Hansson
Copyright (c) 2004-2010 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

@ -1,5 +1,5 @@
#--
# Copyright (c) 2004-2009 David Heinemeier Hansson
# Copyright (c) 2004-2010 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the

@ -1,4 +1,4 @@
Copyright (c) 2006-2009 David Heinemeier Hansson
Copyright (c) 2006-2010 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

@ -1,4 +1,4 @@
Copyright (c) 2005-2009 David Heinemeier Hansson
Copyright (c) 2005-2010 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

@ -1,7 +1,7 @@
=begin
heavily based on Masao Mutoh's gettext String interpolation extension
http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb
Copyright (C) 2005-2009 Masao Mutoh
Copyright (C) 2005-2010 Masao Mutoh
You may redistribute it and/or modify it under the same license terms as Ruby.
=end

@ -106,7 +106,7 @@ def rake(*tasks)
puts "[CruiseControl] SQLite3: #{`sqlite3 -version`}"
`gem env`.each_line {|line| print "[CruiseControl] #{line}"}
puts "[CruiseControl] Bundled gems:"
`gem bundle --list`.each_line {|line| print "[CruiseControl] #{line}"}
# `gem bundle --list`.each_line {|line| print "[CruiseControl] #{line}"}
puts "[CruiseControl] Local gems:"
`gem list`.each_line {|line| print "[CruiseControl] #{line}"}

@ -1,4 +1,4 @@
Copyright (c) 2004-2009 David Heinemeier Hansson
Copyright (c) 2004-2010 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

@ -377,6 +377,8 @@ More Information:
h3. Active Record
Active Record received a lot of attention in Rails 3.0, including abstraction into Active Model, a full update to the Query interface using Arel, validation updates and many enhancements and fixes. All of the Rails 2.x API will be usable through a compatibility layer that will be supported until version 3.1.
h4. Query Interface

@ -1,12 +1,14 @@
h2. Action Mailer Basics
This guide should provide you with all you need to get started in sending and receiving emails from/to your application, and many internals of Action Mailer. It also covers how to test your mailers.
This guide should provide you with all you need to get started in sending and receiving emails from and to your application, and many internals of Action Mailer. It also covers how to test your mailers.
endprologue.
WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in other versions of Rails.
h3. Introduction
Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating models that inherit from +ActionMailer::Base+ that live alongside other models in +app/models+. Those models have associated views that appear alongside controller views in +app/views+.
Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from +ActionMailer::Base+ and live in +app/mailers+. Those mailers have associated views that appear alongside controller views in +app/views+.
h3. Sending Emails
@ -18,22 +20,22 @@ h5. Create the Mailer
<shell>
./script/generate mailer UserMailer
exists app/models/
create app/views/user_mailer
exists test/unit/
create test/fixtures/user_mailer
create app/models/user_mailer.rb
create test/unit/user_mailer_test.rb
create app/mailers/user_mailer.rb
invoke erb
create app/views/user_mailer
invoke test_unit
create test/functional/user_mailer_test.rb
</shell>
So we got the model, the fixtures, and the tests.
So we got the mailer, the fixtures, and the tests.
h5. Edit the Model
h5. Edit the Mailer
+app/models/user_mailer.rb+ contains an empty mailer:
+app/mailers/user_mailer.rb+ contains an empty mailer:
<ruby>
class UserMailer < ActionMailer::Base
default :from => "from@example.com"
end
</ruby>
@ -41,206 +43,272 @@ Let's add a method called +welcome_email+, that will send an email to the user's
<ruby>
class UserMailer < ActionMailer::Base
default :from => "notifications@example.com"
def welcome_email(user)
recipients user.email
from "My Awesome Site Notifications <notifications@example.com>"
subject "Welcome to My Awesome Site"
sent_on Time.now
body( {:user => user, :url => "http://example.com/login"})
@user = user
@url = "http://example.com/login"
mail(:to => user.email,
:subject => "Welcome to My Awesome Site")
end
end
</ruby>
Here is a quick explanation of the options presented in the preceding method. For a full list of all available options, please have a look further down at the Complete List of ActionMailer user-settable attributes section.
Here is a quick explanation of the items presented in the preceding method. For a full list of all available options, please have a look further down at the Complete List of ActionMailer user-settable attributes section.
|recipients| The recipients of the email. It can be a string or, if there are multiple recipients, an array of strings|
|from| The from address of the email|
|subject| The subject of the email|
|sent_on| The timestamp for the email|
* <tt>default Hash</tt> - This is a hash of default values for any email you send, in this case we are setting the <tt>:from</tt> header to a value for all messages in this class, this can be overridden on a per email basis
* +mail+ - The actual email message, we are passing the <tt>:to</tt> and <tt>:subject</tt> headers in|
The keys of the hash passed to +body+ become instance variables in the view. Thus, in our example the mailer view will have a +@user+ and a +@url+ instance variables available.
And instance variables we define in the method become available for use in the view.
h5. Create a Mailer View
Create a file called +welcome_email.text.html.erb+ in +app/views/user_mailer/+. This will be the template used for the email, formatted in HTML:
Create a file called +welcome_email.html.erb+ in +app/views/user_mailer/+. This will be the template used for the email, formatted in HTML:
<erb>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
</head>
<body>
<h1>Welcome to example.com, <%=h @user.first_name %></h1>
<h1>Welcome to example.com, <%= @user.name %></h1>
<p>
You have successfully signed up to example.com, and your username is: <%= @user.login %>.<br/>
To login to the site, just follow this link: <%=h @url %>.
You have successfully signed up to example.com,
your username is: <%= @user.login %>.<br/>
</p>
<p>
To login to the site, just follow this link: <%= @url %>.
</p>
<p>Thanks for joining and have a great day!</p>
</body>
</html>
</erb>
Had we wanted to send text-only emails, the file would have been called +welcome_email.text.plain.erb+. Rails sets the content type of the email to be the one in the filename.
It is also a good idea to make a text part for this email, to do this, create a file called +welcome_email.text.erb+ in +app/views/user_mailer/+:
<erb>
Welcome to example.com, <%= @user.name %>
===============================================
You have successfully signed up to example.com,
your username is: <%= @user.login %>.
To login to the site, just follow this link: <%= @url %>.
Thanks for joining and have a great day!
</erb>
When you call the +mail+ method now, Action Mailer will detect the two templates (text and HTML) and automatically generate a <tt>multipart/alternative</tt> email.
h5. Wire It Up So That the System Sends the Email When a User Signs Up
There are three ways to achieve this. One is to send the email from the controller that sends the email, another is to put it in a +before_create+ callback in the user model, and the last one is to use an observer on the user model. Whether you use the second or third methods is up to you, but staying away from the first is recommended. Not because it's wrong, but because it keeps your controller clean, and keeps all logic related to the user model within the user model. This way, whichever way a user is created (from a web form, or from an API call, for example), we are guaranteed that the email will be sent.
Let's see how we would go about wiring it up using an observer:
Let's see how we would go about wiring it up using an observer.
In +config/environment.rb+:
First off, we need to create a simple +User+ scaffold:
<shell>
$ script/generate scaffold user name:string email:string login:string
$ rake db:migrate
</shell>
Now that we have a user model to play with, edit +config/application.rb+ and register the observer:
<ruby>
Rails::Initializer.run do |config|
# ...
config.active_record.observers = :user_observer
module MailerGuideCode
class Application < Rails::Application
# ...
config.active_record.observers = :user_observer
end
end
</ruby>
You can place the observer in +app/models+ where it will be loaded automatically by Rails.
You can make a +app/observers+ directory and Rails will automatically load it for you (Rails will automatically load anything in the +app+ directory as of version 3.0)
Now create a file called +user_observer.rb+ in +app/models+ depending on where you stored it, and make it look like:
Now create a file called +user_observer.rb+ in +app/observers+ and make it look like:
<ruby>
class UserObserver < ActiveRecord::Observer
def after_create(user)
UserMailer.deliver_welcome_email(user)
UserMailer.welcome_email(user).deliver
end
end
</ruby>
Notice how we call +deliver_welcome_email+? In Action Mailer we send emails by calling +deliver_&lt;method_name&gt;+. In UserMailer, we defined a method called +welcome_email+, and so we deliver the email by calling +deliver_welcome_email+. The next section will go through how Action Mailer achieves this.
Notice how we call <tt>UserMailer.welcome_email(user)</tt>? Even though in the <tt>user_mailer.rb</tt> file we defined an instance method, we are calling the method_name +welcome_email(user)+ on the class. This is a peculiarity of Action Mailer.
h4. Action Mailer and Dynamic +deliver_&lt;method_name&gt;+ methods
NOTE: In previous versions of Rails, you would call +deliver_welcome_email+ or +create_welcome_email+ however in Rails 3.0 this has been deprecated in favour of just calling the method name itself.
So how does Action Mailer understand this +deliver_welcome_email+ call? If you read the documentation (http://api.rubyonrails.org/files/vendor/rails/actionmailer/README.html), you will find this in the "Sending Emails" section:
The method +welcome_email+ returns a Mail::Message object which can then just be told +deliver+ to send itself out.
You never instantiate your mailer class. Rather, your delivery instance methods are automatically wrapped in class methods that start with the word +deliver_+ followed by the name of the mailer method that you would like to deliver.
So, how exactly does this work?
h4. Complete List of Action Mailer Methods
Looking at the +ActionMailer::Base+ source, you will find this:
There are just three methods that you need to send pretty much any email message:
* <tt>headers</tt> - Specifies any header on the email you want, you can pass a hash of header field names and value pairs, or you can call <tt>headers[:field_name] = 'value'</tt>
* <tt>attachments</tt> - Allows you to add attachments to your email, for example <tt>attachments['file-name.jpg'] = File.read('file-name.jpg')</tt>
* <tt>mail</tt> - Sends the actual email itself. You can pass in headers as a hash to the mail method as a parameter, mail will then create an email, either plain text, or multipart, depending on what email templates you have defined.
h5. Custom Headers
Defining custom headers are simple, you can do it one of three ways:
* Defining a header field as a parameter to the +mail+ method:
<ruby>
def method_missing(method_symbol, *parameters)#:nodoc:
case method_symbol.id2name
when /^create_([_a-z]\w*)/ then new($1, *parameters).mail
when /^deliver_([_a-z]\w*)/ then new($1, *parameters).deliver!
when "new" then nil
else super
end
end
mail(:x_spam => value)
</ruby>
Hence, if the method name starts with +deliver_+ followed by any combination of lowercase letters or underscore, +method_missing+ calls +new+ on your mailer class (+UserMailer+ in our example above), sending the combination of lower case letters or underscore, along with the parameters. The resulting object is then sent the +deliver!+ method, which well... delivers it.
* Passing in a key value assignment to the +headers+ method:
h4. Complete List of Action Mailer User-Settable Attributes
<ruby>
headers[:x_spam] = value
</ruby>
|bcc| The BCC addresses of the email, either as a string (for a single address) or an array of strings (for multiple addresses)|
|body| The body of the email. This is either a hash (in which case it specifies the variables to pass to the template when it is rendered), or a string, in which case it specifies the actual body of the message|
|cc| The CC addresses for the email, either as a string (for a single address) or an array of strings (for multiple addresses)|
|charset| The charset to use for the email. This defaults to the +default_charset+ specified for ActionMailer::Base.|
|content_type| The content type for the email. This defaults to "text/plain" but the filename may specify it|
|from| The from address of the email|
|reply_to| The address (if different than the "from" address) to direct replies to this email|
|headers| Additional headers to be added to the email|
|implicit_parts_order| The order in which parts should be sorted, based on the content type. This defaults to the value of +default_implicit_parts_order+|
|mime_version| Defaults to "1.0", but may be explicitly given if needed|
|recipient| The recipient addresses of the email, either as a string (for a single address) or an array of strings (for multiple addresses)|
|sent_on| The timestamp on which the message was sent. If unset, the header will be set by the delivery agent|
|subject| The subject of the email|
|template| The template to use. This is the "base" template name, without the extension or directory, and may be used to have multiple mailer methods share the same template|
* Passing a hash of key value pairs to the +headers+ method:
<ruby>
headers {:x_spam => value, :x_special => another_value}
</ruby>
h5. Adding Attachments
Adding attachments has been simplified in Action Mailer 3.0.
* Pass the file name and content and Action Mailer and the Mail gem will automatically guess the mime_type, set the encoding and create the attachment.
<ruby>
attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
</ruby>
NOTE: Mail will automatically Base64 encode an attachment, if you want something different, pre encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method.
* Pass the file name and specify headers and content and Action Mailer and Mail will use the settings you pass in.
<ruby>
encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
:encoding => 'SpecialEncoding',
:content => encoded_content }
</ruby>
NOTE: If you specify an encoding, Mail will assume that your content is already encoded and not try to Base64 encode it.
h4. Mailer Views
Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because it's name is the same as the mailer method. So for example, in our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.text.html.erb+ for the HTML version and +welcome_email.text.plain.erb+ for the plain text version.
Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because it's name is the same as the mailer method. So for example, in our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version.
To change the default mailer view for your action you do something like:
<ruby>
class UserMailer < ActionMailer::Base
default :from => "notifications@example.com"
def welcome_email(user)
recipients user.email
from "My Awesome Site Notifications<notifications@example.com>"
subject "Welcome to My Awesome Site"
sent_on Time.now
body( {:user => user, :url => "http://example.com/login"})
content_type "text/html"
# use some_other_template.text.(html|plain).erb instead
template "some_other_template"
@user = user
@url = "http://example.com/login"
mail(:to => user.email,
:subject => "Welcome to My Awesome Site") do |format|
format.html { render 'another_template' }
format.text { render 'another_template' }
end
end
end
</ruby>
Will render 'another_template.text.erb' and 'another_template.html.erb'. The render command is the same one used inside of Action Controller, so you can use all the same options, such as <tt>:text</tt> etc.
h4. Action Mailer Layouts
Just like controller views, you can also have mailer layouts. The layout name needs to end in "_mailer" to be automatically recognized by your mailer as a layout. So in our UserMailer example, we need to call our layout +user_mailer.text.(html|plain).erb+. In order to use a different file just use:
Just like controller views, you can also have mailer layouts. The layout name needs to be the same as your mailer, such as +user_mailer.html.erb+ and +user_mailer.text.erb+ to be automatically recognized by your mailer as a layout.
In order to use a different file just use:
<ruby>
class UserMailer < ActionMailer::Base
layout 'awesome' # use awesome.text.(html|plain).erb as the layout
layout 'awesome' # use awesome.(html|text).erb as the layout
end
</ruby>
Just like with controller views, use +yield+ to render the view inside the layout.
You can also pass in a <tt>:layout => 'layout_name'</tt> option to the render call inside the format block to specify different layouts for different actions:
<ruby>
class UserMailer < ActionMailer::Base
def welcome_email(user)
mail(:to => user.email) do |format|
format.html { render :layout => 'my_layout' }
format.text
end
end
end
</ruby>
Will render the HTML part using the <tt>my_layout.html.erb</tt> file and the text part with the usual <tt>user_mailer.text.erb</tt> file if it exists.
h4. Generating URLs in Action Mailer Views
URLs can be generated in mailer views using +url_for+ or named routes.
Unlike controllers, the mailer instance doesn't have any context about the incoming request so you'll need to provide the +:host+, +:controller+, and +:action+:
<erb>
<%= url_for(:host => "example.com", :controller => "welcome", :action => "greeting") %>
<%= url_for(:host => "example.com",
:controller => "welcome",
:action => "greeting") %>
</erb>
When using named routes you only need to supply the +:host+:
<erb>
<%= users_url(:host => "example.com") %>
<%= user_url(@user, :host => "example.com") %>
</erb>
Email clients have no web context and so paths have no base URL to form complete web addresses. Thus, when using named routes only the "_url" variant makes sense.
It is also possible to set a default host that will be used in all mailers by setting the +:host+ option in
the +ActionMailer::Base.default_url_options+ hash as follows:
It is also possible to set a default host that will be used in all mailers by setting the +:host+ option in the +ActionMailer::Base.default_url_options+ hash as follows:
<erb>
ActionMailer::Base.default_url_options[:host] = "example.com"
</erb>
<ruby>
class UserMailer < ActionMailer::Base
default_url_options[:host] = "example.com"
This can also be set as a configuration option in +config/environment.rb+:
<erb>
config.action_mailer.default_url_options = { :host => "example.com" }
</erb>
If you set a default +:host+ for your mailers you need to pass +:only_path => false+ to +url_for+. Otherwise it doesn't get included.
def welcome_email(user)
@user = user
@url = user_url(@user)
mail(:to => user.email,
:subject => "Welcome to My Awesome Site")
end
end
</ruby>
h4. Sending Multipart Emails
Action Mailer will automatically send multipart emails if you have different templates for the same action. So, for our UserMailer example, if you have +welcome_email.text.plain.erb+ and +welcome_email.text.html.erb+ in +app/views/user_mailer+, Action Mailer will automatically send a multipart email with the HTML and text versions setup as different parts.
Action Mailer will automatically send multipart emails if you have different templates for the same action. So, for our UserMailer example, if you have +welcome_email.text.erb+ and +welcome_email.html.erb+ in +app/views/user_mailer+, Action Mailer will automatically send a multipart email with the HTML and text versions setup as different parts.
To explicitly specify multipart messages, you can do something like:
The order of the parts getting inserted is determined by the <tt>:parts_order</tt> inside of the <tt>ActionMailer::Base.default</tt> method. If you want to explicitly alter the order, you can either change the <tt>:parts_order</tt> or explicitly render the parts in a different order:
<ruby>
class UserMailer < ActionMailer::Base
def welcome_email(user)
recipients user.email_address
subject "New account information"
from "system@example.com"
content_type "multipart/alternative"
part :content_type => "text/html",
:body => "<p>html content, can also be the name of an action that you call<p>"
part "text/plain" do |p|
p.body = "text content, can also be the name of an action that you call"
@user = user
@url = user_url(@user)
mail(:to => user.email,
:subject => "Welcome to My Awesome Site") do |format|
format.html
format.text
end
end
end
</ruby>
Will put the HTML part first, and the plain text part second.
h4. Sending Emails with Attachments
Attachments can be added by using the +attachment+ method:
@ -248,61 +316,24 @@ Attachments can be added by using the +attachment+ method:
<ruby>
class UserMailer < ActionMailer::Base
def welcome_email(user)
recipients user.email_address
subject "New account information"
from "system@example.com"
content_type "multipart/alternative"
attachment :content_type => "image/jpeg",
:body => File.read("an-image.jpg")
attachment "application/pdf" do |a|
a.body = generate_your_pdf_here()
end
@user = user
@url = user_url(@user)
attachments['terms.pdf'] = File.read('/path/terms.pdf')
mail(:to => user.email,
:subject => "Please see the Terms and Conditions attached")
end
end
</ruby>
h4. Sending Multipart Emails with Attachments
Once you use the +attachment+ method, ActionMailer will no longer automagically use the correct template based on the filename, nor will it properly order the alternative parts. You must declare which template you are using for each content type via the +part+ method. And you must declare these templates in the proper order.
In the following example, there would be two template files, +welcome_email_html.erb+ and +welcome_email_plain.erb+ in the +app/views/user_mailer+ folder. The +text/plain+ part must be listed first for full compatibility with email clients. If +text/plain+ is listed after +text/html+, some clients may display both the HTML and plain text versions of the email. The text alternatives alone must be enclosed in a +multipart/alternative+ part. Do not set the entire message's +content_type+ to +multipart/alternative+ or some email clients may ignore the display of attachments such as PDF's.
<ruby>
class UserMailer < ActionMailer::Base
def welcome_email(user)
recipients user.email_address
subject "New account information"
from "system@example.com"
part "multipart/alternative" do |pt|
pt.part "text/plain" do |p|
p.body = render_message("welcome_email_plain", :message => "text content")
end
pt.part "text/html" do |p|
p.body = render_message("welcome_email_html", :message => "<h1>HTML content</h1>")
end
end
attachment :content_type => "image/jpeg",
:body => File.read("an-image.jpg")
attachment "application/pdf" do |a|
a.body = generate_your_pdf_here()
end
end
end
</ruby>
The above will send a multipart email with an attachment, properly nested with the top level being <tt>mixed/multipart</tt> and the first part being a <tt>mixed/alternative</tt> containing the plain text and HTML email messages.
h3. Receiving Emails
Receiving and parsing emails with Action Mailer can be a rather complex endeavour. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that. So, to receive emails in your Rails app you'll need:
1. Implement a +receive+ method in your mailer.
* Implement a +receive+ method in your mailer.
2. Configure your email server to forward emails from the address(es) you would like your app to receive to +/path/to/app/script/runner 'UserMailer.receive(STDIN.read)'+.
* Configure your email server to forward emails from the address(es) you would like your app to receive to +/path/to/app/script/runner 'UserMailer.receive(STDIN.read)'+.
Once a method called +receive+ is defined in any mailer, Action Mailer will parse the raw incoming email into an email object, decode it, instantiate a new mailer, and pass the email object to the mailer +receive+ instance method. Here's an example:
@ -329,12 +360,7 @@ end
h3. Using Action Mailer Helpers
Action Mailer classes have 4 helper methods available to them:
|add_template_helper(helper_module)|Makes all the (instance) methods in the helper module available to templates rendered through this controller.|
|helper(*args, &block)| Declare a helper: helper :foo requires 'foo_helper' and includes FooHelper in the template class. helper FooHelper includes FooHelper in the template class. helper { def foo() "#{bar} is the very best" end } evaluates the block in the template class, adding method foo. helper(:three, BlindHelper) { def mice() 'mice' end } does all three. |
|helper_method| Declare a controller method as a helper. For example, helper_method :link_to def link_to(name, options) ... end makes the link_to controller method available in the view.|
|helper_attr| Declare a controller attribute as a helper. For example, helper_attr :name attr_accessor :name makes the name and name= controller methods available in the view. The is a convenience wrapper for helper_method.|
Action Mailer now just inherits from Abstract Controller, so you have access to the same generic helpers as you do in Action Controller.
h3. Action Mailer Configuration
@ -348,50 +374,36 @@ The following configuration options are best made in one of the environment file
|delivery_method|Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.|
|perform_deliveries|Determines whether deliver_* methods are actually carried out. By default they are, but this can be turned off to help functional testing.|
|deliveries|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.|
|default_charset|The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also pick a different charset from inside a method with charset.|
|default_content_type|The default content type used for the main part of the message. Defaults to "text/plain". You can also pick a different content type from inside a method with content_type.|
|default_mime_version|The default mime version used for the message. Defaults to 1.0. You can also pick a different value from inside a method with mime_version.|
|default_implicit_parts_order|When a message is built implicitly (i.e. multiple parts are assembled from templates which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to ["text/html", "text/enriched", "text/plain"]. Items that appear first in the array have higher priority in the mail client and appear last in the mime encoded message. You can also pick a different order from inside a method with implicit_parts_order.|
h4. Example Action Mailer Configuration
An example would be:
An example would be adding the following to your appropriate <tt>config/environments/env.rb</tt> file:
<ruby>
ActionMailer::Base.delivery_method = :sendmail
ActionMailer::Base.sendmail_settings = {
:location => '/usr/sbin/sendmail',
:arguments => '-i -t'
}
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.default_charset = "iso-8859-1"
config.action_mailer.delivery_method = :sendmail
# Defaults to:
# config.action_mailer.sendmail_settings = {
# :location => '/usr/sbin/sendmail',
# :arguments => '-i -t'
# }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
</ruby>
h4. Action Mailer Configuration for GMail
Instructions copied from "this blog entry":http://www.fromjavatoruby.com/2008/11/actionmailer-with-gmail-must-issue.html by Robert Zotter.
First you must install the "action_mailer_tls":http://github.com/openrain/action_mailer_tls plugin, then all you have to do is configure Action Mailer:
As Action Mailer now uses the Mail gem, this becomes as simple as adding to your <tt>config/environments/env.rb</tt> file:
<ruby>
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "domain.com",
:user_name => "user@domain.com",
:password => "password",
:authentication => :plain
}
</ruby>
h4. Configure Action Mailer to Recognize HAML Templates
In +config/environment.rb+, add the following line:
<ruby>
ActionMailer::Base.register_template_extension('haml')
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => 'baci.lindsaar.net',
:user_name => '<username>',
:password => '<password>',
:authentication => 'plain',
:enable_starttls_auto => true }
</ruby>
h3. Mailer Testing
@ -412,7 +424,8 @@ class UserMailerTest < ActionMailer::TestCase
# Test the body of the sent email contains what we expect it to
assert_equal [user.email], email.to
assert_equal "Welcome to My Awesome Site", email.subject
assert_match /Welcome to example.com, #{user.first_name}/, email.body
assert_match /<h1>Welcome to example.com, #{user.name}<\/h1>/, email.encoded
assert_match /Welcome to example.com, #{user.name}/, email.encoded
end
end
</ruby>

@ -181,7 +181,7 @@ def apply_rails_template
end
def bundle_if_dev_or_edge
run "gem bundle" if dev_or_edge?
run "bundle install" if dev_or_edge?
end
protected

@ -7,7 +7,7 @@ gem "rails", "<%= Rails::VERSION::STRING %>"
## Bundle edge rails:
<%- if options.dev? -%>
directory "<%= Rails::Generators::RAILS_DEV_PATH %>", :glob => "{*/,}*.gemspec"
path "<%= Rails::Generators::RAILS_DEV_PATH %>", :glob => "{*/,}*.gemspec"
gem "rails", "<%= Rails::VERSION::STRING %>"
<%- else -%>
<%= "# " unless options.edge? %>gem "rails", :git => "git://github.com/rails/rails.git"

@ -1,5 +1,5 @@
#--
# Copyright (c) 2004-2009 David Heinemeier Hansson
# Copyright (c) 2004-2010 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the

@ -168,15 +168,15 @@ def test_file_is_added_for_backwards_compatibility
end
def test_dev_option
generator([destination_root], :dev => true).expects(:run).with("gem bundle")
generator([destination_root], :dev => true).expects(:run).with("bundle install")
silence(:stdout){ generator.invoke }
rails_path = File.expand_path('../../..', Rails.root)
dev_gem = %(directory #{rails_path.inspect}, :glob => "{*/,}*.gemspec")
dev_gem = %(path #{rails_path.inspect}, :glob => "{*/,}*.gemspec")
assert_file 'Gemfile', /^#{Regexp.escape(dev_gem)}$/
end
def test_edge_option
generator([destination_root], :edge => true).expects(:run).with("gem bundle")
generator([destination_root], :edge => true).expects(:run).with("bundle install")
silence(:stdout){ generator.invoke }
edge_gem = %(gem "rails", :git => "git://github.com/rails/rails.git")
assert_file 'Gemfile', /^#{Regexp.escape(edge_gem)}$/