rails 4.0.0 → 4.2.11.3
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +5 -5
- data/README.md +30 -23
- data/guides/CHANGELOG.md +108 -6
- data/guides/Rakefile +21 -6
- data/guides/assets/images/akshaysurve.jpg +0 -0
- data/guides/assets/images/edge_badge.png +0 -0
- data/guides/assets/images/feature_tile.gif +0 -0
- data/guides/assets/images/footer_tile.gif +0 -0
- data/guides/assets/images/fxn.png +0 -0
- data/guides/assets/images/getting_started/article_with_comments.png +0 -0
- data/guides/assets/images/getting_started/challenge.png +0 -0
- data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
- data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
- data/guides/assets/images/getting_started/form_with_errors.png +0 -0
- data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
- data/guides/assets/images/getting_started/new_article.png +0 -0
- data/guides/assets/images/getting_started/rails_welcome.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
- data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
- data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
- data/guides/assets/images/header_tile.gif +0 -0
- data/guides/assets/images/icons/README +1 -1
- data/guides/assets/images/icons/callouts/11.png +0 -0
- data/guides/assets/images/icons/callouts/12.png +0 -0
- data/guides/assets/images/icons/callouts/13.png +0 -0
- data/guides/assets/images/icons/callouts/15.png +0 -0
- data/guides/assets/images/icons/caution.png +0 -0
- data/guides/assets/images/icons/example.png +0 -0
- data/guides/assets/images/radar.png +0 -0
- data/guides/assets/images/rails4_features.png +0 -0
- data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
- data/guides/assets/images/vijaydev.jpg +0 -0
- data/guides/assets/javascripts/guides.js +36 -34
- data/guides/assets/stylesheets/main.css +6 -2
- data/guides/assets/stylesheets/print.css +1 -1
- data/guides/bug_report_templates/action_controller_gem.rb +47 -0
- data/guides/bug_report_templates/action_controller_master.rb +54 -0
- data/guides/bug_report_templates/active_record_gem.rb +5 -2
- data/guides/bug_report_templates/active_record_master.rb +3 -2
- data/guides/bug_report_templates/generic_gem.rb +15 -0
- data/guides/bug_report_templates/generic_master.rb +26 -0
- data/guides/rails_guides.rb +23 -4
- data/guides/rails_guides/generator.rb +1 -1
- data/guides/rails_guides/helpers.rb +4 -2
- data/guides/rails_guides/levenshtein.rb +27 -21
- data/guides/rails_guides/markdown.rb +11 -7
- data/guides/rails_guides/markdown/renderer.rb +1 -1
- data/guides/source/2_2_release_notes.md +3 -3
- data/guides/source/2_3_release_notes.md +12 -12
- data/guides/source/3_0_release_notes.md +10 -13
- data/guides/source/3_1_release_notes.md +7 -4
- data/guides/source/3_2_release_notes.md +17 -14
- data/guides/source/4_0_release_notes.md +110 -54
- data/guides/source/4_1_release_notes.md +730 -0
- data/guides/source/4_2_release_notes.md +877 -0
- data/guides/source/_license.html.erb +1 -1
- data/guides/source/_welcome.html.erb +6 -2
- data/guides/source/action_controller_overview.md +223 -57
- data/guides/source/action_mailer_basics.md +129 -76
- data/guides/source/action_view_overview.md +247 -246
- data/guides/source/active_job_basics.md +339 -0
- data/guides/source/active_model_basics.md +374 -20
- data/guides/source/active_record_basics.md +46 -45
- data/guides/source/active_record_callbacks.md +83 -28
- data/guides/source/{migrations.md → active_record_migrations.md} +191 -275
- data/guides/source/active_record_postgresql.md +433 -0
- data/guides/source/active_record_querying.md +382 -300
- data/guides/source/active_record_validations.md +64 -55
- data/guides/source/active_support_core_extensions.md +229 -187
- data/guides/source/active_support_instrumentation.md +23 -22
- data/guides/source/api_documentation_guidelines.md +167 -15
- data/guides/source/asset_pipeline.md +768 -294
- data/guides/source/association_basics.md +188 -96
- data/guides/source/autoloading_and_reloading_constants.md +1311 -0
- data/guides/source/caching_with_rails.md +45 -11
- data/guides/source/command_line.md +96 -65
- data/guides/source/configuring.md +404 -70
- data/guides/source/contributing_to_ruby_on_rails.md +270 -130
- data/guides/source/credits.html.erb +7 -3
- data/guides/source/debugging_rails_applications.md +471 -284
- data/guides/source/development_dependencies_install.md +115 -21
- data/guides/source/documents.yaml +31 -9
- data/guides/source/engines.md +737 -291
- data/guides/source/form_helpers.md +137 -89
- data/guides/source/generators.md +60 -28
- data/guides/source/getting_started.md +1007 -596
- data/guides/source/i18n.md +178 -96
- data/guides/source/index.html.erb +2 -1
- data/guides/source/initialization.md +248 -104
- data/guides/source/kindle/toc.html.erb +1 -1
- data/guides/source/layout.html.erb +14 -22
- data/guides/source/layouts_and_rendering.md +78 -46
- data/guides/source/maintenance_policy.md +78 -0
- data/guides/source/nested_model_forms.md +10 -7
- data/guides/source/plugins.md +66 -57
- data/guides/source/rails_application_templates.md +49 -12
- data/guides/source/rails_on_rack.md +50 -60
- data/guides/source/routing.md +190 -139
- data/guides/source/ruby_on_rails_guides_guidelines.md +12 -13
- data/guides/source/security.md +134 -83
- data/guides/source/testing.md +322 -200
- data/guides/source/upgrading_ruby_on_rails.md +834 -37
- data/guides/source/working_with_javascript_in_rails.md +36 -26
- data/guides/w3c_validator.rb +2 -0
- metadata +93 -116
- data/guides/assets/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
- data/guides/assets/images/getting_started/new_post.png +0 -0
- data/guides/assets/images/getting_started/post_with_comments.png +0 -0
- data/guides/assets/images/getting_started/show_action_for_posts.png +0 -0
- data/guides/assets/images/getting_started/template_is_missing_posts_new.png +0 -0
- data/guides/assets/images/getting_started/undefined_method_post_path.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_create_for_posts.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_new_for_posts.png +0 -0
- data/guides/assets/images/jaimeiniesta.jpg +0 -0
- data/guides/code/getting_started/Gemfile +0 -43
- data/guides/code/getting_started/Gemfile.lock +0 -150
- data/guides/code/getting_started/README.rdoc +0 -28
- data/guides/code/getting_started/Rakefile +0 -6
- data/guides/code/getting_started/app/assets/javascripts/application.js +0 -16
- data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
- data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
- data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
- data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -17
- data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -47
- data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
- data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
- data/guides/code/getting_started/app/models/comment.rb +0 -3
- data/guides/code/getting_started/app/models/post.rb +0 -7
- data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
- data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
- data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
- data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
- data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
- data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
- data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -3
- data/guides/code/getting_started/bin/bundle +0 -4
- data/guides/code/getting_started/bin/rails +0 -4
- data/guides/code/getting_started/bin/rake +0 -4
- data/guides/code/getting_started/config.ru +0 -4
- data/guides/code/getting_started/config/application.rb +0 -18
- data/guides/code/getting_started/config/boot.rb +0 -4
- data/guides/code/getting_started/config/database.yml +0 -25
- data/guides/code/getting_started/config/environment.rb +0 -5
- data/guides/code/getting_started/config/environments/development.rb +0 -30
- data/guides/code/getting_started/config/environments/production.rb +0 -80
- data/guides/code/getting_started/config/environments/test.rb +0 -36
- data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
- data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
- data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
- data/guides/code/getting_started/config/initializers/locale.rb +0 -9
- data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
- data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
- data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
- data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
- data/guides/code/getting_started/config/locales/en.yml +0 -23
- data/guides/code/getting_started/config/routes.rb +0 -7
- data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
- data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
- data/guides/code/getting_started/db/schema.rb +0 -33
- data/guides/code/getting_started/db/seeds.rb +0 -7
- data/guides/code/getting_started/public/404.html +0 -58
- data/guides/code/getting_started/public/422.html +0 -58
- data/guides/code/getting_started/public/500.html +0 -57
- data/guides/code/getting_started/public/favicon.ico +0 -0
- data/guides/code/getting_started/public/robots.txt +0 -5
- data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
- data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
- data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
- data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
- data/guides/code/getting_started/test/models/comment_test.rb +0 -7
- data/guides/code/getting_started/test/models/post_test.rb +0 -7
- data/guides/code/getting_started/test/test_helper.rb +0 -15
- data/guides/source/kindle/KINDLE.md +0 -26
@@ -17,7 +17,7 @@ After reading this guide, you will know:
|
|
17
17
|
Introduction to instrumentation
|
18
18
|
-------------------------------
|
19
19
|
|
20
|
-
The instrumentation API provided by Active Support allows developers to provide hooks which other developers may hook into. There are several of these within the Rails framework, as described below in
|
20
|
+
The instrumentation API provided by Active Support allows developers to provide hooks which other developers may hook into. There are several of these within the Rails framework, as described below in (TODO: link to section detailing each hook point). With this API, developers can choose to be notified when certain events occur inside their application or another piece of Ruby code.
|
21
21
|
|
22
22
|
For example, there is a hook provided within Active Record that is called every time Active Record uses an SQL query on a database. This hook could be **subscribed** to, and used to track the number of queries during a certain action. There's another hook around the processing of an action of a controller. This could be used, for instance, to track how long a specific action has taken.
|
23
23
|
|
@@ -39,7 +39,7 @@ Action Controller
|
|
39
39
|
|
40
40
|
```ruby
|
41
41
|
{
|
42
|
-
key: 'posts/1-
|
42
|
+
key: 'posts/1-dashboard-view'
|
43
43
|
}
|
44
44
|
```
|
45
45
|
|
@@ -51,7 +51,7 @@ Action Controller
|
|
51
51
|
|
52
52
|
```ruby
|
53
53
|
{
|
54
|
-
key: 'posts/1-
|
54
|
+
key: 'posts/1-dashboard-view'
|
55
55
|
}
|
56
56
|
```
|
57
57
|
|
@@ -63,7 +63,7 @@ Action Controller
|
|
63
63
|
|
64
64
|
```ruby
|
65
65
|
{
|
66
|
-
key: 'posts/1-
|
66
|
+
key: 'posts/1-dashboard-view'
|
67
67
|
}
|
68
68
|
```
|
69
69
|
|
@@ -75,7 +75,7 @@ Action Controller
|
|
75
75
|
|
76
76
|
```ruby
|
77
77
|
{
|
78
|
-
key: 'posts/1-
|
78
|
+
key: 'posts/1-dashboard-view'
|
79
79
|
}
|
80
80
|
```
|
81
81
|
|
@@ -135,7 +135,9 @@ Action Controller
|
|
135
135
|
| `:format` | html/js/json/xml etc |
|
136
136
|
| `:method` | HTTP request verb |
|
137
137
|
| `:path` | Request path |
|
138
|
+
| `:status` | HTTP status code |
|
138
139
|
| `:view_runtime` | Amount spent in view in ms |
|
140
|
+
| `:db_runtime` | Amount spent executing database queries in ms |
|
139
141
|
|
140
142
|
```ruby
|
141
143
|
{
|
@@ -223,11 +225,11 @@ Active Record
|
|
223
225
|
|
224
226
|
### sql.active_record
|
225
227
|
|
226
|
-
| Key
|
227
|
-
|
|
228
|
-
| `:sql`
|
229
|
-
| `:name`
|
230
|
-
| `:
|
228
|
+
| Key | Value |
|
229
|
+
| ---------------- | --------------------- |
|
230
|
+
| `:sql` | SQL statement |
|
231
|
+
| `:name` | Name of the operation |
|
232
|
+
| `:connection_id` | `self.object_id` |
|
231
233
|
|
232
234
|
INFO. The adapters will add their own data as well.
|
233
235
|
|
@@ -303,17 +305,6 @@ Action Mailer
|
|
303
305
|
}
|
304
306
|
```
|
305
307
|
|
306
|
-
ActiveResource
|
307
|
-
--------------
|
308
|
-
|
309
|
-
### request.active_resource
|
310
|
-
|
311
|
-
| Key | Value |
|
312
|
-
| -------------- | -------------------- |
|
313
|
-
| `:method` | HTTP method |
|
314
|
-
| `:request_uri` | Complete URI |
|
315
|
-
| `:result` | HTTP response object |
|
316
|
-
|
317
308
|
Active Support
|
318
309
|
--------------
|
319
310
|
|
@@ -364,7 +355,7 @@ INFO. Options passed to fetch will be merged with the payload.
|
|
364
355
|
| ------ | --------------------- |
|
365
356
|
| `:key` | Key used in the store |
|
366
357
|
|
367
|
-
INFO. Cache stores
|
358
|
+
INFO. Cache stores may add their own keys
|
368
359
|
|
369
360
|
```ruby
|
370
361
|
{
|
@@ -396,6 +387,15 @@ INFO. Cache stores my add their own keys
|
|
396
387
|
}
|
397
388
|
```
|
398
389
|
|
390
|
+
Railties
|
391
|
+
--------
|
392
|
+
|
393
|
+
### load_config_initializer.railties
|
394
|
+
|
395
|
+
| Key | Value |
|
396
|
+
| -------------- | ----------------------------------------------------- |
|
397
|
+
| `:initializer` | Path to loaded initializer from `config/initializers` |
|
398
|
+
|
399
399
|
Rails
|
400
400
|
-----
|
401
401
|
|
@@ -448,6 +448,7 @@ Most times you only care about the data itself. Here is a shortcut to just get t
|
|
448
448
|
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*args|
|
449
449
|
data = args.extract_options!
|
450
450
|
data # { extra: :information }
|
451
|
+
end
|
451
452
|
```
|
452
453
|
|
453
454
|
You may also subscribe to events matching a regular expression. This enables you to subscribe to
|
@@ -13,7 +13,19 @@ After reading this guide, you will know:
|
|
13
13
|
RDoc
|
14
14
|
----
|
15
15
|
|
16
|
-
The Rails API documentation
|
16
|
+
The [Rails API documentation](http://api.rubyonrails.org) is generated with
|
17
|
+
[RDoc](http://docs.seattlerb.org/rdoc/).
|
18
|
+
|
19
|
+
```bash
|
20
|
+
bundle exec rake rdoc
|
21
|
+
```
|
22
|
+
|
23
|
+
Resulting HTML files can be found in the ./doc/rdoc directory.
|
24
|
+
|
25
|
+
Please consult the RDoc documentation for help with the
|
26
|
+
[markup](http://docs.seattlerb.org/rdoc/RDoc/Markup.html),
|
27
|
+
and also take into account these [additional
|
28
|
+
directives](http://docs.seattlerb.org/rdoc/RDoc/Parser/Ruby.html).
|
17
29
|
|
18
30
|
Wording
|
19
31
|
-------
|
@@ -25,7 +37,7 @@ Write in present tense: "Returns a hash that...", rather than "Returned a hash t
|
|
25
37
|
Start comments in upper case. Follow regular punctuation rules:
|
26
38
|
|
27
39
|
```ruby
|
28
|
-
# Declares an attribute reader backed by an internally-named
|
40
|
+
# Declares an attribute reader backed by an internally-named
|
29
41
|
# instance variable.
|
30
42
|
def attr_internal_reader(*attrs)
|
31
43
|
...
|
@@ -42,10 +54,32 @@ Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERB. Wh
|
|
42
54
|
|
43
55
|
Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database".
|
44
56
|
|
57
|
+
Prefer wordings that avoid "you"s and "your"s. For example, instead of
|
58
|
+
|
59
|
+
```markdown
|
60
|
+
If you need to use `return` statements in your callbacks, it is recommended that you explicitly define them as methods.
|
61
|
+
```
|
62
|
+
|
63
|
+
use this style:
|
64
|
+
|
65
|
+
```markdown
|
66
|
+
If `return` is needed it is recommended to explicitly define a method.
|
67
|
+
```
|
68
|
+
|
69
|
+
That said, when using pronouns in reference to a hypothetical person, such as "a
|
70
|
+
user with a session cookie", gender neutral pronouns (they/their/them) should be
|
71
|
+
used. Instead of:
|
72
|
+
|
73
|
+
* he or she... use they.
|
74
|
+
* him or her... use them.
|
75
|
+
* his or her... use their.
|
76
|
+
* his or hers... use theirs.
|
77
|
+
* himself or herself... use themselves.
|
78
|
+
|
45
79
|
English
|
46
80
|
-------
|
47
81
|
|
48
|
-
Please use American English (
|
82
|
+
Please use American English (*color*, *center*, *modularize*, etc). See [a list of American and British English spelling differences here](http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences).
|
49
83
|
|
50
84
|
Example Code
|
51
85
|
------------
|
@@ -57,7 +91,7 @@ Use two spaces to indent chunks of code--that is, for markup purposes, two space
|
|
57
91
|
Short docs do not need an explicit "Examples" label to introduce snippets; they just follow paragraphs:
|
58
92
|
|
59
93
|
```ruby
|
60
|
-
# Converts a collection of elements into a formatted string by
|
94
|
+
# Converts a collection of elements into a formatted string by
|
61
95
|
# calling +to_s+ on all elements and joining them.
|
62
96
|
#
|
63
97
|
# Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
|
@@ -77,7 +111,7 @@ On the other hand, big chunks of structured documentation may have a separate "E
|
|
77
111
|
The results of expressions follow them and are introduced by "# => ", vertically aligned:
|
78
112
|
|
79
113
|
```ruby
|
80
|
-
# For checking if
|
114
|
+
# For checking if an integer is even or odd.
|
81
115
|
#
|
82
116
|
# 1.even? # => false
|
83
117
|
# 1.odd? # => true
|
@@ -88,14 +122,14 @@ The results of expressions follow them and are introduced by "# => ", vertically
|
|
88
122
|
If a line is too long, the comment may be placed on the next line:
|
89
123
|
|
90
124
|
```ruby
|
91
|
-
# label(:
|
92
|
-
# # => <label for="
|
125
|
+
# label(:article, :title)
|
126
|
+
# # => <label for="article_title">Title</label>
|
93
127
|
#
|
94
|
-
# label(:
|
95
|
-
# # => <label for="
|
128
|
+
# label(:article, :title, "A short title")
|
129
|
+
# # => <label for="article_title">A short title</label>
|
96
130
|
#
|
97
|
-
# label(:
|
98
|
-
# # => <label for="
|
131
|
+
# label(:article, :title, "A short title", class: "title_label")
|
132
|
+
# # => <label for="article_title" class="title_label">A short title</label>
|
99
133
|
```
|
100
134
|
|
101
135
|
Avoid using any printing methods like `puts` or `p` for that purpose.
|
@@ -106,8 +140,55 @@ On the other hand, regular comments do not use an arrow:
|
|
106
140
|
# polymorphic_url(record) # same as comment_url(record)
|
107
141
|
```
|
108
142
|
|
109
|
-
|
110
|
-
|
143
|
+
Booleans
|
144
|
+
--------
|
145
|
+
|
146
|
+
In predicates and flags prefer documenting boolean semantics over exact values.
|
147
|
+
|
148
|
+
When "true" or "false" are used as defined in Ruby use regular font. The
|
149
|
+
singletons `true` and `false` need fixed-width font. Please avoid terms like
|
150
|
+
"truthy", Ruby defines what is true and false in the language, and thus those
|
151
|
+
words have a technical meaning and need no substitutes.
|
152
|
+
|
153
|
+
As a rule of thumb, do not document singletons unless absolutely necessary. That
|
154
|
+
prevents artificial constructs like `!!` or ternaries, allows refactors, and the
|
155
|
+
code does not need to rely on the exact values returned by methods being called
|
156
|
+
in the implementation.
|
157
|
+
|
158
|
+
For example:
|
159
|
+
|
160
|
+
```markdown
|
161
|
+
`config.action_mailer.perform_deliveries` specifies whether mail will actually be delivered and is true by default
|
162
|
+
```
|
163
|
+
|
164
|
+
the user does not need to know which is the actual default value of the flag,
|
165
|
+
and so we only document its boolean semantics.
|
166
|
+
|
167
|
+
An example with a predicate:
|
168
|
+
|
169
|
+
```ruby
|
170
|
+
# Returns true if the collection is empty.
|
171
|
+
#
|
172
|
+
# If the collection has been loaded
|
173
|
+
# it is equivalent to <tt>collection.size.zero?</tt>. If the
|
174
|
+
# collection has not been loaded, it is equivalent to
|
175
|
+
# <tt>collection.exists?</tt>. If the collection has not already been
|
176
|
+
# loaded and you are going to fetch the records anyway it is better to
|
177
|
+
# check <tt>collection.length.zero?</tt>.
|
178
|
+
def empty?
|
179
|
+
if loaded?
|
180
|
+
size.zero?
|
181
|
+
else
|
182
|
+
@target.blank? && !scope.exists?
|
183
|
+
end
|
184
|
+
end
|
185
|
+
```
|
186
|
+
|
187
|
+
The API is careful not to commit to any particular value, the method has
|
188
|
+
predicate semantics, that's enough.
|
189
|
+
|
190
|
+
File Names
|
191
|
+
----------
|
111
192
|
|
112
193
|
As a rule of thumb, use filenames relative to the application root:
|
113
194
|
|
@@ -141,7 +222,17 @@ class Array
|
|
141
222
|
end
|
142
223
|
```
|
143
224
|
|
144
|
-
WARNING: Using
|
225
|
+
WARNING: Using `+...+` for fixed-width font only works with simple content like
|
226
|
+
ordinary method names, symbols, paths (with forward slashes), etc. Please use
|
227
|
+
`<tt>...</tt>` for everything else, notably class or module names with a
|
228
|
+
namespace as in `<tt>ActiveRecord::Base</tt>`.
|
229
|
+
|
230
|
+
You can quickly test the RDoc output with the following command:
|
231
|
+
|
232
|
+
```
|
233
|
+
$ echo "+:to_param+" | rdoc --pipe
|
234
|
+
#=> <p><code>:to_param</code></p>
|
235
|
+
```
|
145
236
|
|
146
237
|
### Regular Font
|
147
238
|
|
@@ -172,7 +263,7 @@ In lists of options, parameters, etc. use a hyphen between the item and its desc
|
|
172
263
|
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
|
173
264
|
```
|
174
265
|
|
175
|
-
The description starts in upper case and ends with a full stop
|
266
|
+
The description starts in upper case and ends with a full stop-it's standard English.
|
176
267
|
|
177
268
|
Dynamically Generated Methods
|
178
269
|
-----------------------------
|
@@ -207,3 +298,64 @@ self.class_eval %{
|
|
207
298
|
end
|
208
299
|
}
|
209
300
|
```
|
301
|
+
|
302
|
+
Method Visibility
|
303
|
+
-----------------
|
304
|
+
|
305
|
+
When writing documentation for Rails, it's important to understand the difference between public user-facing API vs internal API.
|
306
|
+
|
307
|
+
Rails, like most libraries, uses the private keyword from Ruby for defining internal API. However, public API follows a slightly different convention. Instead of assuming all public methods are designed for user consumption, Rails uses the `:nodoc:` directive to annotate these kinds of methods as internal API.
|
308
|
+
|
309
|
+
This means that there are methods in Rails with `public` visibility that aren't meant for user consumption.
|
310
|
+
|
311
|
+
An example of this is `ActiveRecord::Core::ClassMethods#arel_table`:
|
312
|
+
|
313
|
+
```ruby
|
314
|
+
module ActiveRecord::Core::ClassMethods
|
315
|
+
def arel_table #:nodoc:
|
316
|
+
# do some magic..
|
317
|
+
end
|
318
|
+
end
|
319
|
+
```
|
320
|
+
|
321
|
+
If you thought, "this method looks like a public class method for `ActiveRecord::Core`", you were right. But actually the Rails team doesn't want users to rely on this method. So they mark it as `:nodoc:` and it's removed from public documentation. The reasoning behind this is to allow the team to change these methods according to their internal needs across releases as they see fit. The name of this method could change, or the return value, or this entire class may disappear; there's no guarantee and so you shouldn't depend on this API in your plugins or applications. Otherwise, you risk your app or gem breaking when you upgrade to a newer release of Rails.
|
322
|
+
|
323
|
+
As a contributor, it's important to think about whether this API is meant for end-user consumption. The Rails team is committed to not making any breaking changes to public API across releases without going through a full deprecation cycle. It's recommended that you `:nodoc:` any of your internal methods/classes unless they're already private (meaning visibility), in which case it's internal by default. Once the API stabilizes the visibility can change, but changing public API is much harder due to backwards compatibility.
|
324
|
+
|
325
|
+
A class or module is marked with `:nodoc:` to indicate that all methods are internal API and should never be used directly.
|
326
|
+
|
327
|
+
If you come across an existing `:nodoc:` you should tread lightly. Consider asking someone from the core team or author of the code before removing it. This should almost always happen through a pull request instead of the docrails project.
|
328
|
+
|
329
|
+
A `:nodoc:` should never be added simply because a method or class is missing documentation. There may be an instance where an internal public method wasn't given a `:nodoc:` by mistake, for example when switching a method from private to public visibility. When this happens it should be discussed over a PR on a case-by-case basis and never committed directly to docrails.
|
330
|
+
|
331
|
+
To summarize, the Rails team uses `:nodoc:` to mark publicly visible methods and classes for internal use; changes to the visibility of API should be considered carefully and discussed over a pull request first.
|
332
|
+
|
333
|
+
Regarding the Rails Stack
|
334
|
+
-------------------------
|
335
|
+
|
336
|
+
When documenting parts of Rails API, it's important to remember all of the
|
337
|
+
pieces that go into the Rails stack.
|
338
|
+
|
339
|
+
This means that behavior may change depending on the scope or context of the
|
340
|
+
method or class you're trying to document.
|
341
|
+
|
342
|
+
In various places there is different behavior when you take the entire stack
|
343
|
+
into account, one such example is
|
344
|
+
`ActionView::Helpers::AssetTagHelper#image_tag`:
|
345
|
+
|
346
|
+
```ruby
|
347
|
+
# image_tag("icon.png")
|
348
|
+
# # => <img alt="Icon" src="/assets/icon.png" />
|
349
|
+
```
|
350
|
+
|
351
|
+
Although the default behavior for `#image_tag` is to always return
|
352
|
+
`/images/icon.png`, we take into account the full Rails stack (including the
|
353
|
+
Asset Pipeline) we may see the result seen above.
|
354
|
+
|
355
|
+
We're only concerned with the behavior experienced when using the full default
|
356
|
+
Rails stack.
|
357
|
+
|
358
|
+
In this case, we want to document the behavior of the _framework_, and not just
|
359
|
+
this specific method.
|
360
|
+
|
361
|
+
If you have a question on how the Rails team handles certain API, don't hesitate to open a ticket or send a patch to the [issue tracker](https://github.com/rails/rails/issues).
|
@@ -5,9 +5,9 @@ This guide covers the asset pipeline.
|
|
5
5
|
|
6
6
|
After reading this guide, you will know:
|
7
7
|
|
8
|
-
*
|
8
|
+
* What the asset pipeline is and what it does.
|
9
9
|
* How to properly organize your application assets.
|
10
|
-
*
|
10
|
+
* The benefits of the asset pipeline.
|
11
11
|
* How to add a pre-processor to the pipeline.
|
12
12
|
* How to package assets with a gem.
|
13
13
|
|
@@ -16,44 +16,97 @@ After reading this guide, you will know:
|
|
16
16
|
What is the Asset Pipeline?
|
17
17
|
---------------------------
|
18
18
|
|
19
|
-
The asset pipeline provides a framework to concatenate and minify or compress
|
19
|
+
The asset pipeline provides a framework to concatenate and minify or compress
|
20
|
+
JavaScript and CSS assets. It also adds the ability to write these assets in
|
21
|
+
other languages and pre-processors such as CoffeeScript, Sass and ERB.
|
20
22
|
|
21
|
-
|
23
|
+
The asset pipeline is technically no longer a core feature of Rails 4, it has
|
24
|
+
been extracted out of the framework into the
|
25
|
+
[sprockets-rails](https://github.com/rails/sprockets-rails) gem.
|
22
26
|
|
23
|
-
The asset pipeline is enabled by default.
|
27
|
+
The asset pipeline is enabled by default.
|
28
|
+
|
29
|
+
You can disable the asset pipeline while creating a new application by
|
30
|
+
passing the `--skip-sprockets` option.
|
31
|
+
|
32
|
+
```bash
|
33
|
+
rails new appname --skip-sprockets
|
34
|
+
```
|
35
|
+
|
36
|
+
Rails 4 automatically adds the `sass-rails`, `coffee-rails` and `uglifier`
|
37
|
+
gems to your Gemfile, which are used by Sprockets for asset compression:
|
24
38
|
|
25
39
|
```ruby
|
26
|
-
|
40
|
+
gem 'sass-rails'
|
41
|
+
gem 'uglifier'
|
42
|
+
gem 'coffee-rails'
|
27
43
|
```
|
28
44
|
|
29
|
-
|
45
|
+
Using the `--skip-sprockets` option will prevent Rails 4 from adding
|
46
|
+
`sass-rails` and `uglifier` to Gemfile, so if you later want to enable
|
47
|
+
the asset pipeline you will have to add those gems to your Gemfile. Also,
|
48
|
+
creating an application with the `--skip-sprockets` option will generate
|
49
|
+
a slightly different `config/application.rb` file, with a require statement
|
50
|
+
for the sprockets railtie that is commented-out. You will have to remove
|
51
|
+
the comment operator on that line to later enable the asset pipeline:
|
30
52
|
|
31
|
-
```
|
32
|
-
|
53
|
+
```ruby
|
54
|
+
# require "sprockets/railtie"
|
55
|
+
```
|
56
|
+
|
57
|
+
To set asset compression methods, set the appropriate configuration options
|
58
|
+
in `production.rb` - `config.assets.css_compressor` for your CSS and
|
59
|
+
`config.assets.js_compressor` for your JavaScript:
|
60
|
+
|
61
|
+
```ruby
|
62
|
+
config.assets.css_compressor = :yui
|
63
|
+
config.assets.js_compressor = :uglifier
|
33
64
|
```
|
34
65
|
|
35
|
-
|
66
|
+
NOTE: The `sass-rails` gem is automatically used for CSS compression if included
|
67
|
+
in Gemfile and no `config.assets.css_compressor` option is set.
|
36
68
|
|
37
69
|
|
38
70
|
### Main Features
|
39
71
|
|
40
|
-
The first feature of the pipeline is to concatenate assets
|
72
|
+
The first feature of the pipeline is to concatenate assets, which can reduce the
|
73
|
+
number of requests that a browser makes to render a web page. Web browsers are
|
74
|
+
limited in the number of requests that they can make in parallel, so fewer
|
75
|
+
requests can mean faster loading for your application.
|
41
76
|
|
42
|
-
|
77
|
+
Sprockets concatenates all JavaScript files into one master `.js` file and all
|
78
|
+
CSS files into one master `.css` file. As you'll learn later in this guide, you
|
79
|
+
can customize this strategy to group files any way you like. In production,
|
80
|
+
Rails inserts an MD5 fingerprint into each filename so that the file is cached
|
81
|
+
by the web browser. You can invalidate the cache by altering this fingerprint,
|
82
|
+
which happens automatically whenever you change the file contents.
|
43
83
|
|
44
|
-
|
84
|
+
The second feature of the asset pipeline is asset minification or compression.
|
85
|
+
For CSS files, this is done by removing whitespace and comments. For JavaScript,
|
86
|
+
more complex processes can be applied. You can choose from a set of built in
|
87
|
+
options or specify your own.
|
45
88
|
|
46
|
-
The
|
47
|
-
|
48
|
-
|
89
|
+
The third feature of the asset pipeline is it allows coding assets via a
|
90
|
+
higher-level language, with precompilation down to the actual assets. Supported
|
91
|
+
languages include Sass for CSS, CoffeeScript for JavaScript, and ERB for both by
|
92
|
+
default.
|
49
93
|
|
50
94
|
### What is Fingerprinting and Why Should I Care?
|
51
95
|
|
52
|
-
Fingerprinting is a technique that makes the name of a file dependent on the
|
96
|
+
Fingerprinting is a technique that makes the name of a file dependent on the
|
97
|
+
contents of the file. When the file contents change, the filename is also
|
98
|
+
changed. For content that is static or infrequently changed, this provides an
|
99
|
+
easy way to tell whether two versions of a file are identical, even across
|
100
|
+
different servers or deployment dates.
|
53
101
|
|
54
|
-
When a filename is unique and based on its content, HTTP headers can be set to
|
102
|
+
When a filename is unique and based on its content, HTTP headers can be set to
|
103
|
+
encourage caches everywhere (whether at CDNs, at ISPs, in networking equipment,
|
104
|
+
or in web browsers) to keep their own copy of the content. When the content is
|
105
|
+
updated, the fingerprint will change. This will cause the remote clients to
|
106
|
+
request a new copy of the content. This is generally known as _cache busting_.
|
55
107
|
|
56
|
-
The technique
|
108
|
+
The technique sprockets uses for fingerprinting is to insert a hash of the
|
109
|
+
content into the name, usually at the end. For example a CSS file `global.css`
|
57
110
|
|
58
111
|
```
|
59
112
|
global-908e25f4bf641868d8683022a5b62f54.css
|
@@ -61,7 +114,8 @@ global-908e25f4bf641868d8683022a5b62f54.css
|
|
61
114
|
|
62
115
|
This is the strategy adopted by the Rails asset pipeline.
|
63
116
|
|
64
|
-
Rails' old strategy was to append a date-based query string to every asset linked
|
117
|
+
Rails' old strategy was to append a date-based query string to every asset linked
|
118
|
+
with a built-in helper. In the source the generated code looked like this:
|
65
119
|
|
66
120
|
```
|
67
121
|
/stylesheets/global.css?1309495796
|
@@ -69,68 +123,130 @@ Rails' old strategy was to append a date-based query string to every asset linke
|
|
69
123
|
|
70
124
|
The query string strategy has several disadvantages:
|
71
125
|
|
72
|
-
1. **Not all caches will reliably cache content where the filename only differs by
|
73
|
-
|
126
|
+
1. **Not all caches will reliably cache content where the filename only differs by
|
127
|
+
query parameters**
|
128
|
+
|
129
|
+
[Steve Souders recommends](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/),
|
130
|
+
"...avoiding a querystring for cacheable resources". He found that in this
|
131
|
+
case 5-20% of requests will not be cached. Query strings in particular do not
|
132
|
+
work at all with some CDNs for cache invalidation.
|
133
|
+
|
134
|
+
2. **The file name can change between nodes in multi-server environments.**
|
135
|
+
|
136
|
+
The default query string in Rails 2.x is based on the modification time of
|
137
|
+
the files. When assets are deployed to a cluster, there is no guarantee that the
|
138
|
+
timestamps will be the same, resulting in different values being used depending
|
139
|
+
on which server handles the request.
|
140
|
+
|
141
|
+
3. **Too much cache invalidation**
|
74
142
|
|
75
|
-
|
76
|
-
|
77
|
-
|
78
|
-
When static assets are deployed with each new release of code, the mtime(time of last modification) of _all_ these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed.
|
143
|
+
When static assets are deployed with each new release of code, the mtime
|
144
|
+
(time of last modification) of _all_ these files changes, forcing all remote
|
145
|
+
clients to fetch them again, even when the content of those assets has not changed.
|
79
146
|
|
80
|
-
Fingerprinting fixes these problems by avoiding query strings, and by ensuring
|
147
|
+
Fingerprinting fixes these problems by avoiding query strings, and by ensuring
|
148
|
+
that filenames are consistent based on their content.
|
81
149
|
|
82
|
-
Fingerprinting is enabled by default for production and disabled for all other
|
150
|
+
Fingerprinting is enabled by default for production and disabled for all other
|
151
|
+
environments. You can enable or disable it in your configuration through the
|
152
|
+
`config.assets.digest` option.
|
83
153
|
|
84
154
|
More reading:
|
85
155
|
|
86
156
|
* [Optimize caching](http://code.google.com/speed/page-speed/docs/caching.html)
|
87
|
-
* [Revving Filenames: don
|
157
|
+
* [Revving Filenames: don't use querystring](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/)
|
88
158
|
|
89
159
|
|
90
160
|
How to Use the Asset Pipeline
|
91
161
|
-----------------------------
|
92
162
|
|
93
|
-
In previous versions of Rails, all assets were located in subdirectories of
|
163
|
+
In previous versions of Rails, all assets were located in subdirectories of
|
164
|
+
`public` such as `images`, `javascripts` and `stylesheets`. With the asset
|
165
|
+
pipeline, the preferred location for these assets is now the `app/assets`
|
166
|
+
directory. Files in this directory are served by the Sprockets middleware.
|
94
167
|
|
95
|
-
Assets can still be placed in the `public` hierarchy. Any assets under `public`
|
168
|
+
Assets can still be placed in the `public` hierarchy. Any assets under `public`
|
169
|
+
will be served as static files by the application or web server when
|
170
|
+
`config.serve_static_files` is set to true. You should use `app/assets` for
|
171
|
+
files that must undergo some pre-processing before they are served.
|
96
172
|
|
97
|
-
In production, Rails precompiles these files to `public/assets` by default. The
|
173
|
+
In production, Rails precompiles these files to `public/assets` by default. The
|
174
|
+
precompiled copies are then served as static assets by the web server. The files
|
175
|
+
in `app/assets` are never served directly in production.
|
98
176
|
|
99
177
|
### Controller Specific Assets
|
100
178
|
|
101
|
-
When you generate a scaffold or a controller, Rails also generates a JavaScript
|
179
|
+
When you generate a scaffold or a controller, Rails also generates a JavaScript
|
180
|
+
file (or CoffeeScript file if the `coffee-rails` gem is in the `Gemfile`) and a
|
181
|
+
Cascading Style Sheet file (or SCSS file if `sass-rails` is in the `Gemfile`)
|
182
|
+
for that controller. Additionally, when generating a scaffold, Rails generates
|
183
|
+
the file scaffolds.css (or scaffolds.css.scss if `sass-rails` is in the
|
184
|
+
`Gemfile`.)
|
102
185
|
|
103
|
-
For example, if you generate a `ProjectsController`, Rails will also add a new
|
186
|
+
For example, if you generate a `ProjectsController`, Rails will also add a new
|
187
|
+
file at `app/assets/javascripts/projects.js.coffee` and another at
|
188
|
+
`app/assets/stylesheets/projects.css.scss`. By default these files will be ready
|
189
|
+
to use by your application immediately using the `require_tree` directive. See
|
190
|
+
[Manifest Files and Directives](#manifest-files-and-directives) for more details
|
191
|
+
on require_tree.
|
104
192
|
|
105
|
-
You can also opt to include controller specific stylesheets and JavaScript files
|
193
|
+
You can also opt to include controller specific stylesheets and JavaScript files
|
194
|
+
only in their respective controllers using the following:
|
106
195
|
|
107
|
-
|
196
|
+
`<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag
|
197
|
+
params[:controller] %>`
|
108
198
|
|
109
|
-
|
199
|
+
When doing this, ensure you are not using the `require_tree` directive, as that
|
200
|
+
will result in your assets being included more than once.
|
110
201
|
|
111
|
-
|
202
|
+
WARNING: When using asset precompilation, you will need to ensure that your
|
203
|
+
controller assets will be precompiled when loading them on a per page basis. By
|
204
|
+
default .coffee and .scss files will not be precompiled on their own. See
|
205
|
+
[Precompiling Assets](#precompiling-assets) for more information on how
|
206
|
+
precompiling works.
|
207
|
+
|
208
|
+
NOTE: You must have an ExecJS supported runtime in order to use CoffeeScript.
|
209
|
+
If you are using Mac OS X or Windows, you have a JavaScript runtime installed in
|
210
|
+
your operating system. Check [ExecJS](https://github.com/rails/execjs#readme) documentation to know all supported JavaScript runtimes.
|
211
|
+
|
212
|
+
You can also disable generation of controller specific asset files by adding the
|
213
|
+
following to your `config/application.rb` configuration:
|
112
214
|
|
113
215
|
```ruby
|
114
|
-
config.generators do |g|
|
115
|
-
|
116
|
-
end
|
216
|
+
config.generators do |g|
|
217
|
+
g.assets false
|
218
|
+
end
|
117
219
|
```
|
118
220
|
|
119
221
|
### Asset Organization
|
120
222
|
|
121
|
-
Pipeline assets can be placed inside an application in one of three locations:
|
223
|
+
Pipeline assets can be placed inside an application in one of three locations:
|
224
|
+
`app/assets`, `lib/assets` or `vendor/assets`.
|
225
|
+
|
226
|
+
* `app/assets` is for assets that are owned by the application, such as custom
|
227
|
+
images, JavaScript files or stylesheets.
|
122
228
|
|
123
|
-
* `
|
229
|
+
* `lib/assets` is for your own libraries' code that doesn't really fit into the
|
230
|
+
scope of the application or those libraries which are shared across applications.
|
124
231
|
|
125
|
-
* `
|
232
|
+
* `vendor/assets` is for assets that are owned by outside entities, such as
|
233
|
+
code for JavaScript plugins and CSS frameworks. Keep in mind that third party
|
234
|
+
code with references to other files also processed by the asset Pipeline (images,
|
235
|
+
stylesheets, etc.), will need to be rewritten to use helpers like `asset_path`.
|
126
236
|
|
127
|
-
|
237
|
+
WARNING: If you are upgrading from Rails 3, please take into account that assets
|
238
|
+
under `lib/assets` or `vendor/assets` are available for inclusion via the
|
239
|
+
application manifests but no longer part of the precompile array. See
|
240
|
+
[Precompiling Assets](#precompiling-assets) for guidance.
|
128
241
|
|
129
242
|
#### Search Paths
|
130
243
|
|
131
|
-
When a file is referenced from a manifest or a helper, Sprockets searches the
|
244
|
+
When a file is referenced from a manifest or a helper, Sprockets searches the
|
245
|
+
three default asset locations for it.
|
132
246
|
|
133
|
-
The default locations are: `
|
247
|
+
The default locations are: the `images`, `javascripts` and `stylesheets`
|
248
|
+
directories under the `app/assets` folder, but these subdirectories
|
249
|
+
are not special - any path under `assets/*` will be searched.
|
134
250
|
|
135
251
|
For example, these files:
|
136
252
|
|
@@ -162,72 +278,113 @@ is referenced as:
|
|
162
278
|
//= require sub/something
|
163
279
|
```
|
164
280
|
|
165
|
-
You can view the search path by inspecting
|
281
|
+
You can view the search path by inspecting
|
282
|
+
`Rails.application.config.assets.paths` in the Rails console.
|
166
283
|
|
167
|
-
Besides the standard `assets/*` paths, additional (fully qualified) paths can be
|
284
|
+
Besides the standard `assets/*` paths, additional (fully qualified) paths can be
|
285
|
+
added to the pipeline in `config/application.rb`. For example:
|
168
286
|
|
169
287
|
```ruby
|
170
288
|
config.assets.paths << Rails.root.join("lib", "videoplayer", "flash")
|
171
289
|
```
|
172
290
|
|
173
|
-
Paths are traversed in the order
|
291
|
+
Paths are traversed in the order they occur in the search path. By default,
|
292
|
+
this means the files in `app/assets` take precedence, and will mask
|
293
|
+
corresponding paths in `lib` and `vendor`.
|
174
294
|
|
175
|
-
It is important to note that files you want to reference outside a manifest must
|
295
|
+
It is important to note that files you want to reference outside a manifest must
|
296
|
+
be added to the precompile array or they will not be available in the production
|
297
|
+
environment.
|
176
298
|
|
177
299
|
#### Using Index Files
|
178
300
|
|
179
|
-
Sprockets uses files named `index` (with the relevant extensions) for a special
|
301
|
+
Sprockets uses files named `index` (with the relevant extensions) for a special
|
302
|
+
purpose.
|
180
303
|
|
181
|
-
For example, if you have a jQuery library with many modules, which is stored in
|
304
|
+
For example, if you have a jQuery library with many modules, which is stored in
|
305
|
+
`lib/assets/javascripts/library_name`, the file `lib/assets/javascripts/library_name/index.js` serves as
|
306
|
+
the manifest for all files in this library. This file could include a list of
|
307
|
+
all the required files in order, or a simple `require_tree` directive.
|
182
308
|
|
183
|
-
The library as a whole can be accessed in the
|
309
|
+
The library as a whole can be accessed in the application manifest like so:
|
184
310
|
|
185
311
|
```js
|
186
312
|
//= require library_name
|
187
313
|
```
|
188
314
|
|
189
|
-
This simplifies maintenance and keeps things clean by allowing related code to
|
315
|
+
This simplifies maintenance and keeps things clean by allowing related code to
|
316
|
+
be grouped before inclusion elsewhere.
|
190
317
|
|
191
318
|
### Coding Links to Assets
|
192
319
|
|
193
|
-
Sprockets does not add any new methods to access your assets - you still use the
|
320
|
+
Sprockets does not add any new methods to access your assets - you still use the
|
321
|
+
familiar `javascript_include_tag` and `stylesheet_link_tag`:
|
194
322
|
|
195
323
|
```erb
|
196
|
-
<%= stylesheet_link_tag "application" %>
|
324
|
+
<%= stylesheet_link_tag "application", media: "all" %>
|
197
325
|
<%= javascript_include_tag "application" %>
|
198
326
|
```
|
199
327
|
|
200
|
-
|
328
|
+
If using the turbolinks gem, which is included by default in Rails 4, then
|
329
|
+
include the 'data-turbolinks-track' option which causes turbolinks to check if
|
330
|
+
an asset has been updated and if so loads it into the page:
|
331
|
+
|
332
|
+
```erb
|
333
|
+
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
|
334
|
+
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
|
335
|
+
```
|
336
|
+
|
337
|
+
In regular views you can access images in the `public/assets/images` directory
|
338
|
+
like this:
|
201
339
|
|
202
340
|
```erb
|
203
341
|
<%= image_tag "rails.png" %>
|
204
342
|
```
|
205
343
|
|
206
|
-
Provided that the pipeline is enabled within your application (and not disabled
|
344
|
+
Provided that the pipeline is enabled within your application (and not disabled
|
345
|
+
in the current environment context), this file is served by Sprockets. If a file
|
346
|
+
exists at `public/assets/rails.png` it is served by the web server.
|
207
347
|
|
208
|
-
Alternatively, a request for a file with an MD5 hash such as
|
348
|
+
Alternatively, a request for a file with an MD5 hash such as
|
349
|
+
`public/assets/rails-af27b6a414e6da00003503148be9b409.png` is treated the same
|
350
|
+
way. How these hashes are generated is covered in the [In
|
351
|
+
Production](#in-production) section later on in this guide.
|
209
352
|
|
210
|
-
Sprockets will also look through the paths specified in `config.assets.paths
|
353
|
+
Sprockets will also look through the paths specified in `config.assets.paths`,
|
354
|
+
which includes the standard application paths and any paths added by Rails
|
355
|
+
engines.
|
211
356
|
|
212
|
-
Images can also be organized into subdirectories if required, and
|
357
|
+
Images can also be organized into subdirectories if required, and then can be
|
358
|
+
accessed by specifying the directory's name in the tag:
|
213
359
|
|
214
360
|
```erb
|
215
361
|
<%= image_tag "icons/rails.png" %>
|
216
362
|
```
|
217
363
|
|
218
|
-
WARNING: If you're precompiling your assets (see [In Production](#in-production)
|
364
|
+
WARNING: If you're precompiling your assets (see [In Production](#in-production)
|
365
|
+
below), linking to an asset that does not exist will raise an exception in the
|
366
|
+
calling page. This includes linking to a blank string. As such, be careful using
|
367
|
+
`image_tag` and the other helpers with user-supplied data.
|
219
368
|
|
220
369
|
#### CSS and ERB
|
221
370
|
|
222
|
-
The asset pipeline automatically evaluates ERB. This means
|
371
|
+
The asset pipeline automatically evaluates ERB. This means if you add an
|
372
|
+
`erb` extension to a CSS asset (for example, `application.css.erb`), then
|
373
|
+
helpers like `asset_path` are available in your CSS rules:
|
223
374
|
|
224
375
|
```css
|
225
376
|
.class { background-image: url(<%= asset_path 'image.png' %>) }
|
226
377
|
```
|
227
378
|
|
228
|
-
This writes the path to the particular asset being referenced. In this example,
|
379
|
+
This writes the path to the particular asset being referenced. In this example,
|
380
|
+
it would make sense to have an image in one of the asset load paths, such as
|
381
|
+
`app/assets/images/image.png`, which would be referenced here. If this image is
|
382
|
+
already available in `public/assets` as a fingerprinted file, then that path is
|
383
|
+
referenced.
|
229
384
|
|
230
|
-
If you want to use a [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme)
|
385
|
+
If you want to use a [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme) -
|
386
|
+
a method of embedding the image data directly into the CSS file - you can use
|
387
|
+
the `asset_data_uri` helper.
|
231
388
|
|
232
389
|
```css
|
233
390
|
#logo { background: url(<%= asset_data_uri 'logo.png' %>) }
|
@@ -239,29 +396,33 @@ Note that the closing tag cannot be of the style `-%>`.
|
|
239
396
|
|
240
397
|
#### CSS and Sass
|
241
398
|
|
242
|
-
When using the asset pipeline, paths to assets must be re-written and
|
399
|
+
When using the asset pipeline, paths to assets must be re-written and
|
400
|
+
`sass-rails` provides `-url` and `-path` helpers (hyphenated in Sass,
|
401
|
+
underscored in Ruby) for the following asset classes: image, font, video, audio,
|
402
|
+
JavaScript and stylesheet.
|
243
403
|
|
244
404
|
* `image-url("rails.png")` becomes `url(/assets/rails.png)`
|
245
405
|
* `image-path("rails.png")` becomes `"/assets/rails.png"`.
|
246
406
|
|
247
|
-
The more generic form can also be used
|
407
|
+
The more generic form can also be used:
|
248
408
|
|
249
|
-
* `asset-url("rails.png"
|
250
|
-
* `asset-path("rails.png"
|
409
|
+
* `asset-url("rails.png")` becomes `url(/assets/rails.png)`
|
410
|
+
* `asset-path("rails.png")` becomes `"/assets/rails.png"`
|
251
411
|
|
252
412
|
#### JavaScript/CoffeeScript and ERB
|
253
413
|
|
254
|
-
If you add an `erb` extension to a JavaScript asset, making it something such as
|
414
|
+
If you add an `erb` extension to a JavaScript asset, making it something such as
|
415
|
+
`application.js.erb`, you can then use the `asset_path` helper in your
|
416
|
+
JavaScript code:
|
255
417
|
|
256
418
|
```js
|
257
|
-
$('#logo').attr({
|
258
|
-
src: "<%= asset_path('logo.png') %>"
|
259
|
-
});
|
419
|
+
$('#logo').attr({ src: "<%= asset_path('logo.png') %>" });
|
260
420
|
```
|
261
421
|
|
262
422
|
This writes the path to the particular asset being referenced.
|
263
423
|
|
264
|
-
Similarly, you can use the `asset_path` helper in CoffeeScript files with `erb`
|
424
|
+
Similarly, you can use the `asset_path` helper in CoffeeScript files with `erb`
|
425
|
+
extension (e.g., `application.js.coffee.erb`):
|
265
426
|
|
266
427
|
```js
|
267
428
|
$('#logo').attr src: "<%= asset_path('logo.png') %>"
|
@@ -269,10 +430,19 @@ $('#logo').attr src: "<%= asset_path('logo.png') %>"
|
|
269
430
|
|
270
431
|
### Manifest Files and Directives
|
271
432
|
|
272
|
-
Sprockets uses manifest files to determine which assets to include and serve.
|
433
|
+
Sprockets uses manifest files to determine which assets to include and serve.
|
434
|
+
These manifest files contain _directives_ - instructions that tell Sprockets
|
435
|
+
which files to require in order to build a single CSS or JavaScript file. With
|
436
|
+
these directives, Sprockets loads the files specified, processes them if
|
437
|
+
necessary, concatenates them into one single file and then compresses them
|
438
|
+
(based on value of `Rails.application.config.assets.js_compressor`). By serving
|
439
|
+
one file rather than many, the load time of pages can be greatly reduced because
|
440
|
+
the browser makes fewer requests. Compression also reduces file size, enabling
|
441
|
+
the browser to download them faster.
|
273
442
|
|
274
443
|
|
275
|
-
For example, a new Rails application includes a default
|
444
|
+
For example, a new Rails 4 application includes a default
|
445
|
+
`app/assets/javascripts/application.js` file containing the following lines:
|
276
446
|
|
277
447
|
```js
|
278
448
|
// ...
|
@@ -281,30 +451,63 @@ For example, a new Rails application includes a default `app/assets/javascripts/
|
|
281
451
|
//= require_tree .
|
282
452
|
```
|
283
453
|
|
284
|
-
In JavaScript files,
|
454
|
+
In JavaScript files, Sprockets directives begin with `//=`. In the above case,
|
455
|
+
the file is using the `require` and the `require_tree` directives. The `require`
|
456
|
+
directive is used to tell Sprockets the files you wish to require. Here, you are
|
457
|
+
requiring the files `jquery.js` and `jquery_ujs.js` that are available somewhere
|
458
|
+
in the search path for Sprockets. You need not supply the extensions explicitly.
|
459
|
+
Sprockets assumes you are requiring a `.js` file when done from within a `.js`
|
460
|
+
file.
|
461
|
+
|
462
|
+
The `require_tree` directive tells Sprockets to recursively include _all_
|
463
|
+
JavaScript files in the specified directory into the output. These paths must be
|
464
|
+
specified relative to the manifest file. You can also use the
|
465
|
+
`require_directory` directive which includes all JavaScript files only in the
|
466
|
+
directory specified, without recursion.
|
467
|
+
|
468
|
+
Directives are processed top to bottom, but the order in which files are
|
469
|
+
included by `require_tree` is unspecified. You should not rely on any particular
|
470
|
+
order among those. If you need to ensure some particular JavaScript ends up
|
471
|
+
above some other in the concatenated file, require the prerequisite file first
|
472
|
+
in the manifest. Note that the family of `require` directives prevents files
|
473
|
+
from being included twice in the output.
|
474
|
+
|
475
|
+
Rails also creates a default `app/assets/stylesheets/application.css` file
|
476
|
+
which contains these lines:
|
285
477
|
|
286
|
-
|
287
|
-
|
288
|
-
Directives are processed top to bottom, but the order in which files are included by `require_tree` is unspecified. You should not rely on any particular order among those. If you need to ensure some particular JavaScript ends up above some other in the concatenated file, require the prerequisite file first in the manifest. Note that the family of `require` directives prevents files from being included twice in the output.
|
289
|
-
|
290
|
-
Rails also creates a default `app/assets/stylesheets/application.css` file which contains these lines:
|
291
|
-
|
292
|
-
```js
|
478
|
+
```css
|
293
479
|
/* ...
|
294
480
|
*= require_self
|
295
481
|
*= require_tree .
|
296
482
|
*/
|
297
483
|
```
|
298
484
|
|
299
|
-
|
485
|
+
Rails 4 creates both `app/assets/javascripts/application.js` and
|
486
|
+
`app/assets/stylesheets/application.css` regardless of whether the
|
487
|
+
--skip-sprockets option is used when creating a new rails application. This is
|
488
|
+
so you can easily add asset pipelining later if you like.
|
300
489
|
|
301
|
-
|
490
|
+
The directives that work in JavaScript files also work in stylesheets
|
491
|
+
(though obviously including stylesheets rather than JavaScript files). The
|
492
|
+
`require_tree` directive in a CSS manifest works the same way as the JavaScript
|
493
|
+
one, requiring all stylesheets from the current directory.
|
302
494
|
|
303
|
-
|
495
|
+
In this example, `require_self` is used. This puts the CSS contained within the
|
496
|
+
file (if any) at the precise location of the `require_self` call.
|
304
497
|
|
305
|
-
|
498
|
+
NOTE. If you want to use multiple Sass files, you should generally use the [Sass `@import` rule](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import)
|
499
|
+
instead of these Sprockets directives. When using Sprockets directives, Sass files exist within
|
500
|
+
their own scope, making variables or mixins only available within the document they were defined in.
|
306
501
|
|
307
|
-
|
502
|
+
You can do file globbing as well using `@import "*"`, and `@import "**/*"` to add the whole tree which is equivalent to how `require_tree` works. Check the [sass-rails documentation](https://github.com/rails/sass-rails#features) for more info and important caveats.
|
503
|
+
|
504
|
+
You can have as many manifest files as you need. For example, the `admin.css`
|
505
|
+
and `admin.js` manifest could contain the JS and CSS files that are used for the
|
506
|
+
admin section of an application.
|
507
|
+
|
508
|
+
The same remarks about ordering made above apply. In particular, you can specify
|
509
|
+
individual files and they are compiled in the order specified. For example, you
|
510
|
+
might concatenate three CSS files together this way:
|
308
511
|
|
309
512
|
```js
|
310
513
|
/* ...
|
@@ -314,21 +517,41 @@ The same remarks about ordering made above apply. In particular, you can specify
|
|
314
517
|
*/
|
315
518
|
```
|
316
519
|
|
317
|
-
|
318
520
|
### Preprocessing
|
319
521
|
|
320
|
-
The file extensions used on an asset determine what preprocessing is applied.
|
321
|
-
|
322
|
-
|
323
|
-
|
324
|
-
|
522
|
+
The file extensions used on an asset determine what preprocessing is applied.
|
523
|
+
When a controller or a scaffold is generated with the default Rails gemset, a
|
524
|
+
CoffeeScript file and a SCSS file are generated in place of a regular JavaScript
|
525
|
+
and CSS file. The example used before was a controller called "projects", which
|
526
|
+
generated an `app/assets/javascripts/projects.js.coffee` and an
|
527
|
+
`app/assets/stylesheets/projects.css.scss` file.
|
528
|
+
|
529
|
+
In development mode, or if the asset pipeline is disabled, when these files are
|
530
|
+
requested they are processed by the processors provided by the `coffee-script`
|
531
|
+
and `sass` gems and then sent back to the browser as JavaScript and CSS
|
532
|
+
respectively. When asset pipelining is enabled, these files are preprocessed and
|
533
|
+
placed in the `public/assets` directory for serving by either the Rails app or
|
534
|
+
web server.
|
535
|
+
|
536
|
+
Additional layers of preprocessing can be requested by adding other extensions,
|
537
|
+
where each extension is processed in a right-to-left manner. These should be
|
538
|
+
used in the order the processing should be applied. For example, a stylesheet
|
539
|
+
called `app/assets/stylesheets/projects.css.scss.erb` is first processed as ERB,
|
540
|
+
then SCSS, and finally served as CSS. The same applies to a JavaScript file -
|
541
|
+
`app/assets/javascripts/projects.js.coffee.erb` is processed as ERB, then
|
542
|
+
CoffeeScript, and served as JavaScript.
|
543
|
+
|
544
|
+
Keep in mind the order of these preprocessors is important. For example, if
|
545
|
+
you called your JavaScript file `app/assets/javascripts/projects.js.erb.coffee`
|
546
|
+
then it would be processed with the CoffeeScript interpreter first, which
|
547
|
+
wouldn't understand ERB and therefore you would run into problems.
|
325
548
|
|
326
|
-
Keep in mind that the order of these preprocessors is important. For example, if you called your JavaScript file `app/assets/javascripts/projects.js.erb.coffee` then it would be processed with the CoffeeScript interpreter first, which wouldn't understand ERB and therefore you would run into problems.
|
327
549
|
|
328
550
|
In Development
|
329
551
|
--------------
|
330
552
|
|
331
|
-
In development mode, assets are served as separate files in the order they are
|
553
|
+
In development mode, assets are served as separate files in the order they are
|
554
|
+
specified in the manifest file.
|
332
555
|
|
333
556
|
This manifest `app/assets/javascripts/application.js`:
|
334
557
|
|
@@ -348,41 +571,79 @@ would generate this HTML:
|
|
348
571
|
|
349
572
|
The `body` param is required by Sprockets.
|
350
573
|
|
574
|
+
### Runtime Error Checking
|
575
|
+
|
576
|
+
By default the asset pipeline will check for potential errors in development mode during
|
577
|
+
runtime. To disable this behavior you can set:
|
578
|
+
|
579
|
+
```ruby
|
580
|
+
config.assets.raise_runtime_errors = false
|
581
|
+
```
|
582
|
+
|
583
|
+
When this option is true, the asset pipeline will check if all the assets loaded
|
584
|
+
in your application are included in the `config.assets.precompile` list.
|
585
|
+
If `config.assets.digest` is also true, the asset pipeline will require that
|
586
|
+
all requests for assets include digests.
|
587
|
+
|
588
|
+
### Turning Digests Off
|
589
|
+
|
590
|
+
You can turn off digests by updating `config/environments/development.rb` to
|
591
|
+
include:
|
592
|
+
|
593
|
+
```ruby
|
594
|
+
config.assets.digest = false
|
595
|
+
```
|
596
|
+
|
597
|
+
When this option is true, digests will be generated for asset URLs.
|
598
|
+
|
351
599
|
### Turning Debugging Off
|
352
600
|
|
353
|
-
You can turn off debug mode by updating `config/environments/development.rb` to
|
601
|
+
You can turn off debug mode by updating `config/environments/development.rb` to
|
602
|
+
include:
|
354
603
|
|
355
604
|
```ruby
|
356
605
|
config.assets.debug = false
|
357
606
|
```
|
358
607
|
|
359
|
-
When debug mode is off, Sprockets concatenates and runs the necessary
|
608
|
+
When debug mode is off, Sprockets concatenates and runs the necessary
|
609
|
+
preprocessors on all files. With debug mode turned off the manifest above would
|
610
|
+
generate instead:
|
360
611
|
|
361
612
|
```html
|
362
613
|
<script src="/assets/application.js"></script>
|
363
614
|
```
|
364
615
|
|
365
|
-
Assets are compiled and cached on the first request after the server is started.
|
616
|
+
Assets are compiled and cached on the first request after the server is started.
|
617
|
+
Sprockets sets a `must-revalidate` Cache-Control HTTP header to reduce request
|
618
|
+
overhead on subsequent requests - on these the browser gets a 304 (Not Modified)
|
619
|
+
response.
|
366
620
|
|
367
|
-
If any of the files in the manifest have changed between requests, the server
|
621
|
+
If any of the files in the manifest have changed between requests, the server
|
622
|
+
responds with a new compiled file.
|
368
623
|
|
369
|
-
Debug mode can also be enabled in
|
624
|
+
Debug mode can also be enabled in Rails helper methods:
|
370
625
|
|
371
626
|
```erb
|
372
627
|
<%= stylesheet_link_tag "application", debug: true %>
|
373
628
|
<%= javascript_include_tag "application", debug: true %>
|
374
629
|
```
|
375
630
|
|
376
|
-
The `:debug` option is redundant if debug mode is on.
|
631
|
+
The `:debug` option is redundant if debug mode is already on.
|
377
632
|
|
378
|
-
You
|
633
|
+
You can also enable compression in development mode as a sanity check, and
|
634
|
+
disable it on-demand as required for debugging.
|
379
635
|
|
380
636
|
In Production
|
381
637
|
-------------
|
382
638
|
|
383
|
-
In the production environment
|
639
|
+
In the production environment Sprockets uses the fingerprinting scheme outlined
|
640
|
+
above. By default Rails assumes assets have been precompiled and will be
|
641
|
+
served as static assets by your web server.
|
384
642
|
|
385
|
-
During the precompilation phase an MD5 is generated from the contents of the
|
643
|
+
During the precompilation phase an MD5 is generated from the contents of the
|
644
|
+
compiled files, and inserted into the filenames as they are written to disc.
|
645
|
+
These fingerprinted names are used by the Rails helpers in place of the manifest
|
646
|
+
name.
|
386
647
|
|
387
648
|
For example this:
|
388
649
|
|
@@ -395,113 +656,117 @@ generates something like this:
|
|
395
656
|
|
396
657
|
```html
|
397
658
|
<script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js"></script>
|
398
|
-
<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen"
|
659
|
+
<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen"
|
660
|
+
rel="stylesheet" />
|
399
661
|
```
|
400
662
|
|
401
|
-
Note: with the Asset Pipeline the :cache and :concat options aren't used
|
402
|
-
|
663
|
+
Note: with the Asset Pipeline the :cache and :concat options aren't used
|
664
|
+
anymore, delete these options from the `javascript_include_tag` and
|
665
|
+
`stylesheet_link_tag`.
|
403
666
|
|
404
|
-
The fingerprinting behavior is controlled by the
|
667
|
+
The fingerprinting behavior is controlled by the `config.assets.digest`
|
668
|
+
initialization option (which defaults to `true` for production and `false` for
|
669
|
+
everything else).
|
405
670
|
|
406
|
-
NOTE: Under normal circumstances the default
|
671
|
+
NOTE: Under normal circumstances the default `config.assets.digest` option
|
672
|
+
should not be changed. If there are no digests in the filenames, and far-future
|
673
|
+
headers are set, remote clients will never know to refetch the files when their
|
674
|
+
content changes.
|
407
675
|
|
408
676
|
### Precompiling Assets
|
409
677
|
|
410
|
-
Rails comes bundled with a rake task to compile the asset manifests and other
|
678
|
+
Rails comes bundled with a rake task to compile the asset manifests and other
|
679
|
+
files in the pipeline.
|
411
680
|
|
412
|
-
Compiled assets are written to the location specified in `config.assets.prefix`.
|
681
|
+
Compiled assets are written to the location specified in `config.assets.prefix`.
|
682
|
+
By default, this is the `/assets` directory.
|
413
683
|
|
414
|
-
You can call this task on the server during deployment to create compiled
|
684
|
+
You can call this task on the server during deployment to create compiled
|
685
|
+
versions of your assets directly on the server. See the next section for
|
686
|
+
information on compiling locally.
|
415
687
|
|
416
688
|
The rake task is:
|
417
689
|
|
418
690
|
```bash
|
419
|
-
$ RAILS_ENV=production
|
691
|
+
$ RAILS_ENV=production bin/rake assets:precompile
|
420
692
|
```
|
421
693
|
|
422
|
-
|
423
|
-
|
424
|
-
cannot see application objects or methods. **Heroku requires this to be false.**
|
425
|
-
|
426
|
-
WARNING: If you set `config.assets.initialize_on_precompile` to false, be sure to
|
427
|
-
test `rake assets:precompile` locally before deploying. It may expose bugs where
|
428
|
-
your assets reference application objects or methods, since those are still
|
429
|
-
in scope in development mode regardless of the value of this flag. Changing this flag also affects
|
430
|
-
engines. Engines can define assets for precompilation as well. Since the complete environment is not loaded,
|
431
|
-
engines (or other gems) will not be loaded, which can cause missing assets.
|
432
|
-
|
433
|
-
Capistrano (v2.8.0 and above) includes a recipe to handle this in deployment. Add the following line to `Capfile`:
|
694
|
+
Capistrano (v2.15.1 and above) includes a recipe to handle this in deployment.
|
695
|
+
Add the following line to `Capfile`:
|
434
696
|
|
435
697
|
```ruby
|
436
698
|
load 'deploy/assets'
|
437
699
|
```
|
438
700
|
|
439
|
-
This links the folder specified in `config.assets.prefix` to `shared/assets`.
|
701
|
+
This links the folder specified in `config.assets.prefix` to `shared/assets`.
|
702
|
+
If you already use this shared folder you'll need to write your own deployment
|
703
|
+
task.
|
440
704
|
|
441
|
-
It is important that this folder is shared between deployments so that remotely
|
705
|
+
It is important that this folder is shared between deployments so that remotely
|
706
|
+
cached pages referencing the old compiled assets still work for the life of
|
707
|
+
the cached page.
|
442
708
|
|
443
|
-
|
444
|
-
|
445
|
-
|
709
|
+
The default matcher for compiling files includes `application.js`,
|
710
|
+
`application.css` and all non-JS/CSS files (this will include all image assets
|
711
|
+
automatically) from `app/assets` folders including your gems:
|
446
712
|
|
447
713
|
```ruby
|
448
|
-
[ Proc.new { |path| !%w(.js .css).include?(File.extname(
|
714
|
+
[ Proc.new { |filename, path| path =~ /app\/assets/ && !%w(.js .css).include?(File.extname(filename)) },
|
715
|
+
/application.(css|js)$/ ]
|
449
716
|
```
|
450
717
|
|
451
|
-
NOTE
|
452
|
-
|
453
|
-
|
454
|
-
|
455
|
-
```ruby
|
456
|
-
config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
|
457
|
-
```
|
718
|
+
NOTE: The matcher (and other members of the precompile array; see below) is
|
719
|
+
applied to final compiled file names. This means anything that compiles to
|
720
|
+
JS/CSS is excluded, as well as raw JS/CSS files; for example, `.coffee` and
|
721
|
+
`.scss` files are **not** automatically included as they compile to JS/CSS.
|
458
722
|
|
459
|
-
|
723
|
+
If you have other manifests or individual stylesheets and JavaScript files to
|
724
|
+
include, you can add them to the `precompile` array in `config/initializers/assets.rb`:
|
460
725
|
|
461
726
|
```ruby
|
462
|
-
|
463
|
-
config.assets.precompile << Proc.new do |path|
|
464
|
-
if path =~ /\.(css|js)\z/
|
465
|
-
full_path = Rails.application.assets.resolve(path).to_path
|
466
|
-
app_assets_path = Rails.root.join('app', 'assets').to_path
|
467
|
-
if full_path.starts_with? app_assets_path
|
468
|
-
puts "including asset: " + full_path
|
469
|
-
true
|
470
|
-
else
|
471
|
-
puts "excluding asset: " + full_path
|
472
|
-
false
|
473
|
-
end
|
474
|
-
else
|
475
|
-
false
|
476
|
-
end
|
477
|
-
end
|
727
|
+
Rails.application.config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
|
478
728
|
```
|
479
729
|
|
480
|
-
NOTE. Always specify an expected compiled filename that ends with js or css,
|
730
|
+
NOTE. Always specify an expected compiled filename that ends with .js or .css,
|
731
|
+
even if you want to add Sass or CoffeeScript files to the precompile array.
|
481
732
|
|
482
|
-
The rake task also generates a `manifest.
|
733
|
+
The rake task also generates a `manifest-md5hash.json` that contains a list with
|
734
|
+
all your assets and their respective fingerprints. This is used by the Rails
|
735
|
+
helper methods to avoid handing the mapping requests back to Sprockets. A
|
736
|
+
typical manifest file looks like:
|
483
737
|
|
484
|
-
```
|
485
|
-
|
486
|
-
|
487
|
-
|
488
|
-
|
489
|
-
|
490
|
-
application.
|
738
|
+
```ruby
|
739
|
+
{"files":{"application-723d1be6cc741a3aabb1cec24276d681.js":{"logical_path":"application.js","mtime":"2013-07-26T22:55:03-07:00","size":302506,
|
740
|
+
"digest":"723d1be6cc741a3aabb1cec24276d681"},"application-12b3c7dd74d2e9df37e7cbb1efa76a6d.css":{"logical_path":"application.css","mtime":"2013-07-26T22:54:54-07:00","size":1560,
|
741
|
+
"digest":"12b3c7dd74d2e9df37e7cbb1efa76a6d"},"application-1c5752789588ac18d7e1a50b1f0fd4c2.css":{"logical_path":"application.css","mtime":"2013-07-26T22:56:17-07:00","size":1591,
|
742
|
+
"digest":"1c5752789588ac18d7e1a50b1f0fd4c2"},"favicon-a9c641bf2b81f0476e876f7c5e375969.ico":{"logical_path":"favicon.ico","mtime":"2013-07-26T23:00:10-07:00","size":1406,
|
743
|
+
"digest":"a9c641bf2b81f0476e876f7c5e375969"},"my_image-231a680f23887d9dd70710ea5efd3c62.png":{"logical_path":"my_image.png","mtime":"2013-07-26T23:00:27-07:00","size":6646,
|
744
|
+
"digest":"231a680f23887d9dd70710ea5efd3c62"}},"assets":{"application.js":
|
745
|
+
"application-723d1be6cc741a3aabb1cec24276d681.js","application.css":
|
746
|
+
"application-1c5752789588ac18d7e1a50b1f0fd4c2.css",
|
747
|
+
"favicon.ico":"favicona9c641bf2b81f0476e876f7c5e375969.ico","my_image.png":
|
748
|
+
"my_image-231a680f23887d9dd70710ea5efd3c62.png"}}
|
491
749
|
```
|
492
750
|
|
493
|
-
The default location for the manifest is the root of the location specified in
|
751
|
+
The default location for the manifest is the root of the location specified in
|
752
|
+
`config.assets.prefix` ('/assets' by default).
|
494
753
|
|
495
|
-
NOTE: If there are missing precompiled files in production you will get an
|
754
|
+
NOTE: If there are missing precompiled files in production you will get an
|
755
|
+
`Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError`
|
756
|
+
exception indicating the name of the missing file(s).
|
496
757
|
|
497
758
|
#### Far-future Expires Header
|
498
759
|
|
499
|
-
Precompiled assets exist on the
|
760
|
+
Precompiled assets exist on the file system and are served directly by your web
|
761
|
+
server. They do not have far-future headers by default, so to get the benefit of
|
762
|
+
fingerprinting you'll have to update your server configuration to add those
|
763
|
+
headers.
|
500
764
|
|
501
765
|
For Apache:
|
502
766
|
|
503
767
|
```apache
|
504
|
-
# The Expires* directives requires the Apache module
|
768
|
+
# The Expires* directives requires the Apache module
|
769
|
+
# `mod_expires` to be enabled.
|
505
770
|
<Location /assets/>
|
506
771
|
# Use of ETag is discouraged when Last-Modified is present
|
507
772
|
Header unset ETag
|
@@ -512,7 +777,7 @@ For Apache:
|
|
512
777
|
</Location>
|
513
778
|
```
|
514
779
|
|
515
|
-
For
|
780
|
+
For NGINX:
|
516
781
|
|
517
782
|
```nginx
|
518
783
|
location ~ ^/assets/ {
|
@@ -524,45 +789,25 @@ location ~ ^/assets/ {
|
|
524
789
|
}
|
525
790
|
```
|
526
791
|
|
527
|
-
#### GZip Compression
|
528
|
-
|
529
|
-
When files are precompiled, Sprockets also creates a [gzipped](http://en.wikipedia.org/wiki/Gzip) (.gz) version of your assets. Web servers are typically configured to use a moderate compression ratio as a compromise, but since precompilation happens once, Sprockets uses the maximum compression ratio, thus reducing the size of the data transfer to the minimum. On the other hand, web servers can be configured to serve compressed content directly from disk, rather than deflating non-compressed files themselves.
|
530
|
-
|
531
|
-
Nginx is able to do this automatically enabling `gzip_static`:
|
532
|
-
|
533
|
-
```nginx
|
534
|
-
location ~ ^/(assets)/ {
|
535
|
-
root /path/to/public;
|
536
|
-
gzip_static on; # to serve pre-gzipped version
|
537
|
-
expires max;
|
538
|
-
add_header Cache-Control public;
|
539
|
-
}
|
540
|
-
```
|
541
|
-
|
542
|
-
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:
|
543
|
-
|
544
|
-
```bash
|
545
|
-
./configure --with-http_gzip_static_module
|
546
|
-
```
|
547
|
-
|
548
|
-
If you're compiling nginx with Phusion Passenger you'll need to pass that option when prompted.
|
549
|
-
|
550
|
-
A robust configuration for Apache is possible but tricky; please Google around. (Or help update this Guide if you have a good example configuration for Apache.)
|
551
|
-
|
552
792
|
### Local Precompilation
|
553
793
|
|
554
|
-
There are several reasons why you might want to precompile your assets locally.
|
794
|
+
There are several reasons why you might want to precompile your assets locally.
|
795
|
+
Among them are:
|
555
796
|
|
556
797
|
* You may not have write access to your production file system.
|
557
|
-
* You may be deploying to more than one server, and want to avoid
|
798
|
+
* You may be deploying to more than one server, and want to avoid
|
799
|
+
duplication of work.
|
558
800
|
* You may be doing frequent deploys that do not include asset changes.
|
559
801
|
|
560
|
-
Local compilation allows you to commit the compiled files into source control,
|
802
|
+
Local compilation allows you to commit the compiled files into source control,
|
803
|
+
and deploy as normal.
|
561
804
|
|
562
|
-
There are
|
805
|
+
There are three caveats:
|
563
806
|
|
564
807
|
* You must not run the Capistrano deployment task that precompiles assets.
|
565
|
-
* You must
|
808
|
+
* You must ensure any necessary compressors or minifiers are
|
809
|
+
available on your development system.
|
810
|
+
* You must change the following application configuration setting:
|
566
811
|
|
567
812
|
In `config/environments/development.rb`, place the following line:
|
568
813
|
|
@@ -570,23 +815,20 @@ In `config/environments/development.rb`, place the following line:
|
|
570
815
|
config.assets.prefix = "/dev-assets"
|
571
816
|
```
|
572
817
|
|
573
|
-
|
818
|
+
The `prefix` change makes Sprockets use a different URL for serving assets in
|
819
|
+
development mode, and pass all requests to Sprockets. The prefix is still set to
|
820
|
+
`/assets` in the production environment. Without this change, the application
|
821
|
+
would serve the precompiled assets from `/assets` in development, and you would
|
822
|
+
not see any local changes until you compile assets again.
|
574
823
|
|
575
|
-
|
576
|
-
|
577
|
-
|
578
|
-
|
579
|
-
The `prefix` change makes Rails use a different URL for serving assets in development mode, and pass all requests to Sprockets. The prefix is still set to `/assets` in the production environment. Without this change, the application would serve the precompiled assets from `public/assets` in development, and you would not see any local changes until you compile assets again.
|
580
|
-
|
581
|
-
The `initialize_on_precompile` change tells the precompile task to run without invoking Rails. This is because the precompile task runs in production mode by default, and will attempt to connect to your specified production database. Please note that you cannot have code in pipeline files that relies on Rails resources (such as the database) when compiling locally with this option.
|
582
|
-
|
583
|
-
You will also need to ensure that any compressors or minifiers are available on your development system.
|
584
|
-
|
585
|
-
In practice, this will allow you to precompile locally, have those files in your working tree, and commit those files to source control when needed. Development mode will work as expected.
|
824
|
+
In practice, this will allow you to precompile locally, have those files in your
|
825
|
+
working tree, and commit those files to source control when needed. Development
|
826
|
+
mode will work as expected.
|
586
827
|
|
587
828
|
### Live Compilation
|
588
829
|
|
589
|
-
In some circumstances you may wish to use live compilation. In this mode all
|
830
|
+
In some circumstances you may wish to use live compilation. In this mode all
|
831
|
+
requests for assets in the pipeline are handled by Sprockets directly.
|
590
832
|
|
591
833
|
To enable this option set:
|
592
834
|
|
@@ -594,13 +836,21 @@ To enable this option set:
|
|
594
836
|
config.assets.compile = true
|
595
837
|
```
|
596
838
|
|
597
|
-
On the first request the assets are compiled and cached as outlined in
|
839
|
+
On the first request the assets are compiled and cached as outlined in
|
840
|
+
development above, and the manifest names used in the helpers are altered to
|
841
|
+
include the MD5 hash.
|
598
842
|
|
599
|
-
Sprockets also sets the `Cache-Control` HTTP header to `max-age=31536000`. This
|
843
|
+
Sprockets also sets the `Cache-Control` HTTP header to `max-age=31536000`. This
|
844
|
+
signals all caches between your server and the client browser that this content
|
845
|
+
(the file served) can be cached for 1 year. The effect of this is to reduce the
|
846
|
+
number of requests for this asset from your server; the asset has a good chance
|
847
|
+
of being in the local browser cache or some intermediate cache.
|
600
848
|
|
601
|
-
This mode uses more memory, performs more poorly than the default and is not
|
849
|
+
This mode uses more memory, performs more poorly than the default and is not
|
850
|
+
recommended.
|
602
851
|
|
603
|
-
If you are deploying a production application to a system without any
|
852
|
+
If you are deploying a production application to a system without any
|
853
|
+
pre-existing JavaScript runtimes, you may want to add one to your Gemfile:
|
604
854
|
|
605
855
|
```ruby
|
606
856
|
group :production do
|
@@ -610,36 +860,239 @@ end
|
|
610
860
|
|
611
861
|
### CDNs
|
612
862
|
|
613
|
-
|
614
|
-
|
615
|
-
|
616
|
-
|
863
|
+
CDN stands for [Content Delivery
|
864
|
+
Network](http://en.wikipedia.org/wiki/Content_delivery_network), they are
|
865
|
+
primarily designed to cache assets all over the world so that when a browser
|
866
|
+
requests the asset, a cached copy will be geographically close to that browser.
|
867
|
+
If you are serving assets directly from your Rails server in production, the
|
868
|
+
best practice is to use a CDN in front of your application.
|
869
|
+
|
870
|
+
A common pattern for using a CDN is to set your production application as the
|
871
|
+
"origin" server. This means when a browser requests an asset from the CDN and
|
872
|
+
there is a cache miss, it will grab the file from your server on the fly and
|
873
|
+
then cache it. For example if you are running a Rails application on
|
874
|
+
`example.com` and have a CDN configured at `mycdnsubdomain.fictional-cdn.com`,
|
875
|
+
then when a request is made to `mycdnsubdomain.fictional-
|
876
|
+
cdn.com/assets/smile.png`, the CDN will query your server once at
|
877
|
+
`example.com/assets/smile.png` and cache the request. The next request to the
|
878
|
+
CDN that comes in to the same URL will hit the cached copy. When the CDN can
|
879
|
+
serve an asset directly the request never touches your Rails server. Since the
|
880
|
+
assets from a CDN are geographically closer to the browser, the request is
|
881
|
+
faster, and since your server doesn't need to spend time serving assets, it can
|
882
|
+
focus on serving application code as fast as possible.
|
883
|
+
|
884
|
+
#### Set up a CDN to Serve Static Assets
|
885
|
+
|
886
|
+
To set up your CDN you have to have your application running in production on
|
887
|
+
the internet at a publically available URL, for example `example.com`. Next
|
888
|
+
you'll need to sign up for a CDN service from a cloud hosting provider. When you
|
889
|
+
do this you need to configure the "origin" of the CDN to point back at your
|
890
|
+
website `example.com`, check your provider for documentation on configuring the
|
891
|
+
origin server.
|
892
|
+
|
893
|
+
The CDN you provisioned should give you a custom subdomain for your application
|
894
|
+
such as `mycdnsubdomain.fictional-cdn.com` (note fictional-cdn.com is not a
|
895
|
+
valid CDN provider at the time of this writing). Now that you have configured
|
896
|
+
your CDN server, you need to tell browsers to use your CDN to grab assets
|
897
|
+
instead of your Rails server directly. You can do this by configuring Rails to
|
898
|
+
set your CDN as the asset host instead of using a relative path. To set your
|
899
|
+
asset host in Rails, you need to set `config.action_controller.asset_host` in
|
900
|
+
`config/production.rb`:
|
901
|
+
|
902
|
+
```ruby
|
903
|
+
config.action_controller.asset_host = 'mycdnsubdomain.fictional-cdn.com'
|
904
|
+
```
|
905
|
+
|
906
|
+
NOTE: You only need to provide the "host", this is the subdomain and root
|
907
|
+
domain, you do not need to specify a protocol or "scheme" such as `http://` or
|
908
|
+
`https://`. When a web page is requested, the protocol in the link to your asset
|
909
|
+
that is generated will match how the webpage is accessed by default.
|
910
|
+
|
911
|
+
You can also set this value through an [environment
|
912
|
+
variable](http://en.wikipedia.org/wiki/Environment_variable) to make running a
|
913
|
+
staging copy of your site easier:
|
914
|
+
|
915
|
+
```
|
916
|
+
config.action_controller.asset_host = ENV['CDN_HOST']
|
917
|
+
```
|
918
|
+
|
919
|
+
|
920
|
+
|
921
|
+
Note: You would need to set `CDN_HOST` on your server to `mycdnsubdomain
|
922
|
+
.fictional-cdn.com` for this to work.
|
923
|
+
|
924
|
+
Once you have configured your server and your CDN when you serve a webpage that
|
925
|
+
has an asset:
|
926
|
+
|
927
|
+
```erb
|
928
|
+
<%= asset_path('smile.png') %>
|
929
|
+
```
|
930
|
+
|
931
|
+
Instead of returning a path such as `/assets/smile.png` (digests are left out
|
932
|
+
for readability). The URL generated will have the full path to your CDN.
|
617
933
|
|
618
|
-
|
619
|
-
|
620
|
-
|
621
|
-
|
934
|
+
```
|
935
|
+
http://mycdnsubdomain.fictional-cdn.com/assets/smile.png
|
936
|
+
```
|
937
|
+
|
938
|
+
If the CDN has a copy of `smile.png` it will serve it to the browser and your
|
939
|
+
server doesn't even know it was requested. If the CDN does not have a copy it
|
940
|
+
will try to find it a the "origin" `example.com/assets/smile.png` and then store
|
941
|
+
it for future use.
|
942
|
+
|
943
|
+
If you want to serve only some assets from your CDN, you can use custom `:host`
|
944
|
+
option your asset helper, which overwrites value set in
|
945
|
+
`config.action_controller.asset_host`.
|
946
|
+
|
947
|
+
```erb
|
948
|
+
<%= asset_path 'image.png', host: 'mycdnsubdomain.fictional-cdn.com' %>
|
949
|
+
```
|
950
|
+
|
951
|
+
#### Customize CDN Caching Behavior
|
952
|
+
|
953
|
+
A CDN works by caching content. If the CDN has stale or bad content, then it is
|
954
|
+
hurting rather than helping your application. The purpose of this section is to
|
955
|
+
describe general caching behavior of most CDNs, your specific provider may
|
956
|
+
behave slightly differently.
|
957
|
+
|
958
|
+
##### CDN Request Caching
|
959
|
+
|
960
|
+
While a CDN is described as being good for caching assets, in reality caches the
|
961
|
+
entire request. This includes the body of the asset as well as any headers. The
|
962
|
+
most important one being `Cache-Control` which tells the CDN (and web browsers)
|
963
|
+
how to cache contents. This means that if someone requests an asset that does
|
964
|
+
not exist `/assets/i-dont-exist.png` and your Rails application returns a 404,
|
965
|
+
then your CDN will likely cache the 404 page if a valid `Cache-Control` header
|
966
|
+
is present.
|
967
|
+
|
968
|
+
##### CDN Header Debugging
|
969
|
+
|
970
|
+
One way to check the headers are cached properly in your CDN is by using [curl](
|
971
|
+
http://explainshell.com/explain?cmd=curl+-I+http%3A%2F%2Fwww.example.com). You
|
972
|
+
can request the headers from both your server and your CDN to verify they are
|
973
|
+
the same:
|
974
|
+
|
975
|
+
```
|
976
|
+
$ curl -I http://www.example/assets/application-
|
977
|
+
d0e099e021c95eb0de3615fd1d8c4d83.css
|
978
|
+
HTTP/1.1 200 OK
|
979
|
+
Server: Cowboy
|
980
|
+
Date: Sun, 24 Aug 2014 20:27:50 GMT
|
981
|
+
Connection: keep-alive
|
982
|
+
Last-Modified: Thu, 08 May 2014 01:24:14 GMT
|
983
|
+
Content-Type: text/css
|
984
|
+
Cache-Control: public, max-age=2592000
|
985
|
+
Content-Length: 126560
|
986
|
+
Via: 1.1 vegur
|
987
|
+
```
|
988
|
+
|
989
|
+
Versus the CDN copy.
|
990
|
+
|
991
|
+
```
|
992
|
+
$ curl -I http://mycdnsubdomain.fictional-cdn.com/application-
|
993
|
+
d0e099e021c95eb0de3615fd1d8c4d83.css
|
994
|
+
HTTP/1.1 200 OK Server: Cowboy Last-
|
995
|
+
Modified: Thu, 08 May 2014 01:24:14 GMT Content-Type: text/css
|
996
|
+
Cache-Control:
|
997
|
+
public, max-age=2592000
|
998
|
+
Via: 1.1 vegur
|
999
|
+
Content-Length: 126560
|
1000
|
+
Accept-Ranges:
|
1001
|
+
bytes
|
1002
|
+
Date: Sun, 24 Aug 2014 20:28:45 GMT
|
1003
|
+
Via: 1.1 varnish
|
1004
|
+
Age: 885814
|
1005
|
+
Connection: keep-alive
|
1006
|
+
X-Served-By: cache-dfw1828-DFW
|
1007
|
+
X-Cache: HIT
|
1008
|
+
X-Cache-Hits:
|
1009
|
+
68
|
1010
|
+
X-Timer: S1408912125.211638212,VS0,VE0
|
1011
|
+
```
|
1012
|
+
|
1013
|
+
Check your CDN documentation for any additional information they may provide
|
1014
|
+
such as `X-Cache` or for any additional headers they may add.
|
1015
|
+
|
1016
|
+
##### CDNs and the Cache-Control Header
|
1017
|
+
|
1018
|
+
The [cache control
|
1019
|
+
header](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9) is a W3C
|
1020
|
+
specification that describes how a request can be cached. When no CDN is used, a
|
1021
|
+
browser will use this information to cache contents. This is very helpful for
|
1022
|
+
assets that are not modified so that a browser does not need to re-download a
|
1023
|
+
website's CSS or javascript on every request. Generally we want our Rails server
|
1024
|
+
to tell our CDN (and browser) that the asset is "public", that means any cache
|
1025
|
+
can store the request. Also we commonly want to set `max-age` which is how long
|
1026
|
+
the cache will store the object before invalidating the cache. The `max-age`
|
1027
|
+
value is set to seconds with a maximum possible value of `31536000` which is one
|
1028
|
+
year. You can do this in your rails application by setting
|
1029
|
+
|
1030
|
+
```
|
1031
|
+
config.static_cache_control = "public, max-age=31536000"
|
1032
|
+
```
|
1033
|
+
|
1034
|
+
Now when your application serves an asset in production, the CDN will store the
|
1035
|
+
asset for up to a year. Since most CDNs also cache headers of the request, this
|
1036
|
+
`Cache-Control` will be passed along to all future browsers seeking this asset,
|
1037
|
+
the browser then knows that it can store this asset for a very long time before
|
1038
|
+
needing to re-request it.
|
1039
|
+
|
1040
|
+
##### CDNs and URL based Cache Invalidation
|
1041
|
+
|
1042
|
+
Most CDNs will cache contents of an asset based on the complete URL. This means
|
1043
|
+
that a request to
|
1044
|
+
|
1045
|
+
```
|
1046
|
+
http://mycdnsubdomain.fictional-cdn.com/assets/smile-123.png
|
1047
|
+
```
|
1048
|
+
|
1049
|
+
Will be a completely different cache from
|
1050
|
+
|
1051
|
+
```
|
1052
|
+
http://mycdnsubdomain.fictional-cdn.com/assets/smile.png
|
1053
|
+
```
|
1054
|
+
|
1055
|
+
If you want to set far future `max-age` in your `Cache-Control` (and you do),
|
1056
|
+
then make sure when you change your assets that your cache is invalidated. For
|
1057
|
+
example when changing the smiley face in an image from yellow to blue, you want
|
1058
|
+
all visitors of your site to get the new blue face. When using a CDN with the
|
1059
|
+
Rails asset pipeline `config.assets.digest` is set to true by default so that
|
1060
|
+
each asset will have a different file name when it is changed. This way you
|
1061
|
+
don't have to ever manually invalidate any items in your cache. By using a
|
1062
|
+
different unique asset name instead, your users get the latest asset.
|
622
1063
|
|
623
1064
|
Customizing the Pipeline
|
624
1065
|
------------------------
|
625
1066
|
|
626
1067
|
### CSS Compression
|
627
1068
|
|
628
|
-
|
1069
|
+
One of the options for compressing CSS is YUI. The [YUI CSS
|
1070
|
+
compressor](http://yui.github.io/yuicompressor/css.html) provides
|
1071
|
+
minification.
|
629
1072
|
|
630
|
-
The following line enables YUI compression, and requires the `yui-compressor`
|
1073
|
+
The following line enables YUI compression, and requires the `yui-compressor`
|
1074
|
+
gem.
|
631
1075
|
|
632
1076
|
```ruby
|
633
1077
|
config.assets.css_compressor = :yui
|
634
1078
|
```
|
1079
|
+
The other option for compressing CSS if you have the sass-rails gem installed is
|
635
1080
|
|
636
|
-
|
1081
|
+
```ruby
|
1082
|
+
config.assets.css_compressor = :sass
|
1083
|
+
```
|
637
1084
|
|
638
1085
|
### JavaScript Compression
|
639
1086
|
|
640
|
-
Possible options for JavaScript compression are `:closure`, `:uglifier` and
|
1087
|
+
Possible options for JavaScript compression are `:closure`, `:uglifier` and
|
1088
|
+
`:yui`. These require the use of the `closure-compiler`, `uglifier` or
|
1089
|
+
`yui-compressor` gems, respectively.
|
641
1090
|
|
642
|
-
The default Gemfile includes [uglifier](https://github.com/lautis/uglifier).
|
1091
|
+
The default Gemfile includes [uglifier](https://github.com/lautis/uglifier).
|
1092
|
+
This gem wraps [UglifyJS](https://github.com/mishoo/UglifyJS) (written for
|
1093
|
+
NodeJS) in Ruby. It compresses your code by removing white space and comments,
|
1094
|
+
shortening local variable names, and performing other micro-optimizations such
|
1095
|
+
as changing `if` and `else` statements to ternary operators where possible.
|
643
1096
|
|
644
1097
|
The following line invokes `uglifier` for JavaScript compression.
|
645
1098
|
|
@@ -647,13 +1100,21 @@ The following line invokes `uglifier` for JavaScript compression.
|
|
647
1100
|
config.assets.js_compressor = :uglifier
|
648
1101
|
```
|
649
1102
|
|
650
|
-
|
1103
|
+
NOTE: You will need an [ExecJS](https://github.com/rails/execjs#readme)
|
1104
|
+
supported runtime in order to use `uglifier`. If you are using Mac OS X or
|
1105
|
+
Windows you have a JavaScript runtime installed in your operating system.
|
651
1106
|
|
652
|
-
NOTE:
|
1107
|
+
NOTE: The `config.assets.compress` initialization option is no longer used in
|
1108
|
+
Rails 4 to enable either CSS or JavaScript compression. Setting it will have no
|
1109
|
+
effect on the application. Instead, setting `config.assets.css_compressor` and
|
1110
|
+
`config.assets.js_compressor` will control compression of CSS and JavaScript
|
1111
|
+
assets.
|
653
1112
|
|
654
1113
|
### Using Your Own Compressor
|
655
1114
|
|
656
|
-
The compressor config settings for CSS and JavaScript also take any object.
|
1115
|
+
The compressor config settings for CSS and JavaScript also take any object.
|
1116
|
+
This object must have a `compress` method that takes a string as the sole
|
1117
|
+
argument and it must return a string.
|
657
1118
|
|
658
1119
|
```ruby
|
659
1120
|
class Transformer
|
@@ -680,60 +1141,96 @@ This can be changed to something else:
|
|
680
1141
|
config.assets.prefix = "/some_other_path"
|
681
1142
|
```
|
682
1143
|
|
683
|
-
This is a handy option if you are updating an older project that didn't use the
|
1144
|
+
This is a handy option if you are updating an older project that didn't use the
|
1145
|
+
asset pipeline and already uses this path or you wish to use this path for
|
1146
|
+
a new resource.
|
684
1147
|
|
685
1148
|
### X-Sendfile Headers
|
686
1149
|
|
687
|
-
The X-Sendfile header is a directive to the web server to ignore the response
|
1150
|
+
The X-Sendfile header is a directive to the web server to ignore the response
|
1151
|
+
from the application, and instead serve a specified file from disk. This option
|
1152
|
+
is off by default, but can be enabled if your server supports it. When enabled,
|
1153
|
+
this passes responsibility for serving the file to the web server, which is
|
1154
|
+
faster. Have a look at [send_file](http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_file)
|
1155
|
+
on how to use this feature.
|
688
1156
|
|
689
|
-
Apache and
|
1157
|
+
Apache and NGINX support this option, which can be enabled in
|
1158
|
+
`config/environments/production.rb`:
|
690
1159
|
|
691
1160
|
```ruby
|
692
|
-
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for
|
693
|
-
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for
|
1161
|
+
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache
|
1162
|
+
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
|
694
1163
|
```
|
695
1164
|
|
696
|
-
WARNING: If you are upgrading an existing application and intend to use this
|
1165
|
+
WARNING: If you are upgrading an existing application and intend to use this
|
1166
|
+
option, take care to paste this configuration option only into `production.rb`
|
1167
|
+
and any other environments you define with production behavior (not
|
1168
|
+
`application.rb`).
|
1169
|
+
|
1170
|
+
TIP: For further details have a look at the docs of your production web server:
|
1171
|
+
- [Apache](https://tn123.org/mod_xsendfile/)
|
1172
|
+
- [NGINX](http://wiki.nginx.org/XSendfile)
|
697
1173
|
|
698
1174
|
Assets Cache Store
|
699
1175
|
------------------
|
700
1176
|
|
701
|
-
The default Rails cache store will be used by Sprockets to cache assets in
|
1177
|
+
The default Rails cache store will be used by Sprockets to cache assets in
|
1178
|
+
development and production. This can be changed by setting
|
1179
|
+
`config.assets.cache_store`:
|
702
1180
|
|
703
1181
|
```ruby
|
704
1182
|
config.assets.cache_store = :memory_store
|
705
1183
|
```
|
706
1184
|
|
707
|
-
The options accepted by the assets cache store are the same as the application's
|
1185
|
+
The options accepted by the assets cache store are the same as the application's
|
1186
|
+
cache store.
|
708
1187
|
|
709
1188
|
```ruby
|
710
1189
|
config.assets.cache_store = :memory_store, { size: 32.megabytes }
|
711
1190
|
```
|
712
1191
|
|
1192
|
+
To disable the assets cache store:
|
1193
|
+
|
1194
|
+
```ruby
|
1195
|
+
config.assets.configure do |env|
|
1196
|
+
env.cache = ActiveSupport::Cache.lookup_store(:null_store)
|
1197
|
+
end
|
1198
|
+
```
|
1199
|
+
|
713
1200
|
Adding Assets to Your Gems
|
714
1201
|
--------------------------
|
715
1202
|
|
716
1203
|
Assets can also come from external sources in the form of gems.
|
717
1204
|
|
718
|
-
A good example of this is the `jquery-rails` gem which comes with Rails as the
|
1205
|
+
A good example of this is the `jquery-rails` gem which comes with Rails as the
|
1206
|
+
standard JavaScript library gem. This gem contains an engine class which
|
1207
|
+
inherits from `Rails::Engine`. By doing this, Rails is informed that the
|
1208
|
+
directory for this gem may contain assets and the `app/assets`, `lib/assets` and
|
1209
|
+
`vendor/assets` directories of this engine are added to the search path of
|
1210
|
+
Sprockets.
|
719
1211
|
|
720
1212
|
Making Your Library or Gem a Pre-Processor
|
721
1213
|
------------------------------------------
|
722
1214
|
|
723
1215
|
As Sprockets uses [Tilt](https://github.com/rtomayko/tilt) as a generic
|
724
|
-
interface to different templating engines, your gem should just
|
725
|
-
|
726
|
-
|
727
|
-
|
1216
|
+
interface to different templating engines, your gem should just implement the
|
1217
|
+
Tilt template protocol. Normally, you would subclass `Tilt::Template` and
|
1218
|
+
reimplement the `prepare` method, which initializes your template, and the
|
1219
|
+
`evaluate` method, which returns the processed source. The original source is
|
1220
|
+
stored in `data`. Have a look at
|
728
1221
|
[`Tilt::Template`](https://github.com/rtomayko/tilt/blob/master/lib/tilt/template.rb)
|
729
1222
|
sources to learn more.
|
730
1223
|
|
731
1224
|
```ruby
|
732
1225
|
module BangBang
|
733
1226
|
class Template < ::Tilt::Template
|
1227
|
+
def prepare
|
1228
|
+
# Do any initialization here
|
1229
|
+
end
|
1230
|
+
|
734
1231
|
# Adds a "!" to original template.
|
735
1232
|
def evaluate(scope, locals, &block)
|
736
|
-
"#{
|
1233
|
+
"#{data}!"
|
737
1234
|
end
|
738
1235
|
end
|
739
1236
|
end
|
@@ -749,31 +1246,30 @@ Sprockets.register_engine '.bang', BangBang::Template
|
|
749
1246
|
Upgrading from Old Versions of Rails
|
750
1247
|
------------------------------------
|
751
1248
|
|
752
|
-
There are a few issues when upgrading
|
1249
|
+
There are a few issues when upgrading from Rails 3.0 or Rails 2.x. The first is
|
1250
|
+
moving the files from `public/` to the new locations. See [Asset
|
1251
|
+
Organization](#asset-organization) above for guidance on the correct locations
|
1252
|
+
for different file types.
|
753
1253
|
|
754
|
-
Next will be avoiding duplicate JavaScript files. Since jQuery is the default
|
1254
|
+
Next will be avoiding duplicate JavaScript files. Since jQuery is the default
|
1255
|
+
JavaScript library from Rails 3.1 onwards, you don't need to copy `jquery.js`
|
1256
|
+
into `app/assets` and it will be included automatically.
|
755
1257
|
|
756
|
-
The third is updating the various environment files with the correct default
|
1258
|
+
The third is updating the various environment files with the correct default
|
1259
|
+
options.
|
757
1260
|
|
758
1261
|
In `application.rb`:
|
759
1262
|
|
760
1263
|
```ruby
|
761
|
-
# Enable the asset pipeline
|
762
|
-
config.assets.enabled = true
|
763
|
-
|
764
1264
|
# Version of your assets, change this if you want to expire all your assets
|
765
1265
|
config.assets.version = '1.0'
|
766
1266
|
|
767
|
-
# Change the path that assets are served from
|
768
|
-
# config.assets.prefix = "/assets"
|
1267
|
+
# Change the path that assets are served from config.assets.prefix = "/assets"
|
769
1268
|
```
|
770
1269
|
|
771
1270
|
In `development.rb`:
|
772
1271
|
|
773
1272
|
```ruby
|
774
|
-
# Do not compress assets
|
775
|
-
config.assets.compress = false
|
776
|
-
|
777
1273
|
# Expands the lines which load the assets
|
778
1274
|
config.assets.debug = true
|
779
1275
|
```
|
@@ -781,50 +1277,28 @@ config.assets.debug = true
|
|
781
1277
|
And in `production.rb`:
|
782
1278
|
|
783
1279
|
```ruby
|
784
|
-
#
|
785
|
-
config.assets.
|
786
|
-
|
787
|
-
# Choose the compressors to use
|
788
|
-
# config.assets.js_compressor = :uglifier
|
789
|
-
# config.assets.css_compressor = :yui
|
1280
|
+
# Choose the compressors to use (if any) config.assets.js_compressor =
|
1281
|
+
# :uglifier config.assets.css_compressor = :yui
|
790
1282
|
|
791
1283
|
# Don't fallback to assets pipeline if a precompiled asset is missed
|
792
1284
|
config.assets.compile = false
|
793
1285
|
|
794
|
-
# Generate digests for assets URLs.
|
1286
|
+
# Generate digests for assets URLs. This is planned for deprecation.
|
795
1287
|
config.assets.digest = true
|
796
1288
|
|
797
|
-
# Precompile additional assets (application.js, application.css, and all
|
798
|
-
# config.assets.precompile += %w( search.js )
|
1289
|
+
# Precompile additional assets (application.js, application.css, and all
|
1290
|
+
# non-JS/CSS are already added) config.assets.precompile += %w( search.js )
|
799
1291
|
```
|
800
1292
|
|
801
|
-
|
1293
|
+
Rails 4 no longer sets default config values for Sprockets in `test.rb`, so
|
1294
|
+
`test.rb` now requires Sprockets configuration. The old defaults in the test
|
1295
|
+
environment are: `config.assets.compile = true`, `config.assets.compress = false`,
|
1296
|
+
`config.assets.debug = false` and `config.assets.digest = false`.
|
802
1297
|
|
803
1298
|
The following should also be added to `Gemfile`:
|
804
1299
|
|
805
1300
|
```ruby
|
806
|
-
|
807
|
-
|
808
|
-
|
809
|
-
gem 'sass-rails', "~> 3.2.3"
|
810
|
-
gem 'coffee-rails', "~> 3.2.1"
|
811
|
-
gem 'uglifier'
|
812
|
-
end
|
813
|
-
```
|
814
|
-
|
815
|
-
If you use the `assets` group with Bundler, please make sure that your `config/application.rb` has the following Bundler require statement:
|
816
|
-
|
817
|
-
```ruby
|
818
|
-
# If you precompile assets before deploying to production, use this line
|
819
|
-
Bundler.require *Rails.groups(:assets => %w(development test))
|
820
|
-
# If you want your assets lazily compiled in production, use this line
|
821
|
-
# Bundler.require(:default, :assets, Rails.env)
|
822
|
-
```
|
823
|
-
|
824
|
-
Instead of the generated version:
|
825
|
-
|
826
|
-
```ruby
|
827
|
-
# Require the gems listed in Gemfile, including any gems
|
828
|
-
# you've limited to :test, :development, or :production.
|
829
|
-
Bundler.require(:default, Rails.env)
|
1301
|
+
gem 'sass-rails', "~> 3.2.3"
|
1302
|
+
gem 'coffee-rails', "~> 3.2.1"
|
1303
|
+
gem 'uglifier'
|
830
1304
|
```
|