From 9707d1787d80a9951b729b7fea7b59cbad3fc77a Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Tue, 18 Nov 2008 10:50:21 -0600 Subject: FIx minor errors in Getting Started & Associations guides --- railties/doc/guides/source/association_basics.txt | 8 ++++---- railties/doc/guides/source/getting_started_with_rails.txt | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/railties/doc/guides/source/association_basics.txt b/railties/doc/guides/source/association_basics.txt index e0c9ee35d3..39d92be2d2 100644 --- a/railties/doc/guides/source/association_basics.txt +++ b/railties/doc/guides/source/association_basics.txt @@ -354,8 +354,8 @@ In designing a data model, you will sometimes find a model that should have a re [source, ruby] ------------------------------------------------------- class Employee < ActiveRecord::Base - has_many :subordinates, :class_name => "User", :foreign_key => "manager_id" - belongs_to :manager, :class_name => "User" + has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id" + belongs_to :manager, :class_name => "Employee" end ------------------------------------------------------- @@ -1336,7 +1336,7 @@ end ===== +:offset+ -The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records. +The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. ===== +:order+ @@ -1704,7 +1704,7 @@ end ===== +:offset+ -The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records. +The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. ===== +:order+ diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt index 00c6d52eef..9adcc729a3 100644 --- a/railties/doc/guides/source/getting_started_with_rails.txt +++ b/railties/doc/guides/source/getting_started_with_rails.txt @@ -1021,7 +1021,7 @@ class CommentsController < ApplicationController def show @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def new @@ -1033,7 +1033,7 @@ class CommentsController < ApplicationController @post = Post.find(params[:post_id]) @comment = @post.comments.build(params[:comment]) if @comment.save - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "new" end @@ -1041,14 +1041,14 @@ class CommentsController < ApplicationController def edit @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def update @post = Post.find(params[:post_id]) @comment = Comment.find(params[:id]) if @comment.update_attributes(params[:comment]) - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "edit" end -- cgit v1.2.3 From 24bc0b267d1c313d78424eeffda6d8eaa5be0c24 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Tue, 18 Nov 2008 10:50:42 -0600 Subject: Regenerate Guide HTML --- .../doc/guides/html/actioncontroller_basics.html | 20 +- railties/doc/guides/html/association_basics.html | 8 +- .../guides/html/getting_started_with_rails.html | 8 +- railties/doc/guides/html/i18n.html | 1079 ++++++++++++++++++++ railties/doc/guides/html/index.html | 13 + 5 files changed, 1110 insertions(+), 18 deletions(-) create mode 100644 railties/doc/guides/html/i18n.html diff --git a/railties/doc/guides/html/actioncontroller_basics.html b/railties/doc/guides/html/actioncontroller_basics.html index 66563bf1a3..4af157d4f7 100644 --- a/railties/doc/guides/html/actioncontroller_basics.html +++ b/railties/doc/guides/html/actioncontroller_basics.html @@ -723,7 +723,7 @@ http://www.gnu.org/software/src-highlite --> end -

Note that while for session values, you set the key to nil, to delete a cookie value, you should use cookies.delete(:key).

+

Note that while for session values you set the key to nil, to delete a cookie value you should use cookies.delete(:key).

6. Filters

@@ -767,7 +767,7 @@ http://www.gnu.org/software/src-highlite --> end
-

In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_filter :

+

In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_filter:

end
-

Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.

+

Now, the LoginsController's new and create actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.

6.1. After Filters and Around Filters

In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.

@@ -872,7 +872,7 @@ http://www.gnu.org/software/src-highlite --> end
-

Now the create action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for every action in LoginsController, which is not what we want. You can limit which actions it will be used for with the :only and :except options just like a filter:

+

Now the create action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the new action will be rendered. But there's something rather important missing from the verification above: It will be used for every action in LoginsController, which is not what we want. You can limit which actions it will be used for with the :only and :except options just like a filter:

Tip -It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. +It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the :x_sendfile option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the X-Sendfile header for this to work, and you still have to be careful not to use user input in a way that lets someone retrieve arbitrary files.

11.2. RESTful Downloads

@@ -1166,7 +1166,7 @@ http://www.gnu.org/software/src-highlite -->

12. Parameter Filtering

-

Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The filter_parameter_logging method can be used to filter out sensitive information from the log. It works by replacing certain values in the params hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":

+

Rails keeps a log file for each environment (development, test and production) in the log folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The filter_parameter_logging method can be used to filter out sensitive information from the log. It works by replacing certain values in the params hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":

end
-

The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true.

+

The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.

13. Rescue

diff --git a/railties/doc/guides/html/association_basics.html b/railties/doc/guides/html/association_basics.html index e8cad6c220..3eea8b421f 100644 --- a/railties/doc/guides/html/association_basics.html +++ b/railties/doc/guides/html/association_basics.html @@ -687,8 +687,8 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
class Employee < ActiveRecord::Base
-  has_many :subordinates, :class_name => "User", :foreign_key => "manager_id"
-  belongs_to :manager, :class_name => "User"
+  has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id"
+  belongs_to :manager, :class_name => "Employee"
 end
 

With this setup, you can retrieve @employee.subordinates and @employee.manager.

@@ -1941,7 +1941,7 @@ http://www.gnu.org/software/src-highlite --> end
:offset
-

The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 10 records.

+

The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 11 records.

:order

The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause).

@@ -2412,7 +2412,7 @@ http://www.gnu.org/software/src-highlite --> end
:offset
-

The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 10 records.

+

The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 11 records.

:order

The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause).

diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html index 2912bae98d..304c26a54f 100644 --- a/railties/doc/guides/html/getting_started_with_rails.html +++ b/railties/doc/guides/html/getting_started_with_rails.html @@ -1791,7 +1791,7 @@ http://www.gnu.org/software/src-highlite --> def show @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def new @@ -1803,7 +1803,7 @@ http://www.gnu.org/software/src-highlite --> @post = Post.find(params[:post_id]) @comment = @post.comments.build(params[:comment]) if @comment.save - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "new" end @@ -1811,14 +1811,14 @@ http://www.gnu.org/software/src-highlite --> def edit @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def update @post = Post.find(params[:post_id]) @comment = Comment.find(params[:id]) if @comment.update_attributes(params[:comment]) - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "edit" end diff --git a/railties/doc/guides/html/i18n.html b/railties/doc/guides/html/i18n.html new file mode 100644 index 0000000000..3504a9e366 --- /dev/null +++ b/railties/doc/guides/html/i18n.html @@ -0,0 +1,1079 @@ + + + + + The Rails Internationalization API + + + + + + + + + +
+ + + +
+

The Rails Internationalization API

+
+
+

The Ruby I18n gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or providing multi-language support in your application.

+
+
+

1. How I18n in Ruby on Rails works

+
+

Internationalization is a complex problem. Natural languages differ in so many ways that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focusses on:

+
    +
  • +

    +providing support for English and similar languages out of the box +

    +
  • +
  • +

    +making it easy to customize and extend everything for other languages +

    +
  • +
+

1.1. The overall architecture of the library

+

To solve this the Ruby I18n gem is split into two parts:

+
    +
  • +

    +The public API which is just a Ruby module with a bunch of public methods and definitions how the library works. +

    +
  • +
  • +

    +A shipped backend (which is intentionally named the Simple backend) that implements these methods. +

    +
  • +
+

As a user you should always only access the public methods on the I18n module but it is useful to know about the capabilities of the backend you use and maybe exchange the shipped Simple backend with a more powerful one.

+

1.2. The public I18n API

+

We will go into more detail about the public methods later but here's a quick overview. The most important methods are:

+
+
+
translate         # lookup translations
+localize          # localize Date and Time objects to local formats
+
+

There are also attribute readers and writers for the following attributes:

+
+
+
load_path         # announce your custom translation files
+locale            # get and set the current locale
+default_locale    # get and set the default locale
+exception_handler # use a different exception_handler
+backend           # use a different backend
+
+
+

2. Walkthrough: setup a simple I18n'ed Rails application

+
+

There are just a few, simple steps to get up and running with a I18n support for your application.

+

2.1. Configure the I18n module

+

First of all you want to tell the I18n library where it can find your custom translation files. You might also want to set your default locale to something else than English.

+

You can pick whatever directory and translation file naming scheme makes sense for you. The simplest thing possible is probably to put the following into an initializer:

+
+
+
# in config/initializer/locale.rb
+
+# tell the I18n library where to find your translations
+I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ]
+
+# you can omit this if you're happy with English as a default locale
+I18n.default_locale = :"pt-BR"
+
+

I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.

+

2.2. Set the locale in each request

+

By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en-US (American English).

+

If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this:

+
+
+
before_filter :set_locale
+def set_locale
+  # if this is nil then I18n.default_locale will be used
+  I18n.locale = params[:locale]
+end
+
+

This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt-BR (which is what Google also does). (TODO hints about other approaches in the resources section).

+

Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff.

+

2.3. Internationalize your application

+

The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application (TODO reference to wikipedia). The process of "localization" means to then provide translations and localized formats for these bits.

+

So, let's internationalize something. You most probably have something like this in one of your applications:

+
+
+
# config/routes.rb
+ActionController::Routing::Routes.draw do |map|
+  map.root :controller => 'home', :action => 'index'
+end
+
+# app/controllers/home_controller.rb
+class HomeController < ApplicationController
+  def index
+    flash[:notice] = "Hello flash!"
+  end
+end
+
+# app/views/home/index.html.erb
+<h1>Hello world!</h1>
+<p><%= flash[:notice] %></p>
+
+

TODO screenshot

+

Obviously there are two strings that are localized to English. In order to internationalize this code replace these strings with calls to Rails' #t helper with a key that makes sense for the translation:

+
+
+
# app/controllers/home_controller.rb
+class HomeController < ApplicationController
+  def index
+    flash[:notice] = t(:hello_flash)
+  end
+end
+
+# app/views/home/index.html.erb
+<h1><%=t :hello_world %></h1>
+<p><%= flash[:notice] %></p>
+
+

TODO insert note about #t helper compared to I18n.t

+

TODO insert note/reference about structuring translation keys

+

When you now render this view it will show an error message that tells you that the translations for the keys :hello_world and :hello_flash are missing.

+

TODO screenshot

+

So let's add the missing translations (i.e. do the "localization" part):

+
+
+
# lib/locale/en-US.yml
+en-US:
+  hello_world: Hello World
+  hello_flash: Hello Flash
+
+# lib/locale/pirate.yml
+pirate:
+  hello_world: Ahoy World
+  hello_flash: Ahoy Flash
+
+

There you go. Your application now shows:

+

TODO screenshot

+
+
+
I18n.t 'store.title'
+I18n.l Time.now
+
+
+

3. Overview of the I18n API features

+
+

The following purposes are covered:

+
    +
  • +

    +lookup translations +

    +
  • +
  • +

    +interpolate data into translations +

    +
  • +
  • +

    +pluralize translations +

    +
  • +
  • +

    +localize dates, numbers, currency etc. +

    +
  • +
+

3.1. Looking up translations

+

3.1.1. Basic lookup, scopes and nested keys

+

Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:

+
+
+
I18n.t :message
+I18n.t 'message'
+
+

translate also takes a :scope option which can contain one or many additional keys that will be used to specify a “namespace” or scope for a translation key:

+
+
+
I18n.t :invalid, :scope => [:active_record, :error_messages]
+
+

This looks up the :invalid message in the ActiveRecord error messages.

+

Additionally, both the key and scopes can be specified as dot separated keys as in:

+
+
+
I18n.translate :"active_record.error_messages.invalid"
+
+

Thus the following calls are equivalent:

+
+
+
I18n.t 'active_record.error_messages.invalid'
+I18n.t 'error_messages.invalid', :scope => :active_record
+I18n.t :invalid, :scope => 'active_record.error_messages'
+I18n.t :invalid, :scope => [:active_record, :error_messages]
+
+

3.1.2. Defaults

+

When a default option is given its value will be returned if the translation is missing:

+
+
+
I18n.t :missing, :default => 'Not here'
+# => 'Not here'
+
+

If the default value is a Symbol it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned.

+

E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string ‘Not here’ will be returned:

+
+
+
I18n.t :missing, :default => [:also_missing, 'Not here']
+# => 'Not here'
+
+

3.1.3. Bulk and namespace lookup

+

To lookup multiple translations at once an array of keys can be passed:

+
+
+
I18n.t [:odd, :even], :scope => 'active_record.error_messages'
+# => ["must be odd", "must be even"]
+
+

Also, a key can translate to a (potentially nested) hash as grouped translations. E.g. one can receive all ActiveRecord error messages as a Hash with:

+
+
+
I18n.t 'active_record.error_messages'
+# => { :inclusion => "is not included in the list", :exclusion => ... }
+
+

3.2. Interpolation

+

TODO explain what this is good for

+

All options besides :default and :scope that are passed to #translate will be interpolated to the translation:

+
+
+
I18n.backend.store_translations 'en-US', :thanks => 'Thanks {{name}}!'
+I18n.translate :thanks, :name => 'Jeremy'
+# => 'Thanks Jeremy!'
+
+

If a translation uses :default or :scope as a interpolation variable an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable but it has not been passed to #translate an I18n::MissingInterpolationArgument exception is raised.

+

3.3. Pluralization

+

TODO explain what this is good for

+

The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:

+
+
+
I18n.backend.store_translations 'en-US', :inbox => { # TODO change this
+  :one => '1 message',
+  :other => '{{count}} messages'
+}
+I18n.translate :inbox, :count => 2
+# => '2 messages'
+
+

The algorithm for pluralizations in en-US is as simple as:

+
+
+
entry[count == 1 ? 0 : 1]
+
+

I.e. the translation denoted as :one is regarded as singular, the other is used as plural (including the count being zero).

+

If the lookup for the key does not return an Hash suitable for pluralization an I18n::InvalidPluralizationData exception is raised.

+

3.4. Setting and passing a locale

+

The locale can be either set pseudo-globally to I18n.locale (which uses Thread.current like, e.g., Time.zone) or can be passed as an option to #translate and #localize.

+

If no locale is passed I18n.locale is used:

+
+
+
I18n.locale = :'de-DE'
+I18n.t :foo
+I18n.l Time.now
+
+

Explicitely passing a locale:

+
+
+
I18n.t :foo, :locale => :'de-DE'
+I18n.l Time.now, :locale => :'de-DE'
+
+

I18n.locale defaults to I18n.default_locale which defaults to :en-US. The default locale can be set like this:

+
+
+
I18n.default_locale = :'de-DE'
+
+
+

4. How to store your custom translations

+
+

The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. (2)

+

For example a Ruby Hash providing translations can look like this:

+
+
+
{
+  :'pt-BR' => {
+    :foo => {
+      :bar => "baz"
+    }
+  }
+}
+
+

The equivalent YAML file would look like this:

+
+
+
"pt-BR":
+  foo:
+    bar: baz
+
+

As you see in both cases the toplevel key is the locale. :foo is a namespace key and :bar is the key for the translation "baz".

+

Here is a "real" example from the ActiveSupport en-US translations YAML file:

+
+
+
"en-US":
+  date:
+    formats:
+      default: "%Y-%m-%d"
+      short: "%b %d"
+      long: "%B %d, %Y"
+
+

So, all of the following equivalent lookups will return the :short date format "%B %d":

+
+
+
I18n.t 'date.formats.short'
+I18n.t 'formats.short', :scope => :date
+I18n.t :short, :scope => 'date.formats'
+I18n.t :short, :scope => [:date, :formats]
+
+

4.1. Translations for ActiveRecord models

+

You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently lookup translations for your model and attribute names.

+

For example when you add the following translations:

+

en-US: + activerecord: + models: + user: Dude + attributes: + user: + login: "Handle" + # will translate User attribute "login" as "Handle"

+

Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle".

+

4.1.1. Error message scopes

+

ActiveRecord validation error messages can also be translated easily. ActiveRecord gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes and/or validations. It also transparently takes single table inheritance into account.

+

This gives you quite powerful means to flexibly adjust your messages to your application's needs.

+

Consider a User model with a validates_presence_of validation for the name attribute like this:

+
+
+
class User < ActiveRecord::Base
+  validates_presence_of :name
+end
+
+

The key for the error message in this case is :blank. So ActiveRecord will first try to look up an error message with:

+
+
+
activerecord.errors.messages.models.user.attributes.name.blank
+
+

If it's not there it will try:

+
+
+
activerecord.errors.messages.models.user.blank
+
+

If this is also not there it will use the default message from:

+
+
+
activerecord.errors.messages.blank
+
+

When your models are additionally using inheritance then the messages are looked up for the inherited model class names are looked up.

+

For example, you might have an Admin model inheriting from User:

+
+
+
class Admin < User
+  validates_presence_of :name
+end
+
+

Then ActiveRecord will look for messages in this order:

+
+
+
activerecord.errors.models.admin.attributes.title.blank
+activerecord.errors.models.admin.blank
+activerecord.errors.models.user.attributes.title.blank
+activerecord.errors.models.user.blank
+activerecord.errors.messages.blank
+
+

This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models or default scopes.

+

4.1.2. Error message interpolation

+

The translated model name and translated attribute name are always available for interpolation.

+

+

Count and/or value are available where applicable. Count can be used for pluralization if present:

+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ validation + + with option + + message + + interpolation +
+ validates_confirmation_of + + - + + :confirmation + + - +
+ validates_acceptance_of + + - + + :accepted + + - +
+ validates_presence_of + + - + + :blank + + - +
+ validates_length_of + + :within, :in + + :too_short + + count +
+ validates_length_of + + :within, :in + + :too_long + + count +
+ validates_length_of + + :is + + :wrong_length + + count +
+ validates_length_of + + :minimum + + :too_short + + count +
+ validates_length_of + + :maximum + + :too_long + + count +
+ validates_uniqueness_of + + - + + :taken + + value +
+ validates_format_of + + - + + :invalid + + value +
+ validates_inclusion_of + + - + + :inclusion + + value +
+ validates_exclusion_of + + - + + :exclusion + + value +
+ validates_associated + + - + + :invalid + + value +
+ validates_numericality_of + + - + + :not_a_number + + value +
+ validates_numericality_of + + :odd + + :odd + + value +
+ validates_numericality_of + + :even + + :even + + value +
+
+

4.1.3. Translations for the ActiveRecord error_messages_for helper

+

If you are using the ActiveRecord error_messages_for helper you will want to add translations for it.

+

Rails ships with the following translations:

+
+
+
"en-US":
+  activerecord:
+    errors:
+      template:
+        header:
+          one:   "1 error prohibited this {{model}} from being saved"
+          other: "{{count}} errors prohibited this {{model}} from being saved"
+        body: "There were problems with the following fields:"
+
+

4.2. Other translations and localizations

+

Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers.

+

TODO list helpers and available keys

+
+

5. Customize your I18n setup

+
+

5.1. Using different backends

+

For several reasons the shipped Simple backend only does the "simplest thing that ever could work" for Ruby on Rails (1) … which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.

+

That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:

+
+
+
I18n.backend = Globalize::Backend::Static.new
+
+

TODO expand this …? list some backends and their features?

+

5.2. Using different exception handlers

+

TODO

+
    +
  • +

    +Explain what exceptions are raised and why we are using exceptions for communication from backend to frontend. +

    +
  • +
  • +

    +Explain the default behaviour. +

    +
  • +
  • +

    +Explain the :raise option +

    +
  • +
  • +

    +Example 1: the Rails #t helper uses a custom exception handler that catches I18n::MissingTranslationData and wraps the message into a span with the CSS class "translation_missing" +

    +
  • +
  • +

    +Example 2: for tests you might want a handler that just raises all exceptions all the time +

    +
  • +
  • +

    +Example 3: a handler +

    +
  • +
+
+

6. Resources

+
+
+

7. Footnotes

+
+

(1) One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.

+

(2) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.

+
+

8. Credits

+
+
+

9. NOTES

+
+

How to contribute?

+
+ +
+
+ + diff --git a/railties/doc/guides/html/index.html b/railties/doc/guides/html/index.html index 991b10c7e8..45e131012e 100644 --- a/railties/doc/guides/html/index.html +++ b/railties/doc/guides/html/index.html @@ -338,6 +338,19 @@ of your code.

This guide covers how to build a plugin to extend the functionality of Rails.

+
+

Authors who have contributed to complete guides are listed here.

-- cgit v1.2.3 From b930d2f259f7ebf3c7134db82dde02c55e00070c Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Tue, 18 Nov 2008 11:03:31 -0600 Subject: Finishing up RDoc 2.x markup for cattr_accessors --- activemodel/lib/active_model/errors.rb | 2 ++ activeresource/lib/active_resource/base.rb | 2 ++ activesupport/lib/active_support/buffered_logger.rb | 2 ++ activesupport/lib/active_support/core_ext/logger.rb | 2 ++ 4 files changed, 8 insertions(+) diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index a99bb001e4..bcf0810290 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -24,6 +24,8 @@ module ActiveModel :even => "must be even" } + ## + # :singleton-method: # Holds a hash with all the default error messages that can be replaced by your own copy or localizations. cattr_accessor :default_error_messages diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index bb284803d8..303b09ba76 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -202,6 +202,8 @@ module ActiveResource # sets the read_timeout of the internal Net::HTTP instance to the same value. The default # read_timeout is 60 seconds on most Ruby implementations. class Base + ## + # :singleton-method: # The logger for diagnosing and tracing Active Resource calls. cattr_accessor :logger diff --git a/activesupport/lib/active_support/buffered_logger.rb b/activesupport/lib/active_support/buffered_logger.rb index 77e0b1d33f..b2c863c893 100644 --- a/activesupport/lib/active_support/buffered_logger.rb +++ b/activesupport/lib/active_support/buffered_logger.rb @@ -13,6 +13,8 @@ module ActiveSupport MAX_BUFFER_SIZE = 1000 + ## + # :singleton-method: # Set to false to disable the silencer cattr_accessor :silencer self.silencer = true diff --git a/activesupport/lib/active_support/core_ext/logger.rb b/activesupport/lib/active_support/core_ext/logger.rb index c622554860..24fe7294c9 100644 --- a/activesupport/lib/active_support/core_ext/logger.rb +++ b/activesupport/lib/active_support/core_ext/logger.rb @@ -30,6 +30,8 @@ require 'logger' # # Note: This logger is deprecated in favor of ActiveSupport::BufferedLogger class Logger + ## + # :singleton-method: # Set to false to disable the silencer cattr_accessor :silencer self.silencer = true -- cgit v1.2.3 From 64e8f14058949b0b1967a4d1282c6fc154e890e9 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Tue, 18 Nov 2008 11:05:04 -0600 Subject: Configuration options for Active Model, Active Resource, Active Support --- railties/doc/guides/html/configuring.html | 181 ++++++++++++----------------- railties/doc/guides/source/configuring.txt | 174 +++++++-------------------- 2 files changed, 114 insertions(+), 241 deletions(-) diff --git a/railties/doc/guides/html/configuring.html b/railties/doc/guides/html/configuring.html index 55f5d48554..adc827c89a 100644 --- a/railties/doc/guides/html/configuring.html +++ b/railties/doc/guides/html/configuring.html @@ -223,6 +223,8 @@ ul#navMain {
  • Configuring Active Support
  • +
  • Configuring Active Model
  • +
  • @@ -332,11 +334,78 @@ after-initializer

    default_form_builder tells Rails which form builder to use by default. The default is ActionView::Helpers::FormBuilder.

    The ERB template handler supplies one additional option:

    -

    ActionView::TemplateHandlers::ERB.erb_trim_mode gives the trim mode to be used by ERB. It defaults to -.

    +

    ActionView::TemplateHandlers::ERB.erb_trim_mode gives the trim mode to be used by ERB. It defaults to -. See the ERB documentation for more information.

    4.4. Configuring Action Mailer

    There are a number of settings available on ActionMailer::Base:

    +

    template_root gives the root folder for Action Mailer templates.

    +

    logger accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Mailer. Set to nil to disable logging.

    +

    smtp_settings allows detailed configuration for the :smtp delivery method. It accepts a hash of options, which can include any of these options:

    +
      +
    • +

      +<tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting. +

      +
    • +
    • +

      +<tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it. +

      +
    • +
    • +

      +<tt>:domain</tt> - If you need to specify a HELO domain, you can do it here. +

      +
    • +
    • +

      +<tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting. +

      +
    • +
    • +

      +<tt>:password</tt> - If your mail server requires authentication, set the password in this setting. +

      +
    • +
    • +

      +<tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>. +

      +
    • +
    +

    sendmail_settings allows detailed configuration for the sendmail delivery method. It accepts a hash of options, which can include any of these options:

    +
      +
    • +

      +<tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>. +

      +
    • +
    • +

      +<tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt>. +

      +
    • +
    +

    raise_delivery_errors specifies whether to raise an error if email delivery cannot be completed. It defaults to true.

    +

    delivery_method defines the delivery method. The allowed values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, and <tt>:test</tt>.

    +

    perform_deliveries specifies whether mail will actually be delivered. By default this is true; it can be convenient to set it to false for testing.

    +

    default_charset tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to utf-8.

    +

    default_content_type specifies the default content type used for the main part of the message. It defaults to "text/plain"

    +

    default_mime_version is the default MIME version for the message. It defaults to 1.0.

    +

    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 +<tt>["text/html", "text/enriched", "text/plain"]</tt>. Items that appear first in the array have higher priority in the mail client +and appear last in the mime encoded message.

    4.5. Configuring Active Resource

    +

    There is a single configuration setting available on ActiveResource::Base:

    +

    logger accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Active Resource. Set to nil to disable logging.

    4.6. Configuring Active Support

    +

    There are a few configuration options available in Active Support:

    +

    ActiveSupport::BufferedLogger.silencer is set to false to disable the ability to silence logging in a block. The default is true.

    +

    ActiveSupport::Cache::Store.logger specifies the logger to use within cache store operations.

    +

    ActiveSupport::Logger.silencer is set to false to disable the ability to silence logging in a block. The default is true.

    +

    4.7. Configuring Active Model

    +

    Active Model currently has a single configuration setting:

    +

    +ActiveModel::Errors.default_error_messages is an array containing all of the validation error messages.

    5. Using Initializers

    @@ -360,114 +429,6 @@ after-initializer

    November 5, 2008: Rough outline by Mike Gunderloy

    -
  • - -

    actionmailer/lib/action_mailer/base.rb -257: cattr_accessor :logger -267: cattr_accessor :smtp_settings -273: cattr_accessor :sendmail_settings -276: cattr_accessor :raise_delivery_errors -282: cattr_accessor :perform_deliveries -285: cattr_accessor :deliveries -288: cattr_accessor :default_charset -291: cattr_accessor :default_content_type -294: cattr_accessor :default_mime_version -297: cattr_accessor :default_implicit_parts_order -299: cattr_reader :protected_instance_variables

    -

    actionmailer/Rakefile -36: rdoc.options << —line-numbers << —inline-source << -A cattr_accessor=object

    -

    actionpack/lib/action_controller/base.rb -263: cattr_reader :protected_instance_variables -273: cattr_accessor :asset_host -279: cattr_accessor :consider_all_requests_local -285: cattr_accessor :allow_concurrency -317: cattr_accessor :param_parsers -321: cattr_accessor :default_charset -325: cattr_accessor :logger -329: cattr_accessor :resource_action_separator -333: cattr_accessor :resources_path_names -337: cattr_accessor :request_forgery_protection_token -341: cattr_accessor :optimise_named_routes -351: cattr_accessor :use_accept_header -361: cattr_accessor :relative_url_root

    -

    actionpack/lib/action_controller/caching/pages.rb -55: cattr_accessor :page_cache_directory -58: cattr_accessor :page_cache_extension

    -

    actionpack/lib/action_controller/caching.rb -37: cattr_reader :cache_store -48: cattr_accessor :perform_caching

    -

    actionpack/lib/action_controller/dispatcher.rb -98: cattr_accessor :error_file_path

    -

    actionpack/lib/action_controller/mime_type.rb -24: cattr_reader :html_types, :unverifiable_types

    -

    actionpack/lib/action_controller/rescue.rb -36: base.cattr_accessor :rescue_responses -40: base.cattr_accessor :rescue_templates

    -

    actionpack/lib/action_controller/session/active_record_store.rb -60: cattr_accessor :data_column_name -170: cattr_accessor :connection -173: cattr_accessor :table_name -177: cattr_accessor :session_id_column -181: cattr_accessor :data_column -282: cattr_accessor :session_class

    -

    actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb -44: cattr_accessor :included_tags, :instance_writer ⇒ false

    -

    actionpack/lib/action_view/base.rb -189: cattr_accessor :debug_rjs -193: cattr_accessor :warn_cache_misses

    -

    actionpack/lib/action_view/helpers/active_record_helper.rb -7: cattr_accessor :field_error_proc

    -

    actionpack/lib/action_view/helpers/form_helper.rb -805: cattr_accessor :default_form_builder

    -

    actionpack/lib/action_view/template_handlers/erb.rb -47: cattr_accessor :erb_trim_mode

    -

    actionpack/test/active_record_unit.rb -5: cattr_accessor :able_to_connect -6: cattr_accessor :connected

    -

    actionpack/test/controller/filters_test.rb -286: cattr_accessor :execution_log

    -

    actionpack/test/template/form_options_helper_test.rb -3:TZInfo::Timezone.cattr_reader :loaded_zones

    -

    activemodel/lib/active_model/errors.rb -28: cattr_accessor :default_error_messages

    -

    activemodel/Rakefile -19: rdoc.options << —line-numbers << —inline-source << -A cattr_accessor=object

    -

    activerecord/lib/active_record/attribute_methods.rb -9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer ⇒ false -11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer ⇒ false

    -

    activeresource/lib/active_resource/base.rb -206: cattr_accessor :logger

    -

    activeresource/Rakefile -43: rdoc.options << —line-numbers << —inline-source << -A cattr_accessor=object

    -

    activesupport/lib/active_support/buffered_logger.rb -17: cattr_accessor :silencer

    -

    activesupport/lib/active_support/cache.rb -81: cattr_accessor :logger

    -

    activesupport/lib/active_support/core_ext/class/attribute_accessors.rb -5:# cattr_accessor :hair_colors -10: def cattr_reader(*syms) -29: def cattr_writer(*syms) -50: def cattr_accessor(*syms) -51: cattr_reader(*syms) -52: cattr_writer(*syms)

    -

    activesupport/lib/active_support/core_ext/logger.rb -34: cattr_accessor :silencer

    -

    activesupport/test/core_ext/class/attribute_accessor_test.rb -6: cattr_accessor :foo -7: cattr_accessor :bar, :instance_writer ⇒ false

    -

    activesupport/test/core_ext/module/synchronization_test.rb -6: @target.cattr_accessor :mutex, :instance_writer ⇒ false

    -

    railties/doc/guides/html/creating_plugins.html -786: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field -860: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field

    -

    railties/lib/rails_generator/base.rb -93: cattr_accessor :logger

    -

    railties/Rakefile -265: rdoc.options << —line-numbers << —inline-source << —accessor << cattr_accessor=object

    -

    railties/test/rails_info_controller_test.rb -12: cattr_accessor :local_request

    -

    Rakefile -32: rdoc.options << -A cattr_accessor=object

    1. @@ -475,6 +436,8 @@ need to look for def self. ?

    + + diff --git a/railties/doc/guides/source/configuring.txt b/railties/doc/guides/source/configuring.txt index 1fb73abbb8..945e48cd45 100644 --- a/railties/doc/guides/source/configuring.txt +++ b/railties/doc/guides/source/configuring.txt @@ -113,172 +113,82 @@ There are only a few configuration options for Action View, starting with four o The ERB template handler supplies one additional option: -+ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. ++ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. See the link:http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/[ERB documentation] for more information. === Configuring Action Mailer There are a number of settings available on +ActionMailer::Base+: ++template_root+ gives the root folder for Action Mailer templates. ++logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Mailer. Set to nil to disable logging. -=== Configuring Active Resource - -=== Configuring Active Support - -== Using Initializers - organization, controlling load order - -== Using an After-Initializer ++smtp_settings+ allows detailed configuration for the +:smtp+ delivery method. It accepts a hash of options, which can include any of these options: -== Rails Environment Settings - -ENV - -== Changelog == - -http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket] +* :address - Allows you to use a remote mail server. Just change it from its default "localhost" setting. +* :port - On the off chance that your mail server doesn't run on port 25, you can change it. +* :domain - If you need to specify a HELO domain, you can do it here. +* :user_name - If your mail server requires authentication, set the username in this setting. +* :password - If your mail server requires authentication, set the password in this setting. +* :authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5. -* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy] ++sendmail_settings+ allows detailed configuration for the +sendmail+ delivery method. It accepts a hash of options, which can include any of these options: +* :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail. +* :arguments - The command line arguments. Defaults to -i -t. -actionmailer/lib/action_mailer/base.rb -257: cattr_accessor :logger -267: cattr_accessor :smtp_settings -273: cattr_accessor :sendmail_settings -276: cattr_accessor :raise_delivery_errors -282: cattr_accessor :perform_deliveries -285: cattr_accessor :deliveries -288: cattr_accessor :default_charset -291: cattr_accessor :default_content_type -294: cattr_accessor :default_mime_version -297: cattr_accessor :default_implicit_parts_order -299: cattr_reader :protected_instance_variables - -actionmailer/Rakefile -36: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' - -actionpack/lib/action_controller/base.rb -263: cattr_reader :protected_instance_variables -273: cattr_accessor :asset_host -279: cattr_accessor :consider_all_requests_local -285: cattr_accessor :allow_concurrency -317: cattr_accessor :param_parsers -321: cattr_accessor :default_charset -325: cattr_accessor :logger -329: cattr_accessor :resource_action_separator -333: cattr_accessor :resources_path_names -337: cattr_accessor :request_forgery_protection_token -341: cattr_accessor :optimise_named_routes -351: cattr_accessor :use_accept_header -361: cattr_accessor :relative_url_root ++raise_delivery_errors+ specifies whether to raise an error if email delivery cannot be completed. It defaults to +true+. -actionpack/lib/action_controller/caching/pages.rb -55: cattr_accessor :page_cache_directory -58: cattr_accessor :page_cache_extension ++delivery_method+ defines the delivery method. The allowed values are :smtp (default), :sendmail, and :test. -actionpack/lib/action_controller/caching.rb -37: cattr_reader :cache_store -48: cattr_accessor :perform_caching ++perform_deliveries+ specifies whether mail will actually be delivered. By default this is +true+; it can be convenient to set it to +false+ for testing. -actionpack/lib/action_controller/dispatcher.rb -98: cattr_accessor :error_file_path ++default_charset+ tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to +utf-8+. -actionpack/lib/action_controller/mime_type.rb -24: cattr_reader :html_types, :unverifiable_types ++default_content_type+ specifies the default content type used for the main part of the message. It defaults to "text/plain" -actionpack/lib/action_controller/rescue.rb -36: base.cattr_accessor :rescue_responses -40: base.cattr_accessor :rescue_templates ++default_mime_version+ is the default MIME version for the message. It defaults to +1.0+. -actionpack/lib/action_controller/session/active_record_store.rb -60: cattr_accessor :data_column_name -170: cattr_accessor :connection -173: cattr_accessor :table_name -177: cattr_accessor :session_id_column -181: cattr_accessor :data_column -282: cattr_accessor :session_class ++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. -actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb -44: cattr_accessor :included_tags, :instance_writer => false - -actionpack/lib/action_view/base.rb -189: cattr_accessor :debug_rjs -193: cattr_accessor :warn_cache_misses - -actionpack/lib/action_view/helpers/active_record_helper.rb -7: cattr_accessor :field_error_proc - -actionpack/lib/action_view/helpers/form_helper.rb -805: cattr_accessor :default_form_builder - -actionpack/lib/action_view/template_handlers/erb.rb -47: cattr_accessor :erb_trim_mode - -actionpack/test/active_record_unit.rb -5: cattr_accessor :able_to_connect -6: cattr_accessor :connected +=== Configuring Active Resource -actionpack/test/controller/filters_test.rb -286: cattr_accessor :execution_log +There is a single configuration setting available on +ActiveResource::Base+: -actionpack/test/template/form_options_helper_test.rb -3:TZInfo::Timezone.cattr_reader :loaded_zones ++logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Active Resource. Set to nil to disable logging. -activemodel/lib/active_model/errors.rb -28: cattr_accessor :default_error_messages +=== Configuring Active Support -activemodel/Rakefile -19: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' +There are a few configuration options available in Active Support: -activerecord/lib/active_record/attribute_methods.rb -9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer => false -11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer => false ++ActiveSupport::BufferedLogger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. ++ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations. -activeresource/lib/active_resource/base.rb -206: cattr_accessor :logger ++ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. -activeresource/Rakefile -43: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' - -activesupport/lib/active_support/buffered_logger.rb -17: cattr_accessor :silencer - -activesupport/lib/active_support/cache.rb -81: cattr_accessor :logger +=== Configuring Active Model -activesupport/lib/active_support/core_ext/class/attribute_accessors.rb -5:# cattr_accessor :hair_colors -10: def cattr_reader(*syms) -29: def cattr_writer(*syms) -50: def cattr_accessor(*syms) -51: cattr_reader(*syms) -52: cattr_writer(*syms) +Active Model currently has a single configuration setting: -activesupport/lib/active_support/core_ext/logger.rb -34: cattr_accessor :silencer ++ActiveModel::Errors.default_error_messages is an array containing all of the validation error messages. -activesupport/test/core_ext/class/attribute_accessor_test.rb -6: cattr_accessor :foo -7: cattr_accessor :bar, :instance_writer => false +== Using Initializers + organization, controlling load order -activesupport/test/core_ext/module/synchronization_test.rb -6: @target.cattr_accessor :mutex, :instance_writer => false +== Using an After-Initializer -railties/doc/guides/html/creating_plugins.html -786: cattr_accessor :yaffle_text_field, :yaffle_date_field -860: cattr_accessor :yaffle_text_field, :yaffle_date_field +== Rails Environment Settings -railties/lib/rails_generator/base.rb -93: cattr_accessor :logger +ENV -railties/Rakefile -265: rdoc.options << '--line-numbers' << '--inline-source' << '--accessor' << 'cattr_accessor=object' +== Changelog == -railties/test/rails_info_controller_test.rb -12: cattr_accessor :local_request +http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket] -Rakefile -32: rdoc.options << '-A cattr_accessor=object' +* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy] need to look for def self. ??? -- cgit v1.2.3 From b60971ad6b19a3cd72a972b459e94059d24c0848 Mon Sep 17 00:00:00 2001 From: CassioMarques Date: Tue, 18 Nov 2008 19:14:51 -0200 Subject: Added note about update_attribute not triggering validation --- .../doc/guides/html/activerecord_validations_callbacks.html | 10 +++++++++- .../doc/guides/source/activerecord_validations_callbacks.txt | 5 ++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html index b6cb481eab..097ef706ca 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -362,6 +362,14 @@ http://www.gnu.org/software/src-highlite --> => false

    Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either save, update_attribute or update_attributes) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.

    +
    + + + +
    +Caution +There are four methods that when called will trigger validation: save, save!, update_attributes and update_attributes!. There is one method left, which is update_attribute. This method will update the value of an attribute without triggering any validation, so be careful when using update_attribute, since it can let you save your objects in an invalid state.
    +

    2.2. The meaning of valid

    For verifying if an object is valid, Active Record uses the valid? method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the errors instance method. The proccess is really simple: If the errors method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the errors collection.

    @@ -722,7 +730,7 @@ http://www.gnu.org/software/src-highlite --> end end -

    If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of validate, validate_on_create or validate_on_update methods, passing it the symbols for the methods' names.

    +

    If your validation rules are too complicated and you want to break them in small methods, you can implement all of them and call one of validate, validate_on_create or validate_on_update methods, passing it the symbols for the methods' names.

    +
    class User < ActiveRecord::Base
    +  validates_presence_of :login, :email
    +
    +  protected
    +  def before_validation
    +    if self.login.nil?
    +      self.login = email unless email.blank?
    +    end
    +  end
    +end
    +
    +

    8.3. Registering callbacks by using macro-style class methods

    +

    The other way you can register a callback method is by implementing it as an ordinary method, and then using a macro-style class method to register it as a callback. The last example could be written like that:

    +
    +
    +
    class User < ActiveRecord::Base
    +  validates_presence_of :login, :email
    +
    +  before_validation :ensure_login_has_a_value
    +
    +  protected
    +  def ensure_login_has_a_value
    +    if self.login.nil?
    +      self.login = email unless email.blank?
    +    end
    +  end
    +end
    +
    +

    The macro-style class methods can also receive a block. Rails best practices say that you should only use this style of registration if the code inside your block is so short that it fits in just one line.

    +
    +
    +
    class User < ActiveRecord::Base
    +  validates_presence_of :login, :email
    +
    +  before_create {|user| user.name = user.login.capitalize if user.name.blank?}
    +end
    +
    +

    In Rails, the preferred way of registering callbacks is by using macro-style class methods. The main advantages of using macro-style class methods are:

    +
      +
    • +

      +You can add more than one method for each type of callback. Those methods will be queued for execution at the same order they were registered. +

      +
    • +
    • +

      +Readability, since your callback declarations will live at the beggining of your models' files. +

      +
    • +
    +
    + + + +
    +Caution +Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details.
    +
    + +

    9. Callbacks that get triggered when an objects is saved

    +
    +
      +
    • +

      +before_validation will be triggered before any validation upon your object is done. You can use this callback to change the object's state so it becames valid. +

      +
    • +
    +
    +

    10. Changelog

    diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt index cbd914405e..a369a66bd3 100644 --- a/railties/doc/guides/source/activerecord_validations_callbacks.txt +++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt @@ -477,6 +477,79 @@ person.errors.clear person.errors # => nil ------------------------------------------------------------------ +== Callbacks + +Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database. + +=== Callbacks registration + +In order to use the available callbacks, you need to registrate them. There are two ways of doing that. + +=== Registering callbacks by overriding the callback methods + +You can specify the callback method direcly, by overriding it. Let's see how it works using the +before_validation+ callback, which will surprisingly run right before any validation is done. + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + protected + def before_validation + if self.login.nil? + self.login = email unless email.blank? + end + end +end +------------------------------------------------------------------ + +=== Registering callbacks by using macro-style class methods + +The other way you can register a callback method is by implementing it as an ordinary method, and then using a macro-style class method to register it as a callback. The last example could be written like that: + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + before_validation :ensure_login_has_a_value + + protected + def ensure_login_has_a_value + if self.login.nil? + self.login = email unless email.blank? + end + end +end +------------------------------------------------------------------ + +The macro-style class methods can also receive a block. Rails best practices say that you should only use this style of registration if the code inside your block is so short that it fits in just one line. + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + before_create {|user| user.name = user.login.capitalize if user.name.blank?} +end +------------------------------------------------------------------ + +In Rails, the preferred way of registering callbacks is by using macro-style class methods. The main advantages of using macro-style class methods are: + +* You can add more than one method for each type of callback. Those methods will be queued for execution at the same order they were registered. +* Readability, since your callback declarations will live at the beggining of your models' files. + +CAUTION: Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details. + +== Callbacks that get triggered when an objects is saved + +* +before_validation+ will be triggered before any validation upon your object is done. You can use this callback to change the object's state so it becames valid. + + + + + + == Changelog -- cgit v1.2.3