From cbf4bef492eb9e65e51019924e19346b1aba07ad Mon Sep 17 00:00:00 2001
From: Mike Gunderloy
+Request#relative_url_root is deprecated. Use ActionController::Base.relative_url_root instead. +
+Rails 2.3 delivers a variety of new and improved features, including pervasive Rack integration, refreshed support for Rails Engines, nested transactions for Active Record, dynamic and default scopes, unified rendering, more efficient routing, application templates, and quiet backtraces. This list covers the major upgrades, but doesn’t include every little bug fix and change. If you want to see everything, check out the list of commits in the main Rails repository on GitHub.
Rails 2.3 delivers a variety of new and improved features, including pervasive Rack integration, refreshed support for Rails Engines, nested transactions for Active Record, dynamic and default scopes, unified rendering, more efficient routing, application templates, and quiet backtraces. This list covers the major upgrades, but doesn’t include every little bug fix and change. If you want to see everything, check out the list of commits in the main Rails repository on GitHub or review the CHANGELOG files for the individual Rails components.
-ActionController::Dispatcher maintains its own default middleware stack. Middlewares can be injected in, reordered, and removed. The stack is compiled into a chain on boot. You can configure the middleware stack in environment.rb +ActionController::Dispatcher maintains its own default middleware stack. Middlewares can be injected in, reordered, and removed. The stack is compiled into a chain on boot. You can configure the middleware stack in environment.rb
-You can still change you session store with ActionController::Base.session_store = :active_record_store +You can still change your session store with ActionController::Base.session_store = :active_record_store
You know about dynamic finders in Rails (which allow you to concoct methods like find_by_color_and_flavor on the fly) and named scopes (which allow you to encapsulate reusable query conditions into friendly names like currently_active). Well, now you can have dynamic scope methods. The idea is to put together syntax that allows filtering on the fly <i>and</i> method chaining. For example:
You know about dynamic finders in Rails (which allow you to concoct methods like find_by_color_and_flavor on the fly) and named scopes (which allow you to encapsulate reusable query conditions into friendly names like currently_active). Well, now you can have dynamic scope methods. The idea is to put together syntax that allows filtering on the fly and method chaining. For example:
Rails chooses between file, template, and action depending on whether there is a leading slash, an embedded slash, or no slash at all in what’s to be rendered. Note that you can also use a symbol instead of a string when rendering an action. Other rendering styles (:inline, :text, :update, :nothing, :json, :xml, :js) still require an explicit option.
Rails chooses between file, template, and action depending on whether there is a leading slash, an embedded slash, or no slash at all in what’s to be rendered. Note that you can also use a symbol instead of a string when rendering an action. Other rendering styles (:inline, :text, :update, :nothing, :json, :xml, :js) still require an explicit option.
If you’re one of the people who has always been bothered by the special-case naming of application.rb, rejoice! It’s been reworked to be application_controller.rb in Rails 2.3. In addition, there’s a new rake task, rake rails:update:application_controller to do this automatically for you - and it will be run as part of the normal rake rails:update process.
Rails now has built-in support for HTTP digest authentication. To use it, you call authenticate_or_request_with_http_digest with a block that returns the user’s password (which is then hashed and compared against the transmitted credentials):
class PostsController < ApplicationController + Users = {"dhh" => "secret"} + before_filter :authenticate + + def secret + render :text => "Password Required!" + end + + private + def authenticate + realm = "Application" + authenticate_or_request_with_http_digest(realm) do |name| + Users[name] + end + end +end
+Lead Contributor: Gregg Kellogg +
++More Information: What’s New in Edge Rails: HTTP Digest Authentication +
+There are a couple of significant routing changes in Rails 2.3. The formatted_ route helpers are gone, in favor just passing in :format as an option. This cuts down the route generation process by 50% for any resource - and can save a substantial amount of memory (up to 100MB on large applications). If your code uses the formatted_ helpers, it will still work for the time being - but that behavior is deprecated and your application will be more efficient if you rewrite those routes using the new standard. Another big change is that Rails now supports multiple routing files, not just routes.rb. You can use RouteSet#add_configuration_file to bring in more routes at any time - without clearing the currently-loaded routes. While this change is most useful for Engines, you can use it in any application that needs to load routes in batches.
Lead Contributors: Aaron Batalion and David Heinemeier Hansson
Lead Contributors: Aaron Batalion
A big change pushed the underpinnings of Action Controller session storage down to the Rack level. This involved a good deal of work in the code, though it should be completely transparent to your Rails applications (as a bonus, some icky patches around the old CGI session handler got removed). It’s still significant, though, for one simple reason: non-Rails Rack applications have access to the same session storage handlers (and therefore the same session) as your Rails applications. In addition, sessions are now lazy-loaded (in line with the loading improvements to the rest of the framework). This means that you no longer need to explicitly disable sessions if you don’t want them; just don’t refer to them and they won’t load.
There are a couple of changes to the code for handling MIME types in Rails. First, MIME::Type now implements the =~ operator, making things much cleaner when you need to check for the presence of a type that has synonyms:
render @article # Equivalent of render :partial => 'articles/_article', :object => @article -render @articles # Equivalent of render :partial => 'articles/_article', :collection => @articles
render @article # Equivalent of render :partial => 'articles/_article', :object => @article +render @articles # Equivalent of render :partial => 'articles/_article', :collection => @articles
@@ -596,7 +655,27 @@ More Information: 5.5. Other Action View Changes
+ Action View already haD a bunch of helpers to aid in generating select controls, but now there’s one more: grouped_options_for_select. This one accepts an array or hash of strings, and converts them into a string of option tags wrapped with optgroup tags. For example: returns
@@ -705,7 +784,7 @@ More Information:
Rails 2.3 incorporates Jeremy McAnally’s "rg":http://github.com/jeremymcanally/rg/tree/master application generator. What this means is that we now have template-based application generation built right into Rails; if you have a set of plugins you include in every application (among many other use cases), you can just set up a template once and use it over and over again when you run the rails command. There’s also a rake task to apply a template to an existing application: Rails 2.3 incorporates Jeremy McAnally’s rg application generator. What this means is that we now have template-based application generation built right into Rails; if you have a set of plugins you include in every application (among many other use cases), you can just set up a template once and use it over and over again when you run the rails command. There’s also a rake task to apply a template to an existing application: There are 3 was 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 block 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.5.5. grouped_options_for_select Helper Method
+grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]],
+ "Cowboy Hat", "Choose a product...")
<option value="">Choose a product...</option>
+<optgroup label="Hats">
+ <option value="Baseball Cap">Baseball Cap</option>
+ <option selected="selected" value="Cowboy Hat">Cowboy Hat</option>
+</optgroup>
5.6. Other Action View Changes
7.2. Application Templates
-2.4. 4. Wire it up so that the system sends the email when a user signs up
+2.1.4. 4. Wire it up so that the system sends the email when a user signs up
Notice how we call deliver_welcome_email? Where is that method? Well if you remember, we created a method called welcome_email in UserMailer, right? Well, as part of the "magic" of rails, we deliver the email identified by welcome_email by calling deliver_welcome_email.
That’s it! Now whenever your users signup, they will be greeted with a nice welcome email. Next up, we’ll talk about how to test a mailer model.
Notice how we call deliver_welcome_email? Where is that method? Well if you remember, we created a method called welcome_email in UserMailer, right? Well, as part of the "magic" of rails, we deliver the email identified by welcome_email by calling deliver_welcome_email. The next section will go through this in more detail.
That’s it! Now whenever your users signup, they will be greeted with a nice welcome email.
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:
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. The signup_notification method defined above is +delivered by invoking Notifier.deliver_signup_notification.
So, how exactly does this work?
In ActionMailer:Base, you will find this:
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
Ah, this makes things so much clearer :) so 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 parameter. The resulting object is then sent the deliver! method, which well... delivers it.
bcc |
+Specify the BCC addresses for the message |
+
body |
+Define the body of the message. 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 text of the message. |
+
cc |
+Specify the CC addresses for the message. |
+
charset |
+Specify the charset to use for the message. This defaults to the default_charset specified for ActionMailer::Base. |
+
content_type |
+Specify the content type for the message. This defaults to <text/plain in most cases, but can be automatically set in some situations. |
+
from |
+Specify the from address for the message. |
+
reply_to |
+Specify the address (if different than the "from" address) to direct replies to this message. |
+
headers |
+Specify additional headers to be added to the message. |
+
implicit_parts_order |
+Specify the order in which parts should be sorted, based on content-type. This defaults to the value for the default_implicit_parts_order. |
+
mime_version |
+Defaults to "1.0", but may be explicitly given if needed. |
+
recipient |
+The recipient addresses for the message, either as a string (for a single address) or an array (for multiple addresses). |
+
sent_on |
+The date on which the message was sent. If not set (the default), the header will be set by the delivery agent. |
+
subject |
+Specify the subject of the message. |
+
template |
+Specify the template name to use for current message. This is the "base" template name, without the extension or directory, and may be used to have multiple mailer methods share the same template. |
+
Mailer views are located in /app/views/name_of_mailer_class. 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.txt.erb for the plain text version.
To change the default mailer view for your action you do something like:
class UserMailer < ActionMailer::Base + + 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" + + # change the default from welcome_email.[html, txt].erb + template "some_other_template" # this will be in app/views/user_mailer/some_other_template.[html, txt].erb + end + +end
Just like controller views, you can also have mailer layouts. The layout needs 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.[html,txt].erb. In order to use a different file just use:
class UserMailer < ActionMailer::Base + + layout 'awesome' # will use awesome.html.erb as the layout + +end
Just like with controller views, use yield to render the view inside the layout.
Coming soon!
The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...)
template_root |
+Determines the base from which template references will be made. |
+||||||||||||
logger |
+the logger is used for generating information on the mailing run if available. + Can be set to nil for no logging. Compatible with both Ruby’s own Logger and Log4r loggers. |
+||||||||||||
smtp_settings |
+Allows detailed configuration for :smtp delivery method:
+
|
+||||||||||||
sendmail_settings |
+Allows you to override options for the :sendmail delivery method.
+
|
+||||||||||||
raise_delivery_errors |
+Whether or not errors should be raised if the email fails to be delivered. |
+||||||||||||
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. |
+
An example would be:
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"
Instructions copied from http://http://www.fromjavatoruby.com/2008/11/actionmailer-with-gmail-must-issue.html
First you must install the action_mailer_tls plugin from http://code.openrain.com/rails/action_mailer_tls/, then all you have to do is configure action mailer.
ActionMailer::Base.smtp_settings = { + :address => "smtp.gmail.com", + :port => 587, + :domain => "domain.com", + :user_name => "user@domain.com", + :password => "password", + :authentication => :plain +}
In environment.rb, add the following line:
ActionMailer::Base.register_template_extension('haml')
Testing mailers involves 2 things. One is that the mail was queued and the other that the body contains what we expect it to contain. With that in mind, we could test our example mailer from above like so:
What have we done? Well, we sent the email and stored the returned object in the email variable. We then ensured that it was sent (the first assert), then, in the second batch of assertion, we ensure that the email does indeed contain the values that we expect.
This guide presented how to create a mailer and how to test it. In reality, you may find that writing your tests before you actually write your code to be a rewarding experience. It may take some time to get used to TDD (Test Driven Development), but coding this way achieves two major benefits. Firstly, you know that the code does indeed work, because the tests fail (because there’s no code), then they pass, because the code that satisfies the tests was written. Secondly, when you start with the tests, you don’t have to make time AFTER you write the code, to write the tests, then never get around to it. The tests are already there and testing has now become part of your coding regimen.
- Attribute - | -- Purpose - | -
---|---|
- created_at / created_on - | -- Rails stores the current date & time to this field when creating the record. - | -
- updated_at / updated_on - | -- Rails stores the current date & time to this field when updating the record. - | -
- lock_version - | -- Adds optimistic locking to a model more about optimistic locking. - | -
- type - | -- Specifies that the model uses Single Table Inheritance more about STI. - | -
- id - | -- All models require an id. the default is name is "id" but can be changed using the "set_primary_key" or "primary_key" methods. - | -
- table_name\_count - | -- Can be used to caches the number of belonging objects on the associated class. - | -
By default rails assumes all tables will use “id” as their primary key to identify each record. Though fortunately you won’t have explicitly declare this, Rails will automatically create that field unless you tell it not to.
For example suppose you created a database table called cars:
mysql> CREATE TABLE cars ( - id INT, - color VARCHAR(100), - doors INT, - horses INT, - model VARCHAR(100) - );
Now you created a class named Car, which is to represent an instance of a record from your table.
class Car -end
As you might expect without defining the explicit mappings between your class and the table it is impossible for Rails or any other program to correctly map those relationships.
>> c = Car.new -=> #<Class:0x11e1e90> ->> c.doors -NoMethodError: undefined method `doors' for #<Class:0x11e1e90> - from (irb):2
Now you could define a door methods to write and read data to and from the database. In a nutshell this is what ActiveRecord does. According to the Rails API: -“Active Record objects don‘t specify their attributes directly, but rather infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.” -Lets try our Car class again, this time inheriting from ActiveRecord.
class Car < ActiveRecord::Base -end
Now if we try to access an attribute of the table ActiveRecord automatically handles the mappings for us, as you can see in the following example.
>> c = Car.new -=> #<Car id: nil, doors: nil, color: nil, horses: nil, model: nil> ->> c.doors -=> nil
Rails further extends this model by giving each ActiveRecord a way of describing the variety of ways records are associated with one another. We will touch on some of these associations later in the guide but I encourage readers who are interested to read the guide to ActiveRecord associations for an in-depth explanation of the variety of ways rails can model associations. -- Associations between objects controlled by meta-programming macros.
== STOPED HERE+