From 721afdcc4b58c65f36122b10ec998b913a147912 Mon Sep 17 00:00:00 2001
From: Prem Sichanugrist
Date: Mon, 3 Sep 2012 21:21:24 -0400
Subject: Fix remaining formatting problems in the guide
---
guides/source/action_controller_overview.md | 10 +-
guides/source/action_mailer_basics.md | 70 +++---
guides/source/action_view_overview.md | 50 ++--
guides/source/active_model_basics.md | 2 +-
guides/source/active_record_querying.md | 49 ++--
.../source/active_record_validations_callbacks.md | 30 +--
guides/source/active_support_core_extensions.md | 27 ++-
guides/source/active_support_instrumentation.md | 10 +-
guides/source/ajax_on_rails.md | 149 ++++++------
guides/source/api_documentation_guidelines.md | 17 +-
guides/source/asset_pipeline.md | 93 ++++----
guides/source/association_basics.md | 240 +++++++++----------
guides/source/caching_with_rails.md | 8 +-
guides/source/command_line.md | 2 +-
guides/source/configuring.md | 256 +++++++++++----------
guides/source/contributing_to_ruby_on_rails.md | 2 +-
guides/source/debugging_rails_applications.md | 66 +++---
guides/source/engines.md | 24 +-
guides/source/form_helpers.md | 44 ++--
guides/source/getting_started.md | 83 ++++---
guides/source/i18n.md | 74 +++---
guides/source/initialization.md | 6 +-
guides/source/layouts_and_rendering.md | 214 ++++++++---------
guides/source/migrations.md | 10 +-
guides/source/performance_testing.md | 2 +-
guides/source/plugins.md | 70 +++---
guides/source/rails_application_templates.md | 26 +--
guides/source/rails_on_rack.md | 68 ++++--
guides/source/routing.md | 19 +-
guides/source/security.md | 157 ++++++-------
30 files changed, 956 insertions(+), 922 deletions(-)
(limited to 'guides/source')
diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md
index 2db11a6c31..b4c059641b 100644
--- a/guides/source/action_controller_overview.md
+++ b/guides/source/action_controller_overview.md
@@ -120,7 +120,7 @@ If you're writing a web service application, you might find yourself more comfor
So for example, if you are sending this JSON parameter:
-```
+```json
{ "company": { "name": "acme", "address": "123 Carrot Street" } }
```
@@ -128,7 +128,7 @@ You'll get `params[:company]` as `{ :name => "acme", "address" => "123 Carrot St
Also, if you've turned on `config.wrap_parameters` in your initializer or calling `wrap_parameters` in your controller, you can safely omit the root element in the JSON/XML parameter. The parameters will be cloned and wrapped in the key according to your controller's name by default. So the above parameter can be written as:
-```
+```json
{ "name": "acme", "address": "123 Carrot Street" }
```
@@ -309,7 +309,7 @@ redirect_to root_url, :flash => { :referral_code => 1234 }
The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display any error alerts or notices from the flash in the application's layout:
-```ruby
+```erb
@@ -328,7 +328,7 @@ This way, if an action sets a notice or an alert message, the layout will displa
You can pass anything that the session can store; you're not limited to notices and alerts:
-```ruby
+```erb
<% if flash[:just_signed_up] %>
Welcome to our site!
<% end %>
@@ -549,7 +549,7 @@ The way this is done is to add a non-guessable token which is only known to your
If you generate a form like this:
-```ruby
+```erb
<%= form_for @user do |f| %>
<%= f.text_field :username %>
<%= f.text_field :password %>
diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md
index 38fd49a161..f216c8c00d 100644
--- a/guides/source/action_mailer_basics.md
+++ b/guides/source/action_mailer_basics.md
@@ -67,7 +67,7 @@ Just like controllers, any instance variables we define in the method become ava
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
+```html+erb
@@ -171,21 +171,21 @@ 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
-mail("X-Spam" => value)
-```
+ ```ruby
+ mail("X-Spam" => value)
+ ```
* Passing in a key value assignment to the `headers` method:
-```ruby
-headers["X-Spam"] = value
-```
+ ```ruby
+ headers["X-Spam"] = value
+ ```
* Passing a hash of key value pairs to the `headers` method:
-```ruby
-headers {"X-Spam" => value, "X-Special" => another_value}
-```
+ ```ruby
+ headers {"X-Spam" => value, "X-Special" => another_value}
+ ```
TIP: All `X-Value` headers per the RFC2822 can appear more than once. If you want to delete an `X-Value` header, you need to assign it a value of `nil`.
@@ -195,20 +195,20 @@ 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
+ attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
+ ```
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
+ encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
+ attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
+ :encoding => 'SpecialEncoding',
+ :content => encoded_content }
+ ```
NOTE: If you specify an encoding, Mail will assume that your content is already encoded and not try to Base64 encode it.
@@ -218,28 +218,28 @@ Action Mailer 3.0 makes inline attachments, which involved a lot of hacking in p
* Firstly, to tell Mail to turn an attachment into an inline attachment, you just call `#inline` on the attachments method within your Mailer:
-```ruby
-def welcome
- attachments.inline['image.jpg'] = File.read('/path/to/image.jpg')
-end
-```
+ ```ruby
+ def welcome
+ attachments.inline['image.jpg'] = File.read('/path/to/image.jpg')
+ end
+ ```
* Then in your view, you can just reference `attachments[]` as a hash and specify which attachment you want to show, calling `url` on it and then passing the result into the `image_tag` method:
-```erb
-
Hello there, this is our image
+ ```html+erb
+
Hello there, this is our image
-<%= image_tag attachments['image.jpg'].url %>
-```
+ <%= image_tag attachments['image.jpg'].url %>
+ ```
* As this is a standard call to `image_tag` you can pass in an options hash after the attachment URL as you could for any other image:
-```erb
-
Hello there, this is our image
+ ```html+erb
+
Hello there, this is our image
-<%= image_tag attachments['image.jpg'].url, :alt => 'My Photo',
- :class => 'photos' %>
-```
+ <%= image_tag attachments['image.jpg'].url, :alt => 'My Photo',
+ :class => 'photos' %>
+ ```
#### Sending Email To Multiple Recipients
@@ -262,7 +262,7 @@ The same format can be used to set carbon copy (Cc:) and blind carbon copy (Bcc:
#### Sending Email With Name
Sometimes you wish to show the name of the person instead of just their email address when they receive the email. The trick to doing that is
-to format the email address in the format `"Name <email>"`.
+to format the email address in the format `"Name "`.
```ruby
def welcome_email(user)
@@ -470,6 +470,8 @@ Action Mailer Configuration
The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...)
+| Configuration | Description |
+|---------------|-------------|
|`template_root`|Determines the base from which template references will be made.|
|`logger`|Generates 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:
`: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`.
`:enable_starttls_auto` - Set this to `false` if there is a problem with your server certificate that you cannot resolve.
|
diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md
index a113ead139..d9f4eba409 100644
--- a/guides/source/action_view_overview.md
+++ b/guides/source/action_view_overview.md
@@ -133,7 +133,7 @@ Within an ERB template Ruby code can be included using both `<% %>` and `<%= %>`
Consider the following loop for names:
-```erb
+```html+erb
Names of all the people
<% @people.each do |person| %>
Name: <%= person.name %>
@@ -142,7 +142,7 @@ Consider the following loop for names:
The loop is setup in regular embedding tags `<% %>` and the name is written using the output embedding tag `<%= %>`. Note that this is not just a usage suggestion, for Regular output functions like print or puts won't work with ERB templates. So this would be wrong:
-```erb
+```html+erb
<%# WRONG %>
Hi, Mr. <% puts "Frodo" %>
```
@@ -226,13 +226,13 @@ Partial templates – usually just called "partials" – are another device for
To render a partial as part of a view, you use the `render` method within the view:
-```ruby
+```erb
<%= render "menu" %>
```
This will render a file named `_menu.html.erb` at that point within the view is being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:
-```ruby
+```erb
<%= render "shared/menu" %>
```
@@ -242,7 +242,7 @@ That code will pull in the partial from `app/views/shared/_menu.html.erb`.
One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this:
-```erb
+```html+erb
<%= render "shared/ad_banner" %>
Products
@@ -346,7 +346,7 @@ In the `show` template, we'll render the `post` partial wrapped in the `box` lay
*posts/show.html.erb*
-```ruby
+```erb
<%= render :partial => 'post', :layout => 'box', :locals => {:post => @post} %>
```
@@ -354,7 +354,7 @@ The `box` layout simply wraps the `post` partial in a `div`:
*posts/_box.html.erb*
-```ruby
+```html+erb
<%= yield %>
@@ -364,7 +364,7 @@ The `post` partial wraps the post's `body` in a `div` with the `id` of the post
*posts/_post.html.erb*
-```ruby
+```html+erb
<%= div_for(post) do %>
<%= post.body %>
<% end %>
@@ -386,7 +386,7 @@ You can also render a block of code within a partial layout instead of calling `
*posts/show.html.erb*
-```ruby
+```html+erb
<% render(:layout => 'box', :locals => {:post => @post}) do %>
<%= div_for(post) do %>
<%= post.body %>
@@ -471,7 +471,7 @@ Renders a container tag that relates to your Active Record Object.
For example, given `@post` is the object of `Post` class, you can do:
-```ruby
+```html+erb
<%= content_tag_for(:tr, @post) do %>
<%= @post.title %>
<% end %>
@@ -487,7 +487,7 @@ This will generate this HTML output:
You can also supply HTML attributes as an additional option hash. For example:
-```ruby
+```html+erb
<%= content_tag_for(:tr, @post, :class => "frontpage") do %>
<%= @post.title %>
<% end %>
@@ -503,7 +503,7 @@ Will generate this HTML output:
You can pass a collection of Active Record objects. This method will loop through your objects and create a container for each of them. For example, given `@posts` is an array of two `Post` objects:
-```ruby
+```html+erb
<%= content_tag_for(:tr, @posts) do |post| %>
<%= post.title %>
<% end %>
@@ -524,7 +524,7 @@ Will generate this HTML output:
This is actually a convenient method which calls `content_tag_for` internally with `:div` as the tag name. You can pass either an Active Record object or a collection of objects. For example:
-```ruby
+```html+erb
<%= div_for(@post, :class => "frontpage") do %>
<%= @post.title %>
<% end %>
@@ -745,7 +745,7 @@ end
Allows you to measure the execution time of a block in a template and records the result to the log. Wrap this block around expensive operations or possible bottlenecks to get a time reading for the operation.
-```ruby
+```html+erb
<% benchmark "Process data files" do %>
<%= expensive_files_operation %>
<% end %>
@@ -759,7 +759,7 @@ This would add something like "Process data files (0.34523)" to the log, which y
A method for caching fragments of a view rather than an entire action or page. This technique is useful caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See `ActionController::Caching::Fragments` for more information.
-```ruby
+```erb
<% cache do %>
<%= render "shared/footer" %>
<% end %>
@@ -771,7 +771,7 @@ A method for caching fragments of a view rather than an entire action or page. T
The `capture` method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.
-```ruby
+```html+erb
<% @greeting = capture do %>
Welcome! The date and time is <%= Time.now %>
<% end %>
@@ -779,7 +779,7 @@ The `capture` method allows you to extract part of a template into a variable. Y
The captured variable can then be used anywhere else.
-```ruby
+```html+erb
Welcome!
@@ -798,7 +798,7 @@ For example, let's say we have a standard application layout, but also a special
*app/views/layouts/application.html.erb*
-```ruby
+```html+erb
Welcome!
@@ -812,7 +812,7 @@ For example, let's say we have a standard application layout, but also a special
*app/views/posts/special.html.erb*
-```ruby
+```html+erb
This is a special page.
<% content_for :special_script do %>
@@ -985,7 +985,7 @@ There are two types of form helpers: those that specifically work with model att
The core method of this helper, form_for, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:
-```ruby
+```html+erb
# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
<%= form_for @person, :url => { :action => "create" } do |f| %>
<%= f.text_field :first_name %>
@@ -1027,7 +1027,7 @@ check_box("post", "validated")
Creates a scope around a specific model object like form_for, but doesn't create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form:
-```ruby
+```html+erb
<%= form_for @person, :url => { :action => "update" } do |person_form| %>
First name: <%= person_form.text_field :first_name %>
Last name : <%= person_form.text_field :last_name %>
@@ -1051,7 +1051,7 @@ file_field(:user, :avatar)
Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields.
-```ruby
+```html+erb
<%= form_for @post do |f| %>
<%= f.label :title, 'Title' %>:
<%= f.text_field :title %>
@@ -1360,7 +1360,7 @@ check_box_tag 'accept'
Creates a field set for grouping HTML form elements.
-```ruby
+```html+erb
<%= field_set_tag do %>
<%= text_field_tag 'name' %>
<% end %>
@@ -1373,7 +1373,7 @@ Creates a file upload field.
Prior to Rails 3.1, if you are using file uploads, then you will need to set the multipart option for the form tag. Rails 3.1+ does this automatically.
-```ruby
+```html+erb
<%= form_tag { :action => "post" }, { :multipart => true } do %>
<%= file_field_tag "file" %>
<%= submit_tag %>
@@ -1391,7 +1391,7 @@ file_field_tag 'attachment'
Starts a form tag that points the action to an url configured with `url_for_options` just like `ActionController::Base#url_for`.
-```ruby
+```html+erb
<%= form_tag '/posts' do %>
<%= submit_tag 'Save' %>
<% end %>
diff --git a/guides/source/active_model_basics.md b/guides/source/active_model_basics.md
index 99edc20c73..bfb088ed03 100644
--- a/guides/source/active_model_basics.md
+++ b/guides/source/active_model_basics.md
@@ -71,7 +71,7 @@ end
### Conversion
-If a class defines persisted? and id methods then you can include Conversion module in that class and you can able to call Rails conversion methods to objects of that class.
+If a class defines `persisted?` and `id` methods then you can include `Conversion` module in that class and you can able to call Rails conversion methods to objects of that class.
```ruby
class Person
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index e157baa19d..097735af93 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -53,6 +53,7 @@ Retrieving Objects from the Database
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
The methods are:
+
* `bind`
* `create_with`
* `eager_load`
@@ -266,7 +267,7 @@ The SQL equivalent of the above is:
SELECT * FROM clients WHERE (clients.id IN (1,10))
```
-WARNING: `Model.find(array_of_primary_key)` will raise an `ActiveRecord::RecordNotFound` exception unless a matching record is found for all of the supplied primary keys.
+WARNING: `Model.find(array_of_primary_key)` will raise an `ActiveRecord::RecordNotFound` exception unless a matching record is found for **all** of the supplied primary keys.
#### take
@@ -548,8 +549,6 @@ To select only a subset of fields from the result set, you can specify the subse
NOTE: If the `select` method is used, all the returning objects will be [read only](#readonly-objects).
-
-
For example, to select only `viewable_by` and `locked` columns:
```ruby
@@ -568,7 +567,7 @@ Be careful because this also means you're initializing a model object with only
ActiveModel::MissingAttributeError: missing attribute:
```
-Where `<attribute>` is the attribute you asked for. The `id` method will not raise the `ActiveRecord::MissingAttributeError`, so just be careful when working with associations because they need the `id` method to function properly.
+Where `` is the attribute you asked for. The `id` method will not raise the `ActiveRecord::MissingAttributeError`, so just be careful when working with associations because they need the `id` method to function properly.
If you would like to only grab a single record per unique value in a certain field, you can use `uniq`:
@@ -650,7 +649,8 @@ SQL uses the `HAVING` clause to specify conditions on the `GROUP BY` fields. You
For example:
```ruby
-Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)").having("sum(price) > ?", 100)
+Order.select("date(created_at) as ordered_date, sum(price) as total_price").
+ group("date(created_at)").having("sum(price) > ?", 100)
```
The SQL that would be executed would be something like this:
@@ -801,7 +801,7 @@ Active Record provides two locking mechanisms:
Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An `ActiveRecord::StaleObjectError` exception is thrown if that has occurred and the update is ignored.
-Optimistic locking column
+**Optimistic locking column**
In order to use optimistic locking, the table needs to have a column called `lock_version` of type integer. Each time the record is updated, Active Record increments the `lock_version` column. If an update request is made with a lower value in the `lock_version` field than is currently in the `lock_version` column in the database, the update request will fail with an `ActiveRecord::StaleObjectError`. Example:
@@ -938,7 +938,7 @@ SELECT categories.* FROM categories
INNER JOIN posts ON posts.category_id = categories.id
```
-Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use Category.joins(:posts).select("distinct(categories.id)").
+Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use `Category.joins(:posts).select("distinct(categories.id)")`.
#### Joining Multiple Associations
@@ -1011,7 +1011,7 @@ Eager Loading Associations
Eager loading is the mechanism for loading the associated records of the objects returned by `Model.find` using as few queries as possible.
-N 1 queries problem
+**N + 1 queries problem**
Consider the following code, which finds 10 clients and prints their postcodes:
@@ -1023,9 +1023,9 @@ clients.each do |client|
end
```
-This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 ( to find 10 clients ) 10 ( one per each client to load the address ) = 11 queries in total.
+This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 (to find 10 clients) + 10 (one per each client to load the address) = **11** queries in total.
-Solution to N 1 queries problem
+**Solution to N + 1 queries problem**
Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the `includes` method of the `Model.find` call. With `includes`, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.
@@ -1039,7 +1039,7 @@ clients.each do |client|
end
```
-The above code will execute just 2 queries, as opposed to 11 queries in the previous case:
+The above code will execute just **2** queries, as opposed to **11** queries in the previous case:
```sql
SELECT * FROM clients LIMIT 10
@@ -1324,8 +1324,7 @@ Client.find_by_sql("SELECT * FROM clients
`find_by_sql` provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
-`select_all`
-------------
+### `select_all`
`find_by_sql` has a close relative called `connection#select_all`. `select_all` will retrieve objects from the database using custom SQL just like `find_by_sql` but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
@@ -1333,8 +1332,7 @@ Client.find_by_sql("SELECT * FROM clients
Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
```
-`pluck`
--------
+### `pluck`
`pluck` can be used to query a single or multiple columns from the underlying table of a model. It accepts a list of column names as argument and returns an array of values of the specified columns with the corresponding data type.
@@ -1368,8 +1366,7 @@ Client.pluck(:id)
Client.pluck(:id, :name)
```
-`ids`
------
+### `ids`
`ids` can be used to pluck all the IDs for the relation using the table's primary key.
@@ -1532,12 +1529,12 @@ may yield
```
EXPLAIN for: SELECT `users`.* FROM `users` INNER JOIN `posts` ON `posts`.`user_id` = `users`.`id` WHERE `users`.`id` = 1
-------------------------------------------------------------------------------------------
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
-------------------------------------------------------------------------------------------
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
| 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
-------------------------------------------------------------------------------------------
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
2 rows in set (0.00 sec)
```
@@ -1571,19 +1568,19 @@ yields
```
EXPLAIN for: SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
-------------------------------------------------------------------------------------
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
-------------------------------------------------------------------------------------
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
-------------------------------------------------------------------------------------
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
1 row in set (0.00 sec)
EXPLAIN for: SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1)
--------------------------------------------------------------------------------------
++----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
--------------------------------------------------------------------------------------
++----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
--------------------------------------------------------------------------------------
++----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1 row in set (0.00 sec)
```
diff --git a/guides/source/active_record_validations_callbacks.md b/guides/source/active_record_validations_callbacks.md
index 8a62103d2b..faeb62f833 100644
--- a/guides/source/active_record_validations_callbacks.md
+++ b/guides/source/active_record_validations_callbacks.md
@@ -119,28 +119,28 @@ class Person < ActiveRecord::Base
end
>> p = Person.new
-=> #
+#=> #
>> p.errors
-=> {}
+#=> {}
>> p.valid?
-=> false
+#=> false
>> p.errors
-=> {:name=>["can't be blank"]}
+#=> {:name=>["can't be blank"]}
>> p = Person.create
-=> #
+#=> #
>> p.errors
-=> {:name=>["can't be blank"]}
+#=> {:name=>["can't be blank"]}
>> p.save
-=> false
+#=> false
>> p.save!
-=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
+#=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
>> Person.create!
-=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
+#=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
```
`invalid?` is simply the inverse of `valid?`. `invalid?` triggers your validations, returning true if any errors were found in the object, and false otherwise.
@@ -333,7 +333,7 @@ This helper validates that your attributes have only numeric values. By default,
If you set `:only_integer` to `true`, then it will use the
```ruby
-/\A[-]?\d\Z/
+/\A[+-]?\d+\Z/
```
regular expression to validate the attribute's value. Otherwise, it will try to convert the value to a number using `Float`.
@@ -535,7 +535,7 @@ class Person < ActiveRecord::Base
validates :name, :presence => { :strict => true }
end
-Person.new.valid? => ActiveModel::StrictValidationFailed: Name can't be blank
+Person.new.valid? #=> ActiveModel::StrictValidationFailed: Name can't be blank
```
There is also an ability to pass custom exception to `:strict` option
@@ -545,7 +545,7 @@ class Person < ActiveRecord::Base
validates :token, :presence => true, :uniqueness => true, :strict => TokenGenerationException
end
-Person.new.valid? => TokenGenerationException: Token can't be blank
+Person.new.valid? #=> TokenGenerationException: Token can't be blank
```
Conditional Validation
@@ -605,7 +605,7 @@ All validations inside of `with_options` block will have automatically passed th
### Combining validation conditions
-On the other hand, when multiple conditions define whether or not a validation should happen, an `Array` can be used. Moreover, you can apply both `:if:` and `:unless` to the same validation.
+On the other hand, when multiple conditions define whether or not a validation should happen, an `Array` can be used. Moreover, you can apply both `:if` and `:unless` to the same validation.
```ruby
class Computer < ActiveRecord::Base
@@ -646,7 +646,7 @@ The easiest way to add custom validators for validating individual attributes is
```ruby
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
- unless value =~ /\A([^@\s])@((?:[-a-z0-9]\.)+[a-z]{2,})\z/i
+ unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
record.errors[attribute] << (options[:message] || "is not an email")
end
end
@@ -833,7 +833,7 @@ person.errors.empty? # => true
p.save # => false
p.errors[:name]
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
+# => ["can't be blank", "is too short (minimum is 3 characters)"]
```
### `errors.size`
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index 336f93bc0f..7da2b711f5 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -343,7 +343,7 @@ This method escapes whatever is needed, both for the key and the value:
```ruby
account.to_query('company[name]')
-# => "company%5Bname%5D=Johnson%26Johnson"
+# => "company%5Bname%5D=Johnson+%26+Johnson"
```
so its output is ready to be used in a query string.
@@ -1124,7 +1124,7 @@ NOTE: Defined in `active_support/core_ext/class/subclasses.rb`.
#### `descendants`
-The `descendants` method returns all classes that are `<` than its receiver:
+The `descendants` method returns all classes that are `<` than its receiver:
```ruby
class C; end
@@ -1151,7 +1151,7 @@ Extensions to `String`
#### Motivation
-Inserting data into HTML templates needs extra care. For example, you can't just interpolate `@review.title` verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the "section about cross-site scripting in the [Security guide](security.html#cross-site-scripting-xss) for further information about the risks.
+Inserting data into HTML templates needs extra care. For example, you can't just interpolate `@review.title` verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the section about cross-site scripting in the [Security guide](security.html#cross-site-scripting-xss) for further information about the risks.
#### Safe Strings
@@ -1855,7 +1855,7 @@ NOTE: Defined in `active_support/core_ext/numeric/bytes.rb`.
### Time
-Enables the use of time calculations and declarations, like @45.minutes 2.hours 4.years@.
+Enables the use of time calculations and declarations, like `45.minutes + 2.hours + 4.years`.
These methods use Time#advance for precise date calculations when using from_now, ago, etc.
as well as adding or subtracting their results from a Time object. For example:
@@ -1883,9 +1883,8 @@ converted before use:
1.year.to_f.from_now
```
-In such cases, Ruby's core
-Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
-Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
+In such cases, Ruby's core [Date](http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html) and
+[Time](http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html) should be used for precision
date and time arithmetic.
NOTE: Defined in `active_support/core_ext/numeric/time.rb`.
@@ -2414,7 +2413,7 @@ The method `in_groups_of` splits an array into consecutive groups of a certain s
or yields them in turn if a block is passed:
-```ruby
+```html+erb
<% sample.in_groups_of(3) do |a, b, c| %>
<%=h a %>
@@ -3585,7 +3584,7 @@ They are analogous. Please refer to their documentation above and take into acco
Time.zone_default
# => #
-# In Barcelona, 2010/03/28 02:00 0100 becomes 2010/03/28 03:00 0200 due to DST.
+# In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.
t = Time.local_time(2010, 3, 28, 1, 59, 59)
# => Sun Mar 28 01:59:59 +0100 2010
t.advance(:seconds => 1)
@@ -3608,7 +3607,7 @@ The method `all_day` returns a range representing the whole day of the current t
now = Time.current
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
now.all_day
-# => Mon, 09 Aug 2010 00:00:00 UTC 00:00..Mon, 09 Aug 2010 23:59:59 UTC 00:00
+# => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Mon, 09 Aug 2010 23:59:59 UTC +00:00
```
Analogously, `all_week`, `all_month`, `all_quarter` and `all_year` all serve the purpose of generating time ranges.
@@ -3617,13 +3616,13 @@ Analogously, `all_week`, `all_month`, `all_quarter` and `all_year` all serve the
now = Time.current
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
now.all_week
-# => Mon, 09 Aug 2010 00:00:00 UTC 00:00..Sun, 15 Aug 2010 23:59:59 UTC 00:00
+# => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Sun, 15 Aug 2010 23:59:59 UTC +00:00
now.all_month
-# => Sat, 01 Aug 2010 00:00:00 UTC 00:00..Tue, 31 Aug 2010 23:59:59 UTC 00:00
+# => Sat, 01 Aug 2010 00:00:00 UTC +00:00..Tue, 31 Aug 2010 23:59:59 UTC +00:00
now.all_quarter
-# => Thu, 01 Jul 2010 00:00:00 UTC 00:00..Thu, 30 Sep 2010 23:59:59 UTC 00:00
+# => Thu, 01 Jul 2010 00:00:00 UTC +00:00..Thu, 30 Sep 2010 23:59:59 UTC +00:00
now.all_year
-# => Fri, 01 Jan 2010 00:00:00 UTC 00:00..Fri, 31 Dec 2010 23:59:59 UTC 00:00
+# => Fri, 01 Jan 2010 00:00:00 UTC +00:00..Fri, 31 Dec 2010 23:59:59 UTC +00:00
```
### Time Constructors
diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md
index 76ce98514f..efdcb9f4a5 100644
--- a/guides/source/active_support_instrumentation.md
+++ b/guides/source/active_support_instrumentation.md
@@ -412,11 +412,11 @@ listen to any notification.
The block receives the following arguments:
-# The name of the event
-# Time when it started
-# Time when it finished
-# An unique ID for this event
-# The payload (described in previous sections)
+* The name of the event
+* Time when it started
+* Time when it finished
+* An unique ID for this event
+* The payload (described in previous sections)
```ruby
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |name, started, finished, unique_id, data|
diff --git a/guides/source/ajax_on_rails.md b/guides/source/ajax_on_rails.md
index ab94d2b5c9..58fcdf1daf 100644
--- a/guides/source/ajax_on_rails.md
+++ b/guides/source/ajax_on_rails.md
@@ -182,89 +182,92 @@ link_to_remote "Add to cart",
* The very first parameter, a string, is the text of the link which appears on the page.
* The second parameter, the `options` hash is the most interesting part as it has the AJAX specific stuff:
-** *:url* This is the only parameter that is always required to generate the simplest remote link (technically speaking, it is not required, you can pass an empty `options` hash to `link_to_remote` - but in this case the URL used for the POST request will be equal to your current URL which is probably not your intention). This URL points to your AJAX action handler. The URL is typically specified by Rails REST view helpers, but you can use the `url_for` format too.
-** *:update* Specifying a DOM id of the element we would like to update. The above example demonstrates the simplest way of accomplishing this - however, we are in trouble if the server responds with an error message because that will be injected into the page too! However, Rails has a solution for this situation:
+ * **:url** This is the only parameter that is always required to generate the simplest remote link (technically speaking, it is not required, you can pass an empty `options` hash to `link_to_remote` - but in this case the URL used for the POST request will be equal to your current URL which is probably not your intention). This URL points to your AJAX action handler. The URL is typically specified by Rails REST view helpers, but you can use the `url_for` format too.
+ * **:update** Specifying a DOM id of the element we would like to update. The above example demonstrates the simplest way of accomplishing this - however, we are in trouble if the server responds with an error message because that will be injected into the page too! However, Rails has a solution for this situation:
-```ruby
-link_to_remote "Add to cart",
- :url => add_to_cart_url(product),
- :update => { :success => "cart", :failure => "error" }
-```
+ ```ruby
+ link_to_remote "Add to cart",
+ :url => add_to_cart_url(product),
+ :update => { :success => "cart", :failure => "error" }
+ ```
-If the server returns 200, the output of the above example is equivalent to our first, simple one. However, in case of error, the element with the DOM id `error` is updated rather than the `cart` element.
+ If the server returns 200, the output of the above example is equivalent to our first, simple one. However, in case of error, the element with the DOM id `error` is updated rather than the `cart` element.
-** *position* By default (i.e. when not specifying this option, like in the examples before) the response is injected into the element with the specified DOM id, replacing the original content of the element (if there was any). You might want to alter this behavior by keeping the original content - the only question is where to place the new content? This can specified by the `position` parameter, with four possibilities:
-*** `:before` Inserts the response text just before the target element. More precisely, it creates a text node from the response and inserts it as the left sibling of the target element.
-*** `:after` Similar behavior to `:before`, but in this case the response is inserted after the target element.
-*** `:top` Inserts the text into the target element, before its original content. If the target element was empty, this is equivalent with not specifying `:position` at all.
-*** `:bottom` The counterpart of `:top`: the response is inserted after the target element's original content.
+ * **position** By default (i.e. when not specifying this option, like in the examples before) the response is injected into the element with the specified DOM id, replacing the original content of the element (if there was any). You might want to alter this behavior by keeping the original content - the only question is where to place the new content? This can specified by the `position` parameter, with four possibilities:
+ * `:before` Inserts the response text just before the target element. More precisely, it creates a text node from the response and inserts it as the left sibling of the target element.
+ * `:after` Similar behavior to `:before`, but in this case the response is inserted after the target element.
+ * `:top` Inserts the text into the target element, before its original content. If the target element was empty, this is equivalent with not specifying `:position` at all.
+ * `:bottom` The counterpart of `:top`: the response is inserted after the target element's original content.
-A typical example of using `:bottom` is inserting a new <li> element into an existing list:
+ A typical example of using `:bottom` is inserting a new \
element into an existing list:
-```ruby
-link_to_remote "Add new item",
- :url => items_url,
- :update => 'item_list',
- :position => :bottom
-```
+ ```ruby
+ link_to_remote "Add new item",
+ :url => items_url,
+ :update => 'item_list',
+ :position => :bottom
+ ```
-** *:method* Most typically you want to use a POST request when adding a remote
+ * **:method** Most typically you want to use a POST request when adding a remote
link to your view so this is the default behavior. However, sometimes you'll want to update (PATCH/PUT) or delete/destroy (DELETE) something and you can specify this with the `:method` option. Let's see an example for a typical AJAX link for deleting an item from a list:
-```ruby
-link_to_remote "Delete the item",
- :url => item_url(item),
- :method => :delete
-```
-
-Note that if we wouldn't override the default behavior (POST), the above snippet would route to the create action rather than destroy.
-
-** *JavaScript filters* You can customize the remote call further by wrapping it with some JavaScript code. Let's say in the previous example, when deleting a link, you'd like to ask for a confirmation by showing a simple modal text box to the user. This is a typical example what you can accomplish with these options - let's see them one by one:
-*** `:condition` => `code` Evaluates `code` (which should evaluate to a boolean) and proceeds if it's true, cancels the request otherwise.
-*** `:before` => `code` Evaluates the `code` just before launching the request. The output of the code has no influence on the execution. Typically used show a progress indicator (see this in action in the next example).
-*** `:after` => `code` Evaluates the `code` after launching the request. Note that this is different from the `:success` or `:complete` callback (covered in the next section) since those are triggered after the request is completed, while the code snippet passed to `:after` is evaluated after the remote call is made. A common example is to disable elements on the page or otherwise prevent further action while the request is completed.
-*** `:submit` => `dom_id` This option does not make sense for `link_to_remote`, but we'll cover it for the sake of completeness. By default, the parent element of the form elements the user is going to submit is the current form - use this option if you want to change the default behavior. By specifying this option you can change the parent element to the element specified by the DOM id `dom_id`.
-*** `:with` > `code` The JavaScript code snippet in `code` is evaluated and added to the request URL as a parameter (or set of parameters). Therefore, `code` should return a valid URL query string (like "item_type=8" or "item_type=8&sort=true"). Usually you want to obtain some value(s) from the page - let's see an example:
-
-```ruby
-link_to_remote "Update record",
- :url => record_url(record),
- :method => :patch,
- :with => "'status=' 'encodeURIComponent($('status').value) '&completed=' $('completed')"
-```
-
-This generates a remote link which adds 2 parameters to the standard URL generated by Rails, taken from the page (contained in the elements matched by the 'status' and 'completed' DOM id).
-
-** *Callbacks* Since an AJAX call is typically asynchronous, as its name suggests (this is not a rule, and you can fire a synchronous request - see the last option, `:type`) your only way of communicating with a request once it is fired is via specifying callbacks. There are six options at your disposal (in fact 508, counting all possible response types, but these six are the most frequent and therefore specified by a constant):
-*** `:loading:` => `code` The request is in the process of receiving the data, but the transfer is not completed yet.
-*** `:loaded:` => `code` The transfer is completed, but the data is not processed and returned yet
-*** `:interactive:` => `code` One step after `:loaded`: The data is fully received and being processed
-*** `:success:` => `code` The data is fully received, parsed and the server responded with "200 OK"
-*** `:failure:` => `code` The data is fully received, parsed and the server responded with *anything* but "200 OK" (typically 404 or 500, but in general with any status code ranging from 100 to 509)
-*** `:complete:` => `code` The combination of the previous two: The request has finished receiving and parsing the data, and returned a status code (which can be anything).
-*** Any other status code ranging from 100 to 509: Additionally you might want to check for other HTTP status codes, such as 404. In this case simply use the status code as a number:
-```ruby
-link_to_remote "Add new item",
- :url => items_url,
- :update => "item_list",
- 404 => "alert('Item not found!')"
-```
-Let's see a typical example for the most frequent callbacks, `:success`, `:failure` and `:complete` in action:
-
-```ruby
-link_to_remote "Add new item",
- :url => items_url,
- :update => "item_list",
- :before => "$('progress').show()",
- :complete => "$('progress').hide()",
- :success => "display_item_added(request)",
- :failure => "display_error(request)"
-```
+ ```ruby
+ link_to_remote "Delete the item",
+ :url => item_url(item),
+ :method => :delete
+ ```
+
+ Note that if we wouldn't override the default behavior (POST), the above snippet would route to the create action rather than destroy.
+
+ * **JavaScript filters** You can customize the remote call further by wrapping it with some JavaScript code. Let's say in the previous example, when deleting a link, you'd like to ask for a confirmation by showing a simple modal text box to the user. This is a typical example what you can accomplish with these options - let's see them one by one:
+ * `:condition` => `code` Evaluates `code` (which should evaluate to a boolean) and proceeds if it's true, cancels the request otherwise.
+ * `:before` => `code` Evaluates the `code` just before launching the request. The output of the code has no influence on the execution. Typically used show a progress indicator (see this in action in the next example).
+ * `:after` => `code` Evaluates the `code` after launching the request. Note that this is different from the `:success` or `:complete` callback (covered in the next section) since those are triggered after the request is completed, while the code snippet passed to `:after` is evaluated after the remote call is made. A common example is to disable elements on the page or otherwise prevent further action while the request is completed.
+ * `:submit` => `dom_id` This option does not make sense for `link_to_remote`, but we'll cover it for the sake of completeness. By default, the parent element of the form elements the user is going to submit is the current form - use this option if you want to change the default behavior. By specifying this option you can change the parent element to the element specified by the DOM id `dom_id`.
+ * `:with` > `code` The JavaScript code snippet in `code` is evaluated and added to the request URL as a parameter (or set of parameters). Therefore, `code` should return a valid URL query string (like "item_type=8" or "item_type=8&sort=true"). Usually you want to obtain some value(s) from the page - let's see an example:
+
+ ```ruby
+ link_to_remote "Update record",
+ :url => record_url(record),
+ :method => :patch,
+ :with => "'status=' + 'encodeURIComponent($('status').value) + '&completed=' + $('completed')"
+ ```
+
+ This generates a remote link which adds 2 parameters to the standard URL generated by Rails, taken from the page (contained in the elements matched by the 'status' and 'completed' DOM id).
+
+ * **Callbacks** Since an AJAX call is typically asynchronous, as its name suggests (this is not a rule, and you can fire a synchronous request - see the last option, `:type`) your only way of communicating with a request once it is fired is via specifying callbacks. There are six options at your disposal (in fact 508, counting all possible response types, but these six are the most frequent and therefore specified by a constant):
+ * `:loading:` => `code` The request is in the process of receiving the data, but the transfer is not completed yet.
+ * `:loaded:` => `code` The transfer is completed, but the data is not processed and returned yet
+ * `:interactive:` => `code` One step after `:loaded`: The data is fully received and being processed
+ * `:success:` => `code` The data is fully received, parsed and the server responded with "200 OK"
+ * `:failure:` => `code` The data is fully received, parsed and the server responded with *anything* but "200 OK" (typically 404 or 500, but in general with any status code ranging from 100 to 509)
+ * `:complete:` => `code` The combination of the previous two: The request has finished receiving and parsing the data, and returned a status code (which can be anything).
+ * Any other status code ranging from 100 to 509: Additionally you might want to check for other HTTP status codes, such as 404. In this case simply use the status code as a number:
+
+ ```ruby
+ link_to_remote "Add new item",
+ :url => items_url,
+ :update => "item_list",
+ 404 => "alert('Item not found!')"
+ ```
+
+ Let's see a typical example for the most frequent callbacks, `:success`, `:failure` and `:complete` in action:
+
+ ```ruby
+ link_to_remote "Add new item",
+ :url => items_url,
+ :update => "item_list",
+ :before => "$('progress').show()",
+ :complete => "$('progress').hide()",
+ :success => "display_item_added(request)",
+ :failure => "display_error(request)"
+ ```
+
+ * **:type** If you want to fire a synchronous request for some obscure reason (blocking the browser while the request is processed and doesn't return a status code), you can use the `:type` option with the value of `:synchronous`.
-** *:type* If you want to fire a synchronous request for some obscure reason (blocking the browser while the request is processed and doesn't return a status code), you can use the `:type` option with the value of `:synchronous`.
* Finally, using the `html_options` parameter you can add HTML attributes to the generated tag. It works like the same parameter of the `link_to` helper. There are interesting side effects for the `href` and `onclick` parameters though:
-** If you specify the `href` parameter, the AJAX link will degrade gracefully, i.e. the link will point to the URL even if JavaScript is disabled in the client browser
-** `link_to_remote` gains its AJAX behavior by specifying the remote call in the onclick handler of the link. If you supply `html_options[:onclick]` you override the default behavior, so use this with care!
+ * If you specify the `href` parameter, the AJAX link will degrade gracefully, i.e. the link will point to the URL even if JavaScript is disabled in the client browser
+ * `link_to_remote` gains its AJAX behavior by specifying the remote call in the onclick handler of the link. If you supply `html_options[:onclick]` you override the default behavior, so use this with care!
We are finished with `link_to_remote`. I know this is quite a lot to digest for one helper function, but remember, these options are common for all the rest of the Rails view helpers, so we will take a look at the differences / additional parameters in the next sections.
diff --git a/guides/source/api_documentation_guidelines.md b/guides/source/api_documentation_guidelines.md
index d8839bacf6..27924b11ad 100644
--- a/guides/source/api_documentation_guidelines.md
+++ b/guides/source/api_documentation_guidelines.md
@@ -117,6 +117,7 @@ Fonts
### Fixed-width Font
Use fixed-width fonts for:
+
* Constants, in particular class and module names.
* Method names.
* Literals like `nil`, `false`, `true`, `self`.
@@ -126,15 +127,15 @@ Use fixed-width fonts for:
```ruby
class Array
- # Calls `to_param` on all its elements and joins the result with
- # slashes. This is used by `url_for` in Action Pack.
+ # Calls +to_param+ on all its elements and joins the result with
+ # slashes. This is used by +url_for+ in Action Pack.
def to_param
collect { |e| e.to_param }.join '/'
end
end
```
-WARNING: Using a pair of `+...+` for fixed-width font only works with *words*; that is: anything matching `\A\w+\z`. For anything else use `<tt>...</tt>`, notably symbols, setters, inline snippets, etc.
+WARNING: Using a pair of `+...+` for fixed-width font only works with *words*; that is: anything matching `\A\w+\z`. For anything else use `...`, notably symbols, setters, inline snippets, etc.
### Regular Font
@@ -144,11 +145,11 @@ When "true" and "false" are English words rather than Ruby keywords use a regula
# Runs all the validations within the specified context. Returns true if no errors are found,
# false otherwise.
#
-# If the argument is false (default is `nil`), the context is set to `:create` if
-# `new_record?` is true, and to `:update` if it is not.
+# If the argument is false (default is +nil+), the context is set to :create if
+# new_record? is true, and to :update if it is not.
#
-# Validations with no `:on` option will run no matter the context. Validations with
-# some `:on` option will only run in the specified context.
+# Validations with no :on option will run no matter the context. Validations with
+# some :on option will only run in the specified context.
def valid?(context = nil)
...
end
@@ -160,7 +161,7 @@ Description Lists
In lists of options, parameters, etc. use a hyphen between the item and its description (reads better than a colon because normally options are symbols):
```ruby
-# * `:allow_nil` - Skip validation if attribute is `nil`.
+# * :allow_nil - Skip validation if attribute is `nil`.
```
The description starts in upper case and ends with a full stop—it's standard English.
diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md
index a98c118ae2..9727cd89ef 100644
--- a/guides/source/asset_pipeline.md
+++ b/guides/source/asset_pipeline.md
@@ -29,7 +29,7 @@ config.assets.enabled = false
You can also disable the asset pipeline while creating a new application by passing the `--skip-sprockets` option.
-```
+```bash
rails new appname --skip-sprockets
```
@@ -70,20 +70,13 @@ Rails' old strategy was to append a date-based query string to every asset linke
The query string strategy has several disadvantages:
-
-
- Not all caches will reliably cache content where the filename only differs by query parameters.
+1. **Not all caches will reliably cache content where the filename only differs by query parameters**
[Steve Souders recommends](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/), "...avoiding a querystring for cacheable resources". He found that in this case 5-20% of requests will not be cached. Query strings in particular do not work at all with some CDNs for cache invalidation.
-
-
- The file name can change between nodes in multi-server environments.
+
+2. **The file name can change between nodes in multi-server environments.**
The default query string in Rails 2.x is based on the modification time of the files. When assets are deployed to a cluster, there is no guarantee that the timestamps will be the same, resulting in different values being used depending on which server handles the request.
-
-
- Too much cache invalidation
+3. **Too much cache invalidation**
When static assets are deployed with each new release of code, the mtime of _all_ these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed.
-
-
Fingerprinting fixes these problems by avoiding query strings, and by ensuring that filenames are consistent based on their content.
@@ -114,11 +107,11 @@ NOTE: You must have an [ExecJS](https://github.com/sstephenson/execjs#readme) su
Pipeline assets can be placed inside an application in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`.
-`app/assets` is for assets that are owned by the application, such as custom images, JavaScript files or stylesheets.
+* `app/assets` is for assets that are owned by the application, such as custom images, JavaScript files or stylesheets.
-`lib/assets` is for your own libraries' code that doesn't really fit into the scope of the application or those libraries which are shared across applications.
+* `lib/assets` is for your own libraries' code that doesn't really fit into the scope of the application or those libraries which are shared across applications.
-`vendor/assets` is for assets that are owned by outside entities, such as code for JavaScript plugins and CSS frameworks.
+* `vendor/assets` is for assets that are owned by outside entities, such as code for JavaScript plugins and CSS frameworks.
#### Search paths
@@ -137,7 +130,7 @@ vendor/assets/somepackage/phonebox.js
would be referenced in a manifest like this:
-```
+```js
//= require home
//= require moovinator
//= require slider
@@ -152,7 +145,7 @@ app/assets/javascripts/sub/something.js
is referenced as:
-```
+```js
//= require sub/something
```
@@ -176,7 +169,7 @@ For example, if you have a jQuery library with many modules, which is stored in
The library as a whole can be accessed in the site's application manifest like so:
-```
+```js
//= require library_name
```
@@ -215,7 +208,7 @@ WARNING: If you're precompiling your assets (see [In Production](#in-production)
The asset pipeline automatically evaluates ERB. This means that if you add an `erb` extension to a CSS asset (for example, `application.css.erb`), then helpers like `asset_path` are available in your CSS rules:
-```
+```css
.class { background-image: url(<%= asset_path 'image.png' %>) }
```
@@ -223,7 +216,7 @@ This writes the path to the particular asset being referenced. In this example,
If you want to use a [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme) -- a method of embedding the image data directly into the CSS file -- you can use the `asset_data_uri` helper.
-```
+```css
#logo { background: url(<%= asset_data_uri 'logo.png' %>) }
```
@@ -247,7 +240,7 @@ The more generic form can also be used but the asset path and class must both be
If you add an `erb` extension to a JavaScript asset, making it something such as `application.js.erb`, then you can use the `asset_path` helper in your JavaScript code:
-```erb
+```js
$('#logo').attr({
src: "<%= asset_path('logo.png') %>"
});
@@ -257,7 +250,7 @@ This writes the path to the particular asset being referenced.
Similarly, you can use the `asset_path` helper in CoffeeScript files with `erb` extension (e.g., `application.js.coffee.erb`):
-```
+```js
$('#logo').attr src: "<%= asset_path('logo.png') %>"
```
@@ -267,7 +260,7 @@ Sprockets uses manifest files to determine which assets to include and serve. Th
For example, a new Rails application includes a default `app/assets/javascripts/application.js` file which contains the following lines:
-```
+```js
// ...
//= require jquery
//= require jquery_ujs
@@ -284,7 +277,7 @@ Directives are processed top to bottom, but the order in which files are include
Rails also creates a default `app/assets/stylesheets/application.css` file which contains these lines:
-```
+```js
/* ...
*= require_self
*= require_tree .
@@ -301,7 +294,7 @@ You can have as many manifest files as you need. For example the `admin.css` and
The same remarks about ordering made above apply. In particular, you can specify individual files and they are compiled in the order specified. For example, you might concatenate three CSS files together this way:
-```
+```js
/* ...
*= require reset
*= require layout
@@ -327,7 +320,7 @@ In development mode, assets are served as separate files in the order they are s
This manifest `app/assets/javascripts/application.js`:
-```
+```js
//= require core
//= require projects
//= require tickets
@@ -407,8 +400,8 @@ You can call this task on the server during deployment to create compiled versio
The rake task is:
-```
-bundle exec rake assets:precompile
+```bash
+$ bundle exec rake assets:precompile
```
For faster asset precompiles, you can partially load your application by setting
@@ -424,7 +417,7 @@ engines (or other gems) will not be loaded, which can cause missing assets.
Capistrano (v2.8.0 and above) includes a recipe to handle this in deployment. Add the following line to `Capfile`:
-```erb
+```ruby
load 'deploy/assets'
```
@@ -444,7 +437,7 @@ NOTE. The matcher (and other members of the precompile array; see below) is appl
If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the `precompile` array:
-```erb
+```ruby
config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
```
@@ -452,7 +445,7 @@ NOTE. Always specify an expected compiled filename that ends with js or css, eve
The rake task also generates a `manifest.yml` that contains a list with all your assets and their respective fingerprints. This is used by the Rails helper methods to avoid handing the mapping requests back to Sprockets. A typical manifest file looks like:
-```
+```yaml
---
rails.png: rails-bd9ad5a560b5a3a7be0808c5cd76a798.png
jquery-ui.min.js: jquery-ui-7e33882a28fc84ad0e0e47e46cbf901c.min.js
@@ -465,7 +458,7 @@ The default location for the manifest is the root of the location specified in `
This can be changed with the `config.assets.manifest` option. A fully specified path is required:
-```erb
+```ruby
config.assets.manifest = '/path/to/some/other/location'
```
@@ -477,7 +470,7 @@ Precompiled assets exist on the filesystem and are served directly by your web s
For Apache:
-```
+```apache
# The Expires* directives requires the Apache module `mod_expires` to be enabled.
# Use of ETag is discouraged when Last-Modified is present
@@ -491,7 +484,7 @@ For Apache:
For nginx:
-```
+```nginx
location ~ ^/assets/ {
expires 1y;
add_header Cache-Control public;
@@ -507,7 +500,7 @@ When files are precompiled, Sprockets also creates a [gzipped](http://en.wikiped
Nginx is able to do this automatically enabling `gzip_static`:
-```
+```nginx
location ~ ^/(assets)/ {
root /path/to/public;
gzip_static on; # to serve pre-gzipped version
@@ -518,7 +511,7 @@ location ~ ^/(assets)/ {
This directive is available if the core module that provides this feature was compiled with the web server. Ubuntu packages, even `nginx-light` have the module compiled. Otherwise, you may need to perform a manual compilation:
-```
+```bash
./configure --with-http_gzip_static_module
```
@@ -543,13 +536,13 @@ There are two caveats:
In `config/environments/development.rb`, place the following line:
-```erb
+```ruby
config.assets.prefix = "/dev-assets"
```
You will also need this in application.rb:
-```erb
+```ruby
config.assets.initialize_on_precompile = false
```
@@ -567,7 +560,7 @@ In some circumstances you may wish to use live compilation. In this mode all req
To enable this option set:
-```erb
+```ruby
config.assets.compile = true
```
@@ -579,7 +572,7 @@ This mode uses more memory, performs more poorly than the default and is not rec
If you are deploying a production application to a system without any pre-existing JavaScript runtimes, you may want to add one to your Gemfile:
-```
+```ruby
group :production do
gem 'therubyracer'
end
@@ -594,7 +587,7 @@ There is currently one option for compressing CSS, YUI. The [YUI CSS compressor]
The following line enables YUI compression, and requires the `yui-compressor` gem.
-```erb
+```ruby
config.assets.css_compressor = :yui
```
@@ -608,7 +601,7 @@ The default Gemfile includes [uglifier](https://github.com/lautis/uglifier). Thi
The following line invokes `uglifier` for JavaScript compression.
-```erb
+```ruby
config.assets.js_compressor = :uglifier
```
@@ -620,7 +613,7 @@ NOTE: You will need an [ExecJS](https://github.com/sstephenson/execjs#readme) su
The compressor config settings for CSS and JavaScript also take any object. This object must have a `compress` method that takes a string as the sole argument and it must return a string.
-```erb
+```ruby
class Transformer
def compress(string)
do_something_returning_a_string(string)
@@ -630,7 +623,7 @@ end
To enable this, pass a `new` object to the config option in `application.rb`:
-```erb
+```ruby
config.assets.css_compressor = Transformer.new
```
@@ -641,7 +634,7 @@ The public path that Sprockets uses by default is `/assets`.
This can be changed to something else:
-```erb
+```ruby
config.assets.prefix = "/some_other_path"
```
@@ -653,7 +646,7 @@ The X-Sendfile header is a directive to the web server to ignore the response fr
Apache and nginx support this option, which can be enabled in `config/environments/production.rb`.
-```erb
+```ruby
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
```
@@ -698,7 +691,7 @@ The third is updating the various environment files with the correct default opt
In `application.rb`:
-```erb
+```ruby
# Enable the asset pipeline
config.assets.enabled = true
@@ -711,7 +704,7 @@ config.assets.version = '1.0'
In `development.rb`:
-```erb
+```ruby
# Do not compress assets
config.assets.compress = false
@@ -721,7 +714,7 @@ config.assets.debug = true
And in `production.rb`:
-```erb
+```ruby
# Compress JavaScripts and CSS
config.assets.compress = true
@@ -746,7 +739,7 @@ You should not need to change `test.rb`. The defaults in the test environment ar
The following should also be added to `Gemfile`:
-```
+```ruby
# Gems used only for assets and not required
# in production environments by default.
group :assets do
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index a5e0f39b1e..6a2c58fe8e 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -423,7 +423,7 @@ If you create an association some time after you build the underlying model, you
If you create a `has_and_belongs_to_many` association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the `:join_table` option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
-WARNING: The precedence between model names is calculated using the `<` operator for `String`. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers" (because the underscore '_' is lexicographically _less_ than 's' in common encodings).
+WARNING: The precedence between model names is calculated using the `<` operator for `String`. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper\_boxes" and "papers" to generate a join table name of "papers\_paper\_boxes" because of the length of the name "paper\_boxes", but it in fact generates a join table name of "paper\_boxes\_papers" (because the underscore '\_' is lexicographically _less_ than 's' in common encodings).
Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
@@ -574,12 +574,12 @@ The `belongs_to` association creates a one-to-one match with another model. In d
When you declare a `belongs_to` association, the declaring class automatically gains four methods related to the association:
-* `association(force_reload = false)`
-* `association=(associate)`
-* `build_association(attributes = {})`
-* `create_association(attributes = {})`
+* `association(force_reload = false)`
+* `association=(associate)`
+* `build_association(attributes = {})`
+* `create_association(attributes = {})`
-In all of these methods, `association` is replaced with the symbol passed as the first argument to `belongs_to`. For example, given the declaration:
+In all of these methods, `association` is replaced with the symbol passed as the first argument to `belongs_to`. For example, given the declaration:
```ruby
class Order < ActiveRecord::Base
@@ -598,9 +598,9 @@ create_customer
NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.
-##### `association(force_reload = false)`
+##### `association(force_reload = false)`
-The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.
+The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.
```ruby
@customer = @order.customer
@@ -608,26 +608,26 @@ The `association` method returns the associated object, if any. If no a
If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass `true` as the `force_reload` argument.
-##### `_association_=(associate)`
+##### `association=(associate)`
-The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
+The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
```ruby
@order.customer = @customer
```
-##### `build_association(attributes = {})`
+##### `build_association(attributes = {})`
-The `build_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
+The `build_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
```ruby
@customer = @order.build_customer(:customer_number => 123,
:customer_name => "John Doe")
```
-##### `create_association(attributes = {})`
+##### `create_association(attributes = {})`
-The `create_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
+The `create_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
```ruby
@customer = @order.create_customer(:customer_number => 123,
@@ -852,7 +852,7 @@ TIP: If you use the `select` method on a `belongs_to` association, you should al
#### Do Any Associated Objects Exist?
-You can see if any associated objects exist by using the `association.nil?` method:
+You can see if any associated objects exist by using the `association.nil?` method:
```ruby
if @order.customer.nil?
@@ -872,12 +872,12 @@ The `has_one` association creates a one-to-one match with another model. In data
When you declare a `has_one` association, the declaring class automatically gains four methods related to the association:
-* `association(force_reload = false)`
-* `association=(associate)`
-* `build_association(attributes = {})`
-* `create_association(attributes = {})`
+* `association(force_reload = false)`
+* `association=(associate)`
+* `build_association(attributes = {})`
+* `create_association(attributes = {})`
-In all of these methods, `association` is replaced with the symbol passed as the first argument to `has_one`. For example, given the declaration:
+In all of these methods, `association` is replaced with the symbol passed as the first argument to `has_one`. For example, given the declaration:
```ruby
class Supplier < ActiveRecord::Base
@@ -896,9 +896,9 @@ create_account
NOTE: When initializing a new `has_one` or `belongs_to` association you must use the `build_` prefix to build the association, rather than the `association.build` method that would be used for `has_many` or `has_and_belongs_to_many` associations. To create one, use the `create_` prefix.
-##### `association(force_reload = false)`
+##### `association(force_reload = false)`
-The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.
+The `association` method returns the associated object, if any. If no associated object is found, it returns `nil`.
```ruby
@account = @supplier.account
@@ -906,25 +906,25 @@ The `association` method returns the associated object, if any. If no a
If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass `true` as the `force_reload` argument.
-##### `association=(associate)`
+##### `association=(associate)`
-The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
+The `association=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
```ruby
@supplier.account = @account
```
-##### `build_association(attributes = {})`
+##### `build_association(attributes = {})`
-The `build_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.
+The `build_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.
```ruby
@account = @supplier.build_account(:terms => "Net 30")
```
-##### `create_association(attributes = {})`
+##### `create_association(attributes = {})`
-The `create_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
+The `create_association` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
```ruby
@account = @supplier.create_account(:terms => "Net 30")
@@ -1101,7 +1101,7 @@ The `select` method lets you override the SQL `SELECT` clause that is used to re
#### Do Any Associated Objects Exist?
-You can see if any associated objects exist by using the `association.nil?` method:
+You can see if any associated objects exist by using the `association.nil?` method:
```ruby
if @supplier.account.nil?
@@ -1117,7 +1117,7 @@ If either of these saves fails due to validation errors, then the assignment sta
If the parent object (the one declaring the `has_one` association) is unsaved (that is, `new_record?` returns `true`) then the child objects are not saved. They will automatically when the parent object is saved.
-If you want to assign an object to a `has_one` association without saving the object, use the `association.build` method.
+If you want to assign an object to a `has_one` association without saving the object, use the `association.build` method.
### `has_many` Association Reference
@@ -1127,22 +1127,22 @@ The `has_many` association creates a one-to-many relationship with another model
When you declare a `has_many` association, the declaring class automatically gains 13 methods related to the association:
-* `collection(force_reload = false)`
-* `collection<<(object, ...)`
-* `collection.delete(object, ...)`
-* `collection=objects`
-* `collection_singular_ids`
-* `collection_singular_ids=ids`
-* `collection.clear`
-* `collection.empty?`
-* `collection.size`
-* `collection.find(...)`
-* `collection.where(...)`
-* `collection.exists?(...)`
-* `collection.build(attributes = {}, ...)`
-* `collection.create(attributes = {})`
+* `collection(force_reload = false)`
+* `collection<<(object, ...)`
+* `collection.delete(object, ...)`
+* `collection=objects`
+* `collection_singular_ids`
+* `collection_singular_ids=ids`
+* `collection.clear`
+* `collection.empty?`
+* `collection.size`
+* `collection.find(...)`
+* `collection.where(...)`
+* `collection.exists?(...)`
+* `collection.build(attributes = {}, ...)`
+* `collection.create(attributes = {})`
-In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_many`, and `collection_singular` is replaced with the singularized version of that symbol.. For example, given the declaration:
+In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_many`, and `collection_singular` is replaced with the singularized version of that symbol.. For example, given the declaration:
```ruby
class Customer < ActiveRecord::Base
@@ -1169,25 +1169,25 @@ orders.build(attributes = {}, ...)
orders.create(attributes = {})
```
-##### `collection(force_reload = false)`
+##### `collection(force_reload = false)`
-The `collection` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
+The `collection` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
```ruby
@orders = @customer.orders
```
-##### `collection<<(object, ...)`
+##### `collection<<(object, ...)`
-The `collection<<` method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
+The `collection<<` method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
```ruby
@customer.orders << @order1
```
-##### `collection.delete(object, ...)`
+##### `collection.delete(object, ...)`
-The `collection.delete` method removes one or more objects from the collection by setting their foreign keys to `NULL`.
+The `collection.delete` method removes one or more objects from the collection by setting their foreign keys to `NULL`.
```ruby
@customer.orders.delete(@order1)
@@ -1196,77 +1196,77 @@ The `collection.delete` method removes one or more objects from the col
WARNING: Additionally, objects will be destroyed if they're associated with `:dependent => :destroy`, and deleted if they're associated with `:dependent => :delete_all`.
-##### `collection=objects`
+##### `collection=objects`
-The `collection=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
+The `collection=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
-##### `collection_singular_ids`
+##### `collection_singular_ids`
-The `collection_singular_ids` method returns an array of the ids of the objects in the collection.
+The `collection_singular_ids` method returns an array of the ids of the objects in the collection.
```ruby
@order_ids = @customer.order_ids
```
-##### `collection_singular_ids=ids`
+##### `collection_singular_ids=ids`
-The `collection_singular_ids=` method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
+The `collection_singular_ids=` method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
-##### `collection.clear`
+##### `collection.clear`
-The `collection.clear` method removes every object from the collection. This destroys the associated objects if they are associated with `:dependent => :destroy`, deletes them directly from the database if `:dependent => :delete_all`, and otherwise sets their foreign keys to `NULL`.
+The `collection.clear` method removes every object from the collection. This destroys the associated objects if they are associated with `:dependent => :destroy`, deletes them directly from the database if `:dependent => :delete_all`, and otherwise sets their foreign keys to `NULL`.
-##### `collection.empty?`
+##### `collection.empty?`
-The `collection.empty?` method returns `true` if the collection does not contain any associated objects.
+The `collection.empty?` method returns `true` if the collection does not contain any associated objects.
-```ruby
+```erb
<% if @customer.orders.empty? %>
No Orders Found
<% end %>
```
-##### `collection.size`
+##### `collection.size`
-The `collection.size` method returns the number of objects in the collection.
+The `collection.size` method returns the number of objects in the collection.
```ruby
@order_count = @customer.orders.size
```
-##### `collection.find(...)`
+##### `collection.find(...)`
-The `collection.find` method finds objects within the collection. It uses the same syntax and options as `ActiveRecord::Base.find`.
+The `collection.find` method finds objects within the collection. It uses the same syntax and options as `ActiveRecord::Base.find`.
```ruby
@open_orders = @customer.orders.find(1)
```
-##### `collection.where(...)`
+##### `collection.where(...)`
-The `collection.where` method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.
+The `collection.where` method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.
```ruby
@open_orders = @customer.orders.where(:open => true) # No query yet
@open_order = @open_orders.first # Now the database will be queried
```
-##### `collection.exists?(...)`
+##### `collection.exists?(...)`
-The `collection.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as `ActiveRecord::Base.exists?`.
+The `collection.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as `ActiveRecord::Base.exists?`.
-##### `collection.build(attributes = {}, ...)`
+##### `collection.build(attributes = {}, ...)`
-The `collection.build` method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
+The `collection.build` method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
```ruby
@order = @customer.orders.build(:order_date => Time.now,
:order_number => "A12345")
```
-##### `collection.create(attributes = {})`
+##### `collection.create(attributes = {})`
-The `collection.create` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
+The `collection.create` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
```ruby
@order = @customer.orders.create(:order_date => Time.now,
@@ -1551,7 +1551,7 @@ If any of these saves fails due to validation errors, then the assignment statem
If the parent object (the one declaring the `has_many` association) is unsaved (that is, `new_record?` returns `true`) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
-If you want to assign an object to a `has_many` association without saving the object, use the `collection.build` method.
+If you want to assign an object to a `has_many` association without saving the object, use the `collection.build` method.
### `has_and_belongs_to_many` Association Reference
@@ -1561,22 +1561,22 @@ The `has_and_belongs_to_many` association creates a many-to-many relationship wi
When you declare a `has_and_belongs_to_many` association, the declaring class automatically gains 13 methods related to the association:
-* `collection(force_reload = false)`
-* `collection<<(object, ...)`
-* `collection.delete(object, ...)`
-* `collection=objects`
-* `collection_singular_ids`
-* `collection_singular_ids=ids`
-* `collection.clear`
-* `collection.empty?`
-* `collection.size`
-* `collection.find(...)`
-* `collection.where(...)`
-* `collection.exists?(...)`
-* `collection.build(attributes = {})`
-* `collection.create(attributes = {})`
+* `collection(force_reload = false)`
+* `collection<<(object, ...)`
+* `collection.delete(object, ...)`
+* `collection=objects`
+* `collection_singular_ids`
+* `collection_singular_ids=ids`
+* `collection.clear`
+* `collection.empty?`
+* `collection.size`
+* `collection.find(...)`
+* `collection.where(...)`
+* `collection.exists?(...)`
+* `collection.build(attributes = {})`
+* `collection.create(attributes = {})`
-In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_and_belongs_to_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:
+In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_and_belongs_to_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:
```ruby
class Part < ActiveRecord::Base
@@ -1610,55 +1610,55 @@ If the join table for a `has_and_belongs_to_many` association has additional col
WARNING: The use of extra attributes on the join table in a `has_and_belongs_to_many` association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a `has_many :through` association instead of `has_and_belongs_to_many`.
-##### `collection(force_reload = false)`
+##### `collection(force_reload = false)`
-The `collection` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
+The `collection` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
```ruby
@assemblies = @part.assemblies
```
-##### `collection<<(object, ...)`
+##### `collection<<(object, ...)`
-The `collection<<` method adds one or more objects to the collection by creating records in the join table.
+The `collection<<` method adds one or more objects to the collection by creating records in the join table.
```ruby
@part.assemblies << @assembly1
```
-NOTE: This method is aliased as `collection.concat` and `collection.push`.
+NOTE: This method is aliased as `collection.concat` and `collection.push`.
-##### `collection.delete(object, ...)`
+##### `collection.delete(object, ...)`
-The `collection.delete` method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
+The `collection.delete` method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
```ruby
@part.assemblies.delete(@assembly1)
```
-##### `collection=objects`
+##### `collection=objects`
-The `collection=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
+The `collection=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
-##### `collection_singular_ids`
+##### `collection_singular_ids`
-The `collection_singular_ids` method returns an array of the ids of the objects in the collection.
+The `collection_singular_ids` method returns an array of the ids of the objects in the collection.
```ruby
@assembly_ids = @part.assembly_ids
```
-##### `collection_singular_ids=ids`
+##### `collection_singular_ids=ids`
-The `collection_singular_ids=` method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
+The `collection_singular_ids=` method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
-##### `collection.clear`
+##### `collection.clear`
-The `collection.clear` method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.
+The `collection.clear` method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.
-##### `collection.empty?`
+##### `collection.empty?`
-The `collection.empty?` method returns `true` if the collection does not contain any associated objects.
+The `collection.empty?` method returns `true` if the collection does not contain any associated objects.
```ruby
<% if @part.assemblies.empty? %>
@@ -1666,46 +1666,46 @@ The `collection.empty?` method returns `true` if the collection does no
<% end %>
```
-##### `collection.size`
+##### `collection.size`
-The `collection.size` method returns the number of objects in the collection.
+The `collection.size` method returns the number of objects in the collection.
```ruby
@assembly_count = @part.assemblies.size
```
-##### `collection.find(...)`
+##### `collection.find(...)`
-The `collection.find` method finds objects within the collection. It uses the same syntax and options as `ActiveRecord::Base.find`. It also adds the additional condition that the object must be in the collection.
+The `collection.find` method finds objects within the collection. It uses the same syntax and options as `ActiveRecord::Base.find`. It also adds the additional condition that the object must be in the collection.
```ruby
@assembly = @part.assemblies.find(1)
```
-##### `collection.where(...)`
+##### `collection.where(...)`
-The `collection.where` method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection.
+The `collection.where` method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection.
```ruby
@new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago)
```
-##### `collection.exists?(...)`
+##### `collection.exists?(...)`
-The `collection.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as `ActiveRecord::Base.exists?`.
+The `collection.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as `ActiveRecord::Base.exists?`.
-##### `collection.build(attributes = {})`
+##### `collection.build(attributes = {})`
-The `collection.build` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved.
+The `collection.build` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved.
```ruby
@assembly = @part.assemblies.build(
{:assembly_name => "Transmission housing"})
```
-##### `collection.create(attributes = {})`
+##### `collection.create(attributes = {})`
-The `collection.create` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
+The `collection.create` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
```ruby
@assembly = @part.assemblies.create(
@@ -1889,7 +1889,7 @@ If any of these saves fails due to validation errors, then the assignment statem
If the parent object (the one declaring the `has_and_belongs_to_many` association) is unsaved (that is, `new_record?` returns `true`) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
-If you want to assign an object to a `has_and_belongs_to_many` association without saving the object, use the `collection.build` method.
+If you want to assign an object to a `has_and_belongs_to_many` association without saving the object, use the `collection.build` method.
### Association Callbacks
diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md
index 759562bc10..ce1a01d313 100644
--- a/guides/source/caching_with_rails.md
+++ b/guides/source/caching_with_rails.md
@@ -70,7 +70,7 @@ By default, page caching automatically gzips files (for example, to `products.ht
Nginx is able to serve compressed content directly from disk by enabling `gzip_static`:
-```
+```nginx
location / {
gzip_static on; # to serve pre-gzipped version
}
@@ -133,7 +133,7 @@ Fragment Caching allows a fragment of view logic to be wrapped in a cache block
As an example, if you wanted to show all the orders placed on your website in real time and didn't want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:
-```ruby
+```html+erb
<% Order.find_recent.each do |o| %>
<%= o.buyer.name %> bought <%= o.product.name %>
<% end %>
@@ -148,7 +148,7 @@ As an example, if you wanted to show all the orders placed on your website in re
The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you want to cache multiple fragments per action, you should provide an `action_suffix` to the cache call:
-```ruby
+```html+erb
<% cache(:action => 'recent', :action_suffix => 'all_products') do %>
All available products:
```
@@ -161,7 +161,7 @@ expire_fragment(:controller => 'products', :action => 'recent', :action_suffix =
If you don't want the cache block to bind to the action that called it, you can also use globally keyed fragments by calling the `cache` method with a key:
-```ruby
+```erb
<% cache('all_available_products') do %>
All available products:
<% end %>
diff --git a/guides/source/command_line.md b/guides/source/command_line.md
index 37957cfcdb..c5da050ddc 100644
--- a/guides/source/command_line.md
+++ b/guides/source/command_line.md
@@ -176,7 +176,7 @@ end
Then the view, to display our message (in `app/views/greetings/hello.html.erb`):
-```html
+```erb
A Greeting for You!
<%= @message %>
```
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index 1bba422740..a2c8d70095 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -48,19 +48,19 @@ These configuration methods are to be called on a `Rails::Railtie` object, such
* `config.after_initialize` takes a block which will be run _after_ Rails has finished initializing the application. That includes the initialization of the framework itself, engines, and all the application's initializers in `config/initializers`. Note that this block _will_ be run for rake tasks. Useful for configuring values set up by other initializers:
-```ruby
-config.after_initialize do
- ActionView::Base.sanitized_allowed_tags.delete 'div'
-end
-```
+ ```ruby
+ config.after_initialize do
+ ActionView::Base.sanitized_allowed_tags.delete 'div'
+ end
+ ```
* `config.asset_host` sets the host for the assets. Useful when CDNs are used for hosting assets, or when you want to work around the concurrency constraints builtin in browsers using different domain aliases. Shorter version of `config.action_controller.asset_host`.
* `config.asset_path` lets you decorate asset paths. This can be a callable, a string, or be `nil` which is the default. For example, the normal path for `blog.js` would be `/javascripts/blog.js`, let that absolute path be `path`. If `config.asset_path` is a callable, Rails calls it when generating asset paths passing `path` as argument. If `config.asset_path` is a string, it is expected to be a `sprintf` format string with a `%s` where `path` will get inserted. In either case, Rails outputs the decorated path. Shorter version of `config.action_controller.asset_path`.
-```ruby
-config.asset_path = proc { |path| "/blog/public#{path}" }
-```
+ ```ruby
+ config.asset_path = proc { |path| "/blog/public#{path}" }
+ ```
NOTE. The `config.asset_path` configuration is ignored if the asset pipeline is enabled, which is the default.
@@ -80,14 +80,14 @@ NOTE. The `config.asset_path` configuration is ignored if the asset pipeline is
* `config.console` allows you to set class that will be used as console you run `rails console`. It's best to run it in `console` block:
-```ruby
-console do
- # this block is called only when running console,
- # so we can safely require pry here
- require "pry"
- config.console = Pry
-end
-```
+ ```ruby
+ console do
+ # this block is called only when running console,
+ # so we can safely require pry here
+ require "pry"
+ config.console = Pry
+ end
+ ```
* `config.dependency_loading` is a flag that allows you to disable constant autoloading setting it to false. It only has effect if `config.cache_classes` is true, which it is by default in production mode. This flag is set to false by `config.threadsafe!`.
@@ -127,11 +127,11 @@ end
* `config.session_store` is usually set up in `config/initializers/session_store.rb` and specifies what class to use to store the session. Possible values are `:cookie_store` which is the default, `:mem_cache_store`, and `:disabled`. The last one tells Rails not to deal with sessions. Custom session stores can also be specified:
-```ruby
-config.session_store :my_custom_store
-```
+ ```ruby
+ config.session_store :my_custom_store
+ ```
-This custom store must be defined as `ActionDispatch::Session::MyCustomStore`.
+ This custom store must be defined as `ActionDispatch::Session::MyCustomStore`.
* `config.time_zone` sets the default time zone for the application and enables time zone awareness for Active Record.
@@ -202,8 +202,8 @@ The full set of methods that can be used in this block are as follows:
Every Rails application comes with a standard set of middleware which it uses in this order in the development environment:
* `ActionDispatch::SSL` forces every request to be under HTTPS protocol. Will be available if `config.force_ssl` is set to `true`. Options passed to this can be configured by using `config.ssl_options`.
-* `ActionDispatch::Static` is used to serve static assets. Disabled if `config.serve_static_assets` is `true`.
-* `Rack::Lock` wraps the app in mutex so it can only be called by a single thread at a time. Only enabled when `config.cache_classes_` is `false`.
+* `ActionDispatch::Static` is used to serve static assets. Disabled if `config.serve_static_assets` is `false`.
+* `Rack::Lock` wraps the app in mutex so it can only be called by a single thread at a time. Only enabled when `config.cache_classes` is `false`.
* `ActiveSupport::Cache::Strategy::LocalCache` serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.
* `Rack::Runtime` sets an `X-Runtime` header, containing the time (in seconds) taken to execute the request.
* `Rails::Rack::Logger` notifies the logs that the request has began. After request is complete, flushes all the logs.
@@ -332,9 +332,13 @@ The caching code adds two additional settings:
* `config.action_dispatch.default_headers` is a hash with HTTP headers that are set by default in each response. By default, this is defined as:
-```ruby
-config.action_dispatch.default_headers = { 'X-Frame-Options' => 'SAMEORIGIN', 'X-XSS-Protection' => '1; mode=block', 'X-Content-Type-Options' => 'nosniff' }
-```
+ ```ruby
+ config.action_dispatch.default_headers = {
+ 'X-Frame-Options' => 'SAMEORIGIN',
+ 'X-XSS-Protection' => '1; mode=block',
+ 'X-Content-Type-Options' => 'nosniff'
+ }
+ ```
* `config.action_dispatch.tld_length` sets the TLD (top-level domain) length for the application. Defaults to `1`.
@@ -350,9 +354,11 @@ config.action_dispatch.default_headers = { 'X-Frame-Options' => 'SAMEORIGIN', 'X
* `config.action_view.field_error_proc` provides an HTML generator for displaying errors that come from Active Record. The default is
-```ruby
-Proc.new { |html_tag, instance| %Q(
).html_safe
+ end
+ ```
* `config.action_view.default_form_builder` tells Rails which form builder to use by default. The default is `ActionView::Helpers::FormBuilder`. If you want your form builder class to be loaded after initialization (so it's reloaded on each request in development), you can pass it as a `String`
@@ -362,27 +368,29 @@ Proc.new { |html_tag, instance| %Q(
#{html_tag} %w(jquery jquery_ujs) }
-```
+ ```ruby
+ config.action_view.javascript_expansions = { :defaults => %w(jquery jquery_ujs) }
+ ```
-However, you may add to this by defining others:
+ However, you may add to this by defining others:
-```ruby
-config.action_view.javascript_expansions[:prototype] = ['prototype', 'effects', 'dragdrop', 'controls']
-```
+ ```ruby
+ config.action_view.javascript_expansions[:prototype] = [
+ 'prototype', 'effects', 'dragdrop', 'controls'
+ ]
+ ```
-And can reference in the view with the following code:
+ And can reference in the view with the following code:
-```ruby
-<%= javascript_include_tag :prototype %>
-```
+ ```ruby
+ <%= javascript_include_tag :prototype %>
+ ```
* `config.action_view.stylesheet_expansions` works in much the same way as `javascript_expansions`, but has no default key. Keys defined for this hash can be referenced in the view like such:
-```ruby
-<%= stylesheet_link_tag :special %>
-```
+ ```ruby
+ <%= stylesheet_link_tag :special %>
+ ```
* `config.action_view.cache_asset_ids` With the cache enabled, the asset tag helper methods will make fewer expensive file system calls (the default implementation checks the file system timestamp). However this prevents you from modifying any asset files while the server is running.
@@ -390,11 +398,11 @@ And can reference in the view with the following code:
* `config.action_view.prefix_partial_path_with_controller_namespace` determines whether or not partials are looked up from a subdirectory in templates rendered from namespaced controllers. For example, consider a controller named `Admin::PostsController` which renders this template:
-```erb
-<%= render @post %>
-```
+ ```erb
+ <%= render @post %>
+ ```
-The default setting is `true`, which uses the partial at `/admin/posts/_post.erb`. Setting the value to `false` would render `/posts/_post.erb`, which is the same behavior as rendering from a non-namespaced controller such as `PostsController`.
+ The default setting is `true`, which uses the partial at `/admin/posts/_post.erb`. Setting the value to `false` would render `/posts/_post.erb`, which is the same behavior as rendering from a non-namespaced controller such as `PostsController`.
### Configuring Action Mailer
@@ -403,16 +411,16 @@ There are a number of settings available on `config.action_mailer`:
* `config.action_mailer.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Mailer. Set to `nil` to disable logging.
* `config.action_mailer.smtp_settings` allows detailed configuration for the `:smtp` delivery method. It accepts a hash of options, which can include any of these options:
-** `: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`.
+ * `: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`.
* `config.action_mailer.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`.
+ * `:location` - The location of the sendmail executable. Defaults to `/usr/sbin/sendmail`.
+ * `:arguments` - The command line arguments. Defaults to `-i -t`.
* `config.action_mailer.raise_delivery_errors` specifies whether to raise an error if email delivery cannot be completed. It defaults to true.
@@ -421,22 +429,25 @@ There are a number of settings available on `config.action_mailer`:
* `config.action_mailer.perform_deliveries` specifies whether mail will actually be delivered and is true by default. It can be convenient to set it to false for testing.
* `config.action_mailer.default_options` configures Action Mailer defaults. Use to set options like `from` or `reply_to` for every mailer. These default to:
-```ruby
-:mime_version => "1.0",
-:charset => "UTF-8",
-:content_type => "text/plain",
-:parts_order => [ "text/plain", "text/enriched", "text/html" ]
-```
+
+ ```ruby
+ :mime_version => "1.0",
+ :charset => "UTF-8",
+ :content_type => "text/plain",
+ :parts_order => [ "text/plain", "text/enriched", "text/html" ]
+ ```
* `config.action_mailer.observers` registers observers which will be notified when mail is delivered.
-```ruby
-config.action_mailer.observers = ["MailObserver"]
-```
+
+ ```ruby
+ config.action_mailer.observers = ["MailObserver"]
+ ```
* `config.action_mailer.interceptors` registers interceptors which will be called before mail is sent.
-```ruby
-config.action_mailer.interceptors = ["MailInterceptor"]
-```
+
+ ```ruby
+ config.action_mailer.interceptors = ["MailInterceptor"]
+ ```
* `config.action_mailer.queue` registers the queue that will be used to deliver the mail.
```ruby
@@ -651,112 +662,111 @@ Because `Rails::Application` inherits from `Rails::Railtie` (indirectly), you ca
Below is a comprehensive list of all the initializers found in Rails in the order that they are defined (and therefore run in, unless otherwise stated).
-*`load_environment_hook`*
-Serves as a placeholder so that `:load_environment_config` can be defined to run before it.
+* `load_environment_hook` Serves as a placeholder so that `:load_environment_config` can be defined to run before it.
-*`load_active_support`* Requires `active_support/dependencies` which sets up the basis for Active Support. Optionally requires `active_support/all` if `config.active_support.bare` is un-truthful, which is the default.
+* `load_active_support` Requires `active_support/dependencies` which sets up the basis for Active Support. Optionally requires `active_support/all` if `config.active_support.bare` is un-truthful, which is the default.
-*`initialize_logger`* Initializes the logger (an `ActiveSupport::BufferedLogger` object) for the application and makes it accessible at `Rails.logger`, provided that no initializer inserted before this point has defined `Rails.logger`.
+* `initialize_logger` Initializes the logger (an `ActiveSupport::BufferedLogger` object) for the application and makes it accessible at `Rails.logger`, provided that no initializer inserted before this point has defined `Rails.logger`.
-*`initialize_cache`* If `Rails.cache` isn't set yet, initializes the cache by referencing the value in `config.cache_store` and stores the outcome as `Rails.cache`. If this object responds to the `middleware` method, its middleware is inserted before `Rack::Runtime` in the middleware stack.
+* `initialize_cache` If `Rails.cache` isn't set yet, initializes the cache by referencing the value in `config.cache_store` and stores the outcome as `Rails.cache`. If this object responds to the `middleware` method, its middleware is inserted before `Rack::Runtime` in the middleware stack.
-*`set_clear_dependencies_hook`* Provides a hook for `active_record.set_dispatch_hooks` to use, which will run before this initializer. This initializer -- which runs only if `cache_classes` is set to `false` -- uses `ActionDispatch::Callbacks.after` to remove the constants which have been referenced during the request from the object space so that they will be reloaded during the following request.
+* `set_clear_dependencies_hook` Provides a hook for `active_record.set_dispatch_hooks` to use, which will run before this initializer. This initializer -- which runs only if `cache_classes` is set to `false` -- uses `ActionDispatch::Callbacks.after` to remove the constants which have been referenced during the request from the object space so that they will be reloaded during the following request.
-*`initialize_dependency_mechanism`* If `config.cache_classes` is true, configures `ActiveSupport::Dependencies.mechanism` to `require` dependencies rather than `load` them.
+* `initialize_dependency_mechanism` If `config.cache_classes` is true, configures `ActiveSupport::Dependencies.mechanism` to `require` dependencies rather than `load` them.
-*`bootstrap_hook`* Runs all configured `before_initialize` blocks.
+* `bootstrap_hook` Runs all configured `before_initialize` blocks.
-*`i18n.callbacks`* In the development environment, sets up a `to_prepare` callback which will call `I18n.reload!` if any of the locales have changed since the last request. In production mode this callback will only run on the first request.
+* `i18n.callbacks` In the development environment, sets up a `to_prepare` callback which will call `I18n.reload!` if any of the locales have changed since the last request. In production mode this callback will only run on the first request.
-*`active_support.initialize_whiny_nils`* Requires `active_support/whiny_nil` if `config.whiny_nils` is true. This file will output errors such as:
+* `active_support.initialize_whiny_nils` Requires `active_support/whiny_nil` if `config.whiny_nils` is true. This file will output errors such as:
-```
- Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
-```
+ ```
+ Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
+ ```
-And:
+ And:
-```
-You have a nil object when you didn't expect it!
-You might have expected an instance of Array.
-The error occurred while evaluating nil.each
-```
+ ```
+ You have a nil object when you didn't expect it!
+ You might have expected an instance of Array.
+ The error occurred while evaluating nil.each
+ ```
-*`active_support.deprecation_behavior`* Sets up deprecation reporting for environments, defaulting to `:log` for development, `:notify` for production and `:stderr` for test. If a value isn't set for `config.active_support.deprecation` then this initializer will prompt the user to configure this line in the current environment's `config/environments` file. Can be set to an array of values.
+* `active_support.deprecation_behavior` Sets up deprecation reporting for environments, defaulting to `:log` for development, `:notify` for production and `:stderr` for test. If a value isn't set for `config.active_support.deprecation` then this initializer will prompt the user to configure this line in the current environment's `config/environments` file. Can be set to an array of values.
-*`active_support.initialize_time_zone`* Sets the default time zone for the application based on the `config.time_zone` setting, which defaults to "UTC".
+* `active_support.initialize_time_zone` Sets the default time zone for the application based on the `config.time_zone` setting, which defaults to "UTC".
-*`action_dispatch.configure`* Configures the `ActionDispatch::Http::URL.tld_length` to be set to the value of `config.action_dispatch.tld_length`.
+* `action_dispatch.configure` Configures the `ActionDispatch::Http::URL.tld_length` to be set to the value of `config.action_dispatch.tld_length`.
-*`action_view.cache_asset_ids`* Sets `ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids` to `false` when Active Support loads, but only if `config.cache_classes` is too.
+* `action_view.cache_asset_ids` Sets `ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids` to `false` when Active Support loads, but only if `config.cache_classes` is too.
-*`action_view.javascript_expansions`* Registers the expansions set up by `config.action_view.javascript_expansions` and `config.action_view.stylesheet_expansions` to be recognized by Action View and therefore usable in the views.
+* `action_view.javascript_expansions` Registers the expansions set up by `config.action_view.javascript_expansions` and `config.action_view.stylesheet_expansions` to be recognized by Action View and therefore usable in the views.
-*`action_view.set_configs`* Sets up Action View by using the settings in `config.action_view` by `send`'ing the method names as setters to `ActionView::Base` and passing the values through.
+* `action_view.set_configs` Sets up Action View by using the settings in `config.action_view` by `send`'ing the method names as setters to `ActionView::Base` and passing the values through.
-*`action_controller.logger`* Sets `ActionController::Base.logger` -- if it's not already set -- to `Rails.logger`.
+* `action_controller.logger` Sets `ActionController::Base.logger` -- if it's not already set -- to `Rails.logger`.
-*`action_controller.initialize_framework_caches`* Sets `ActionController::Base.cache_store` -- if it's not already set -- to `Rails.cache`.
+* `action_controller.initialize_framework_caches` Sets `ActionController::Base.cache_store` -- if it's not already set -- to `Rails.cache`.
-*`action_controller.set_configs`* Sets up Action Controller by using the settings in `config.action_controller` by `send`'ing the method names as setters to `ActionController::Base` and passing the values through.
+* `action_controller.set_configs` Sets up Action Controller by using the settings in `config.action_controller` by `send`'ing the method names as setters to `ActionController::Base` and passing the values through.
-*`action_controller.compile_config_methods`* Initializes methods for the config settings specified so that they are quicker to access.
+* `action_controller.compile_config_methods` Initializes methods for the config settings specified so that they are quicker to access.
-*`active_record.initialize_timezone`* Sets `ActiveRecord::Base.time_zone_aware_attributes` to true, as well as setting `ActiveRecord::Base.default_timezone` to UTC. When attributes are read from the database, they will be converted into the time zone specified by `Time.zone`.
+* `active_record.initialize_timezone` Sets `ActiveRecord::Base.time_zone_aware_attributes` to true, as well as setting `ActiveRecord::Base.default_timezone` to UTC. When attributes are read from the database, they will be converted into the time zone specified by `Time.zone`.
-*`active_record.logger`* Sets `ActiveRecord::Base.logger` -- if it's not already set -- to `Rails.logger`.
+* `active_record.logger` Sets `ActiveRecord::Base.logger` -- if it's not already set -- to `Rails.logger`.
-*`active_record.set_configs`* Sets up Active Record by using the settings in `config.active_record` by `send`'ing the method names as setters to `ActiveRecord::Base` and passing the values through.
+* `active_record.set_configs` Sets up Active Record by using the settings in `config.active_record` by `send`'ing the method names as setters to `ActiveRecord::Base` and passing the values through.
-*`active_record.initialize_database`* Loads the database configuration (by default) from `config/database.yml` and establishes a connection for the current environment.
+* `active_record.initialize_database` Loads the database configuration (by default) from `config/database.yml` and establishes a connection for the current environment.
-*`active_record.log_runtime`* Includes `ActiveRecord::Railties::ControllerRuntime` which is responsible for reporting the time taken by Active Record calls for the request back to the logger.
+* `active_record.log_runtime` Includes `ActiveRecord::Railties::ControllerRuntime` which is responsible for reporting the time taken by Active Record calls for the request back to the logger.
-*`active_record.set_dispatch_hooks`* Resets all reloadable connections to the database if `config.cache_classes` is set to `false`.
+* `active_record.set_dispatch_hooks` Resets all reloadable connections to the database if `config.cache_classes` is set to `false`.
-*`action_mailer.logger`* Sets `ActionMailer::Base.logger` -- if it's not already set -- to `Rails.logger`.
+* `action_mailer.logger` Sets `ActionMailer::Base.logger` -- if it's not already set -- to `Rails.logger`.
-*`action_mailer.set_configs`* Sets up Action Mailer by using the settings in `config.action_mailer` by `send`'ing the method names as setters to `ActionMailer::Base` and passing the values through.
+* `action_mailer.set_configs` Sets up Action Mailer by using the settings in `config.action_mailer` by `send`'ing the method names as setters to `ActionMailer::Base` and passing the values through.
-*`action_mailer.compile_config_methods`* Initializes methods for the config settings specified so that they are quicker to access.
+* `action_mailer.compile_config_methods` Initializes methods for the config settings specified so that they are quicker to access.
-*`set_load_path`* This initializer runs before `bootstrap_hook`. Adds the `vendor`, `lib`, all directories of `app` and any paths specified by `config.load_paths` to `$LOAD_PATH`.
+* `set_load_path` This initializer runs before `bootstrap_hook`. Adds the `vendor`, `lib`, all directories of `app` and any paths specified by `config.load_paths` to `$LOAD_PATH`.
-*`set_autoload_paths`* This initializer runs before `bootstrap_hook`. Adds all sub-directories of `app` and paths specified by `config.autoload_paths` to `ActiveSupport::Dependencies.autoload_paths`.
+* `set_autoload_paths` This initializer runs before `bootstrap_hook`. Adds all sub-directories of `app` and paths specified by `config.autoload_paths` to `ActiveSupport::Dependencies.autoload_paths`.
-*`add_routing_paths`* Loads (by default) all `config/routes.rb` files (in the application and railties, including engines) and sets up the routes for the application.
+* `add_routing_paths` Loads (by default) all `config/routes.rb` files (in the application and railties, including engines) and sets up the routes for the application.
-*`add_locales`* Adds the files in `config/locales` (from the application, railties and engines) to `I18n.load_path`, making available the translations in these files.
+* `add_locales` Adds the files in `config/locales` (from the application, railties and engines) to `I18n.load_path`, making available the translations in these files.
-*`add_view_paths`* Adds the directory `app/views` from the application, railties and engines to the lookup path for view files for the application.
+* `add_view_paths` Adds the directory `app/views` from the application, railties and engines to the lookup path for view files for the application.
-*`load_environment_config`* Loads the `config/environments` file for the current environment.
+* `load_environment_config` Loads the `config/environments` file for the current environment.
-*`append_asset_paths`* Finds asset paths for the application and all attached railties and keeps a track of the available directories in `config.static_asset_paths`.
+* `append_asset_paths` Finds asset paths for the application and all attached railties and keeps a track of the available directories in `config.static_asset_paths`.
-*`prepend_helpers_path`* Adds the directory `app/helpers` from the application, railties and engines to the lookup path for helpers for the application.
+* `prepend_helpers_path` Adds the directory `app/helpers` from the application, railties and engines to the lookup path for helpers for the application.
-*`load_config_initializers`* Loads all Ruby files from `config/initializers` in the application, railties and engines. The files in this directory can be used to hold configuration settings that should be made after all of the frameworks are loaded.
+* `load_config_initializers` Loads all Ruby files from `config/initializers` in the application, railties and engines. The files in this directory can be used to hold configuration settings that should be made after all of the frameworks are loaded.
-*`engines_blank_point`* Provides a point-in-initialization to hook into if you wish to do anything before engines are loaded. After this point, all railtie and engine initializers are run.
+* `engines_blank_point` Provides a point-in-initialization to hook into if you wish to do anything before engines are loaded. After this point, all railtie and engine initializers are run.
-*`add_generator_templates`* Finds templates for generators at `lib/templates` for the application, railities and engines and adds these to the `config.generators.templates` setting, which will make the templates available for all generators to reference.
+* `add_generator_templates` Finds templates for generators at `lib/templates` for the application, railities and engines and adds these to the `config.generators.templates` setting, which will make the templates available for all generators to reference.
-*`ensure_autoload_once_paths_as_subset`* Ensures that the `config.autoload_once_paths` only contains paths from `config.autoload_paths`. If it contains extra paths, then an exception will be raised.
+* `ensure_autoload_once_paths_as_subset` Ensures that the `config.autoload_once_paths` only contains paths from `config.autoload_paths`. If it contains extra paths, then an exception will be raised.
-*`add_to_prepare_blocks`* The block for every `config.to_prepare` call in the application, a railtie or engine is added to the `to_prepare` callbacks for Action Dispatch which will be ran per request in development, or before the first request in production.
+* `add_to_prepare_blocks` The block for every `config.to_prepare` call in the application, a railtie or engine is added to the `to_prepare` callbacks for Action Dispatch which will be ran per request in development, or before the first request in production.
-*`add_builtin_route`* If the application is running under the development environment then this will append the route for `rails/info/properties` to the application routes. This route provides the detailed information such as Rails and Ruby version for `public/index.html` in a default Rails application.
+* `add_builtin_route` If the application is running under the development environment then this will append the route for `rails/info/properties` to the application routes. This route provides the detailed information such as Rails and Ruby version for `public/index.html` in a default Rails application.
-*`build_middleware_stack`* Builds the middleware stack for the application, returning an object which has a `call` method which takes a Rack environment object for the request.
+* `build_middleware_stack` Builds the middleware stack for the application, returning an object which has a `call` method which takes a Rack environment object for the request.
-*`eager_load!`* If `config.eager_load` is true, runs the `config.before_eager_load` hooks and then calls `eager_load!` which will load all `config.eager_load_namespaces`.
+* `eager_load!` If `config.eager_load` is true, runs the `config.before_eager_load` hooks and then calls `eager_load!` which will load all `config.eager_load_namespaces`.
-*`finisher_hook`* Provides a hook for after the initialization of process of the application is complete, as well as running all the `config.after_initialize` blocks for the application, railties and engines.
+* `finisher_hook` Provides a hook for after the initialization of process of the application is complete, as well as running all the `config.after_initialize` blocks for the application, railties and engines.
-*`set_routes_reloader`* Configures Action Dispatch to reload the routes file using `ActionDispatch::Callbacks.to_prepare`.
+* `set_routes_reloader` Configures Action Dispatch to reload the routes file using `ActionDispatch::Callbacks.to_prepare`.
-*`disable_dependency_loading`* Disables the automatic dependency loading if the `config.eager_load` is set to true.
+* `disable_dependency_loading` Disables the automatic dependency loading if the `config.eager_load` is set to true.
Database pooling
----------------
diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md
index 7730d2b62d..f74f744611 100644
--- a/guides/source/contributing_to_ruby_on_rails.md
+++ b/guides/source/contributing_to_ruby_on_rails.md
@@ -364,7 +364,7 @@ Rails follows a simple set of coding style conventions.
* Two spaces, no tabs (for indentation).
* No trailing whitespace. Blank lines should not have any spaces.
* Indent after private/protected.
-* Prefer `&&`/`||` over `and`/`or`.
+* Prefer `&&`/`||` over `and`/`or`.
* Prefer class << self over self.method for class methods.
* Use `MyClass.my_method(my_arg)` not `my_method( my_arg )` or `my_method my_arg`.
* Use a = b and not a=b.
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index a2e7a9ed97..10257e55bc 100644
--- a/guides/source/debugging_rails_applications.md
+++ b/guides/source/debugging_rails_applications.md
@@ -21,9 +21,9 @@ One common task is to inspect the contents of a variable. In Rails, you can do t
### `debug`
-The `debug` helper will return a <pre>-tag that renders the object using the YAML format. This will generate human-readable data from any object. For example, if you have this code in a view:
+The `debug` helper will return a \
-tag that renders the object using the YAML format. This will generate human-readable data from any object. For example, if you have this code in a view:
-```html
+```html+erb
<%= debug @post %>
Title:
@@ -52,7 +52,7 @@ Title: Rails debugging guide
Displaying an instance variable, or any other object or method, in YAML format can be achieved this way:
-```html
+```html+erb
<%= simple_format @post.to_yaml %>
Title:
@@ -82,7 +82,7 @@ Title: Rails debugging guide
Another useful method for displaying object values is `inspect`, especially when working with arrays or hashes. This will print the object value as a string. For example:
-```html
+```html+erb
<%= [1, 2, 3, 4, 5].inspect %>
Title:
@@ -174,7 +174,7 @@ end
Here's an example of the log generated by this method:
-```bash
+```
Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
@@ -235,7 +235,7 @@ end
If you see the message in the console or logs:
-```bash
+```
***** Debugger requested, but was not available: Start server with --debugger to enable *****
```
@@ -266,7 +266,7 @@ For example:
Now it's time to explore and dig into your application. A good place to start is by asking the debugger for help... so type: `help` (You didn't see that coming, right?)
-```bash
+```
(rdb:7) help
ruby-debug help v0.10.2
Type 'help ' for help on a specific command
@@ -279,13 +279,13 @@ condition down finish list ps save thread var
continue edit frame method putl set tmate where
```
-TIP: To view the help menu for any command use `help <command-name>` in active debug mode. For example: _`help var`_
+TIP: To view the help menu for any command use `help ` in active debug mode. For example: _`help var`_
The next command to learn is one of the most useful: `list`. You can abbreviate any debugging command by supplying just enough letters to distinguish them from other commands, so you can also use `l` for the `list` command.
This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by `=>`.
-```bash
+```
(rdb:7) list
[1, 10] in /PathToProject/posts_controller.rb
1 class PostsController < ApplicationController
@@ -302,7 +302,7 @@ This command shows you where you are in the code by printing 10 lines centered a
If you repeat the `list` command, this time using just `l`, the next ten lines of the file will be printed out.
-```bash
+```
(rdb:7) l
[11, 20] in /PathTo/project/app/controllers/posts_controller.rb
11 end
@@ -321,7 +321,7 @@ And so on until the end of the current file. When the end of file is reached, th
On the other hand, to see the previous ten lines you should type `list-` (or `l-`)
-```bash
+```
(rdb:7) l-
[1, 10] in /PathToProject/posts_controller.rb
1 class PostsController < ApplicationController
@@ -339,7 +339,7 @@ On the other hand, to see the previous ten lines you should type `list-` (or `l-
This way you can move inside the file, being able to see the code above and over the line you added the `debugger`.
Finally, to see where you are in the code again you can type `list=`
-```bash
+```
(rdb:7) list=
[1, 10] in /PathToProject/posts_controller.rb
1 class PostsController < ApplicationController
@@ -362,7 +362,7 @@ The debugger creates a context when a stopping point or an event is reached. The
At any time you can call the `backtrace` command (or its alias `where`) to print the backtrace of the application. This can be very helpful to know how you got where you are. If you ever wondered about how you got somewhere in your code, then `backtrace` will supply the answer.
-```bash
+```
(rdb:5) where
#0 PostsController.index
at line /PathTo/project/app/controllers/posts_controller.rb:6
@@ -377,7 +377,7 @@ At any time you can call the `backtrace` command (or its alias `where`) to print
You move anywhere you want in this trace (thus changing the context) by using the `frame _n_` command, where _n_ is the specified frame number.
-```bash
+```
(rdb:5) frame 2
#2 ActionController::Base.perform_action_without_filters
at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
@@ -405,7 +405,7 @@ Any expression can be evaluated in the current context. To evaluate an expressio
This example shows how you can print the instance_variables defined within the current context:
-```bash
+```
@posts = Post.all
(rdb:11) instance_variables
["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"]
@@ -413,7 +413,7 @@ This example shows how you can print the instance_variables defined within the c
As you may have figured out, all of the variables that you can access from a controller are displayed. This list is dynamically updated as you execute code. For example, run the next line using `next` (you'll learn more about this command later in this guide).
-```bash
+```
(rdb:11) next
Processing PostsController#index (for 127.0.0.1 at 2008-09-04 19:51:34) [GET]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--b16e91b992453a8cc201694d660147bba8b0fd0e
@@ -424,7 +424,7 @@ respond_to do |format|
And then ask again for the instance_variables:
-```bash
+```
(rdb:11) instance_variables.include? "@posts"
true
```
@@ -435,7 +435,7 @@ TIP: You can also step into *irb* mode with the command `irb` (of course!). This
The `var` method is the most convenient way to show variables and their values:
-```bash
+```
var
(rdb:1) v[ar] const