Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fix remaining formatting problems in the guide

  • Loading branch information...
commit 721afdcc4b58c65f36122b10ec998b913a147912 1 parent 5a4622b
Prem Sichanugrist sikachu authored sikachu committed
Showing with 956 additions and 922 deletions.
  1. +5 −5 guides/source/action_controller_overview.md
  2. +36 −34 guides/source/action_mailer_basics.md
  3. +25 −25 guides/source/action_view_overview.md
  4. +1 −1  guides/source/active_model_basics.md
  5. +23 −26 guides/source/active_record_querying.md
  6. +15 −15 guides/source/active_record_validations_callbacks.md
  7. +13 −14 guides/source/active_support_core_extensions.md
  8. +5 −5 guides/source/active_support_instrumentation.md
  9. +76 −73 guides/source/ajax_on_rails.md
  10. +9 −8 guides/source/api_documentation_guidelines.md
  11. +43 −50 guides/source/asset_pipeline.md
  12. +120 −120 guides/source/association_basics.md
  13. +4 −4 guides/source/caching_with_rails.md
  14. +1 −1  guides/source/command_line.md
  15. +133 −123 guides/source/configuring.md
  16. +1 −1  guides/source/contributing_to_ruby_on_rails.md
  17. +33 −33 guides/source/debugging_rails_applications.md
  18. +12 −12 guides/source/engines.md
  19. +22 −22 guides/source/form_helpers.md
  20. +39 −44 guides/source/getting_started.md
  21. +42 −32 guides/source/i18n.md
  22. +3 −3 guides/source/initialization.md
  23. +107 −107 guides/source/layouts_and_rendering.md
  24. +5 −5 guides/source/migrations.md
  25. +1 −1  guides/source/performance_testing.md
  26. +35 −35 guides/source/plugins.md
  27. +13 −13 guides/source/rails_application_templates.md
  28. +45 −23 guides/source/rails_on_rack.md
  29. +10 −9 guides/source/routing.md
  30. +79 −78 guides/source/security.md
10 guides/source/action_controller_overview.md
View
@@ -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
<html>
<!-- <head/> -->
<body>
@@ -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] %>
<p class="welcome">Welcome to our site!</p>
<% 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 %>
70 guides/source/action_mailer_basics.md
View
@@ -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
<!DOCTYPE html>
<html>
<head>
@@ -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
-<p>Hello there, this is our image</p>
+ ```html+erb
+ <p>Hello there, this is our image</p>
-<%= 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
-<p>Hello there, this is our image</p>
+ ```html+erb
+ <p>Hello there, this is our image</p>
-<%= 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 &lt;email&gt;"`.
+to format the email address in the format `"Name <email>"`.
```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:<ul><li>`:address` - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li>`:port` - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li>`:domain` - If you need to specify a HELO domain, you can do it here.</li><li>`:user_name` - If your mail server requires authentication, set the username in this setting.</li><li>`:password` - If your mail server requires authentication, set the password in this setting.</li><li>`: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`.</li><li>`:enable_starttls_auto` - Set this to `false` if there is a problem with your server certificate that you cannot resolve.</li></ul>|
50 guides/source/action_view_overview.md
View
@@ -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
<b>Names of all the people</b>
<% @people.each do |person| %>
Name: <%= person.name %><br/>
@@ -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" %>
<h1>Products</h1>
@@ -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
<div class='box'>
<%= yield %>
</div>
@@ -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 %>
<p><%= post.body %></p>
<% 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 %>
<p><%= post.body %></p>
@@ -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 %>
<td><%= @post.title %></td>
<% 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 %>
<td><%= @post.title %></td>
<% 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| %>
<td><%= post.title %></td>
<% 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 %>
<td><%= @post.title %></td>
<% 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 %>
<p>Welcome! The date and time is <%= Time.now %></p>
<% 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
<html>
<head>
<title>Welcome!</title>
@@ -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
<html>
<head>
<title>Welcome!</title>
@@ -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
<p>This is a special page.</p>
<% 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 %><br />
@@ -1360,7 +1360,7 @@ check_box_tag 'accept'
Creates a field set for grouping HTML form elements.
-```ruby
+```html+erb
<%= field_set_tag do %>
<p><%= text_field_tag 'name' %></p>
<% 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 %>
<label for="file">File to Upload</label> <%= 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 %>
<div><%= submit_tag 'Save' %></div>
<% end %>
2  guides/source/active_model_basics.md
View
@@ -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
49 guides/source/active_record_querying.md
View
@@ -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 <strong>all</strong> 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).
-<br />
-
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: <attribute>
```
-Where `&lt;attribute&gt;` 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 `<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.
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.
-<strong>Optimistic locking column</strong>
+**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.
-<strong>N <plus> 1 queries problem</strong>
+**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 ) <plus> 10 ( one per each client to load the address ) = <strong>11</strong> 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.
-<strong>Solution to N <plus> 1 queries problem</strong>
+**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 <strong>2</strong> queries, as opposed to <strong>11</strong> 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
-<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------------<plus>
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
-<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------------<plus>
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
| 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
-<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------------<plus>
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
2 rows in set (0.00 sec)
```
@@ -1571,19 +1568,19 @@ yields
```
EXPLAIN for: SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
-<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------<plus>
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
-<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------<plus>
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
-<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------<plus>
++----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
1 row in set (0.00 sec)
EXPLAIN for: SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1)
-<plus>----<plus>-------------<plus>-------<plus>------<plus>---------------<plus>------<plus>---------<plus>------<plus>------<plus>-------------<plus>
++----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
-<plus>----<plus>-------------<plus>-------<plus>------<plus>---------------<plus>------<plus>---------<plus>------<plus>------<plus>-------------<plus>
++----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
-<plus>----<plus>-------------<plus>-------<plus>------<plus>---------------<plus>------<plus>---------<plus>------<plus>------<plus>-------------<plus>
++----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1 row in set (0.00 sec)
```
30 guides/source/active_record_validations_callbacks.md
View
@@ -119,28 +119,28 @@ class Person < ActiveRecord::Base
end
>> p = Person.new
-=> #<Person id: nil, name: nil>
+#=> #<Person id: nil, name: nil>
>> p.errors
-=> {}
+#=> {}
>> p.valid?
-=> false
+#=> false
>> p.errors
-=> {:name=>["can't be blank"]}
+#=> {:name=>["can't be blank"]}
>> p = Person.create
-=> #<Person id: nil, name: nil>
+#=> #<Person id: nil, name: nil>
>> 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[<plus>-]?\d<plus>\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]<plus>)@((?:[-a-z0-9]<plus>\.)+[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`
27 guides/source/active_support_core_extensions.md
View
@@ -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<plus>%26<plus>Johnson"
+# => "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 `&lt;` 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 "&amp;amp;". 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 "&amp;amp;". 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 <plus> 2.hours <plus> 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| %>
<tr>
<td><%=h a %></td>
@@ -3585,7 +3584,7 @@ They are analogous. Please refer to their documentation above and take into acco
Time.zone_default
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
-# In Barcelona, 2010/03/28 02:00 <plus>0100 becomes 2010/03/28 03:00 <plus>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 <plus>00:00..Mon, 09 Aug 2010 23:59:59 UTC <plus>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 <plus>00:00..Sun, 15 Aug 2010 23:59:59 UTC <plus>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 <plus>00:00..Tue, 31 Aug 2010 23:59:59 UTC <plus>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 <plus>00:00..Thu, 30 Sep 2010 23:59:59 UTC <plus>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 <plus>00:00..Fri, 31 Dec 2010 23:59:59 UTC <plus>00:00
+# => Fri, 01 Jan 2010 00:00:00 UTC +00:00..Fri, 31 Dec 2010 23:59:59 UTC +00:00
```
### Time Constructors
10 guides/source/active_support_instrumentation.md
View
@@ -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|
149 guides/source/ajax_on_rails.md
View
@@ -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 &lt;li&gt; element into an existing list:
+ A typical example of using `:bottom` is inserting a new \<li> 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` =&gt; `code` Evaluates `code` (which should evaluate to a boolean) and proceeds if it's true, cancels the request otherwise.
-*** `:before` =&gt; `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` =&gt; `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` =&gt; `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` &gt; `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=' <plus> 'encodeURIComponent($('status').value) <plus> '&completed=' <plus> $('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:` =&gt; `code` The request is in the process of receiving the data, but the transfer is not completed yet.
-*** `:loaded:` =&gt; `code` The transfer is completed, but the data is not processed and returned yet
-*** `:interactive:` =&gt; `code` One step after `:loaded`: The data is fully received and being processed
-*** `:success:` =&gt; `code` The data is fully received, parsed and the server responded with "200 OK"
-*** `:failure:` =&gt; `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:` =&gt; `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` =&gt; `code` Evaluates `code` (which should evaluate to a boolean) and proceeds if it's true, cancels the request otherwise.
+ * `:before` =&gt; `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` =&gt; `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` =&gt; `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` &gt; `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:` =&gt; `code` The request is in the process of receiving the data, but the transfer is not completed yet.
+ * `:loaded:` =&gt; `code` The transfer is completed, but the data is not processed and returned yet
+ * `:interactive:` =&gt; `code` One step after `:loaded`: The data is fully received and being processed
+ * `:success:` =&gt; `code` The data is fully received, parsed and the server responded with "200 OK"
+ * `:failure:` =&gt; `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:` =&gt; `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.
17 guides/source/api_documentation_guidelines.md
View
@@ -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 `&#43;...&#43;` for fixed-width font only works with *words*; that is: anything matching `\A\w&#43;\z`. For anything else use `&lt;tt&gt;...&lt;/tt&gt;`, 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 `<tt>...</tt>`, 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 <tt>:create</tt> if
+# <tt>new_record?</tt> is true, and to <tt>:update</tt> 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 <tt>:on</tt> option will run no matter the context. Validations with
+# some <tt>:on</tt> 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`.
+# * <tt>:allow_nil</tt> - Skip validation if attribute is `nil`.
```
The description starts in upper case and ends with a full stop—it's standard English.
93 guides/source/asset_pipeline.md
View
@@ -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:
-<ol>
- <li>
- <strong>Not all caches will reliably cache content where the filename only differs by query parameters</strong>.<br />
+1. **Not all caches will reliably cache content where the filename only differs by query parameters**<br />
[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.
- </li>
- <li>
- <strong>The file name can change between nodes in multi-server environments.</strong><br />
+
+2. **The file name can change between nodes in multi-server environments.**<br />
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.
- </li>
- <li>
- <strong>Too much cache invalidation</strong><br />
+3. **Too much cache invalidation**<br />
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.
- </li>
-</ol>
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.
<LocationMatch "^/assets/.*$">
# 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
240 guides/source/association_basics.md
View
@@ -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 `&lt;` 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:
-* `<em>association</em>(force_reload = false)`
-* `<em>association</em>=(associate)`
-* `build_<em>association</em>(attributes = {})`
-* `create_<em>association</em>(attributes = {})`
+* `association(force_reload = false)`
+* `association=(associate)`
+* `build_association(attributes = {})`
+* `create_association(attributes = {})`
-In all of these methods, `<em>association</em>` 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.
-##### `<em>association</em>(force_reload = false)`
+##### `association(force_reload = false)`
-The `<em>association</em>` 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 `<em>association</em>` 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 `<em>association</em>=` 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_<em>association</em>(attributes = {})`
+##### `build_association(attributes = {})`
-The `build_<em>association</em>` 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_<em>association</em>(attributes = {})`
+##### `create_association(attributes = {})`
-The `create_<em>association</em>` 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 `<em>association</em>.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:
-* `<em>association</em>(force_reload = false)`
-* `<em>association</em>=(associate)`
-* `build_<em>association</em>(attributes = {})`
-* `create_<em>association</em>(attributes = {})`
+* `association(force_reload = false)`
+* `association=(associate)`
+* `build_association(attributes = {})`
+* `create_association(attributes = {})`
-In all of these methods, `<em>association</em>` 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.
-##### `<em>association</em>(force_reload = false)`
+##### `association(force_reload = false)`
-The `<em>association</em>` 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 `<em>association</em>` 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.
-##### `<em>association</em>=(associate)`
+##### `association=(associate)`
-The `<em>association</em>=` 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_<em>association</em>(attributes = {})`
+##### `build_association(attributes = {})`
-The `build_<em>association</em>` 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_<em>association</em>(attributes = {})`
+##### `create_association(attributes = {})`
-The `create_<em>association</em>` 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 `<em>association</em>.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 `<em>association</em>.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:
-* `<em>collection</em>(force_reload = false)`
-* `<em>collection</em><<(object, ...)`
-* `<em>collection</em>.delete(object, ...)`
-* `<em>collection</em>=objects`
-* `<em>collection_singular</em>_ids`
-* `<em>collection_singular</em>_ids=ids`
-* `<em>collection</em>.clear`
-* `<em>collection</em>.empty?`
-* `<em>collection</em>.size`
-* `<em>collection</em>.find(...)`
-* `<em>collection</em>.where(...)`
-* `<em>collection</em>.exists?(...)`
-* `<em>collection</em>.build(attributes = {}, ...)`
-* `<em>collection</em>.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, `<em>collection</em>` is replaced with the symbol passed as the first argument to `has_many`, and `<em>collection_singular</em>` 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 = {})
```
-##### `<em>collection</em>(force_reload = false)`
+##### `collection(force_reload = false)`
-The `<em>collection</em>` 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
```
-##### `<em>collection</em><<(object, ...)`
+##### `collection<<(object, ...)`
-The `<em>collection</em><<` 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
```
-##### `<em>collection</em>.delete(object, ...)`
+##### `collection.delete(object, ...)`
-The `<em>collection</em>.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 `<em>collection</em>.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`.
-##### `<em>collection</em>=objects`
+##### `collection=objects`
-The `<em>collection</em>=` 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.
-##### `<em>collection_singular</em>_ids`
+##### `collection_singular_ids`
-The `<em>collection_singular</em>_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
```
-##### `<em>collection_singular</em>_ids=ids`
+##### `collection_singular_ids=ids`
-The `<em>collection_singular</em>_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.
-##### `<em>collection</em>.clear`
+##### `collection.clear`
-The `<em>collection</em>.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`.
-##### `<em>collection</em>.empty?`
+##### `collection.empty?`
-The `<em>collection</em>.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 %>
```
-##### `<em>collection</em>.size`
+##### `collection.size`
-The `<em>collection</em>.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
```
-##### `<em>collection</em>.find(...)`
+##### `collection.find(...)`
-The `<em>collection</em>.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)
```
-##### `<em>collection</em>.where(...)`
+##### `collection.where(...)`
-The `<em>collection</em>.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
```
-##### `<em>collection</em>.exists?(...)`
+##### `collection.exists?(...)`
-The `<em>collection</em>.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?`.
-##### `<em>collection</em>.build(attributes = {}, ...)`
+##### `collection.build(attributes = {}, ...)`
-The `<em>collection</em>.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")
```
-##### `<em>collection</em>.create(attributes = {})`
+##### `collection.create(attributes = {})`
-The `<em>collection</em>.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 `<em>collection</em>.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:
-* `<em>collection</em>(force_reload = false)`
-* `<em>collection</em><<(object, ...)`
-* `<em>collection</em>.delete(object, ...)`
-* `<em>collection</em>=objects`
-* `<em>collection_singular</em>_ids`
-* `<em>collection_singular</em>_ids=ids`
-* `<em>collection</em>.clear`
-* `<em>collection</em>.empty?`
-* `<em>collection</em>.size`
-* `<em>collection</em>.find(...)`
-* `<em>collection</em>.where(...)`
-* `<em>collection</em>.exists?(...)`
-* `<em>collection</em>.build(attributes = {})`
-* `<em>collection</em>.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, `<em>collection</em>` is replaced with the symbol passed as the first argument to `has_and_belongs_to_many`, and `<em>collection_singular</em>` 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`.
-##### `<em>collection</em>(force_reload = false)`
+##### `collection(force_reload = false)`
-The `<em>collection</em>` 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
```
-##### `<em>collection</em><<(object, ...)`
+##### `collection<<(object, ...)`
-The `<em>collection</em><<` 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 `<em>collection</em>.concat` and `<em>collection</em>.push`.
+NOTE: This method is aliased as `collection.concat` and `collection.push`.
-##### `<em>collection</em>.delete(object, ...)`
+##### `collection.delete(object, ...)`
-The `<em>collection</em>.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)
```
-##### `<em>collection</em>=objects`
+##### `collection=objects`
-The `<em>collection</em>=` 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.
-##### `<em>collection_singular</em>_ids`
+##### `collection_singular_ids`
-The `<em>collection_singular</em>_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
```
-##### `<em>collection_singular</em>_ids=ids`
+##### `collection_singular_ids=ids`
-The `<em>collection_singular</em>_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.
-##### `<em>collection</em>.clear`
+##### `collection.clear`
-The `<em>collection</em>.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.
-##### `<em>collection</em>.empty?`
+##### `collection.empty?`
-The `<em>collection</em>.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 `<em>collection</em>.empty?` method returns `true` if the collection does no
<% end %>
```
-##### `<em>collection</em>.size`
+##### `collection.size`
-The `<em>collection</em>.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
```
-##### `<em>collection</em>.find(...)`
+##### `collection.find(...)`
-The `<em>collection</em>.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)
```
-##### `<em>collection</em>.where(...)`
+##### `collection.where(...)`
-The `<em>collection</em>.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)
```
-##### `<em>collection</em>.exists?(...)`
+##### `collection.exists?(...)`
-The `<em>collection</em>.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?`.
-##### `<em>collection</em>.build(attributes = {})`
+##### `collection.build(attributes = {})`
-The `<em>collection</em>.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"})
```
-##### `<em>collection</em>.create(attributes = {})`
+##### `collection.create(attributes = {})`
-The `<em>collection</em>.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 `<em>collection</em>.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
8 guides/source/caching_with_rails.md
View
@@ -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 %>
2  guides/source/command_line.md
View
@@ -176,7 +176,7 @@ end
Then the view, to display our message (in `app/views/greetings/hello.html.erb`):
-```html
+```erb
<h1>A Greeting for You!</h1>
<p><%= @message %></p>
```
256 guides/source/configuring.md
View
@@ -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!`.