diff options
Diffstat (limited to 'guides')
-rw-r--r-- | guides/code/getting_started/Gemfile | 2 | ||||
-rw-r--r-- | guides/source/4_0_release_notes.md | 41 | ||||
-rw-r--r-- | guides/source/_welcome.html.erb | 2 | ||||
-rw-r--r-- | guides/source/action_mailer_basics.md | 2 | ||||
-rw-r--r-- | guides/source/active_record_querying.md | 14 | ||||
-rw-r--r-- | guides/source/active_record_validations.md | 2 | ||||
-rw-r--r-- | guides/source/active_support_core_extensions.md | 65 | ||||
-rw-r--r-- | guides/source/asset_pipeline.md | 766 | ||||
-rw-r--r-- | guides/source/command_line.md | 11 | ||||
-rw-r--r-- | guides/source/contributing_to_ruby_on_rails.md | 2 | ||||
-rw-r--r-- | guides/source/debugging_rails_applications.md | 35 | ||||
-rw-r--r-- | guides/source/development_dependencies_install.md | 50 | ||||
-rw-r--r-- | guides/source/engines.md | 7 | ||||
-rw-r--r-- | guides/source/getting_started.md | 4 | ||||
-rw-r--r-- | guides/source/i18n.md | 4 | ||||
-rw-r--r-- | guides/source/layouts_and_rendering.md | 6 | ||||
-rw-r--r-- | guides/source/plugins.md | 8 | ||||
-rw-r--r-- | guides/source/rails_on_rack.md | 2 | ||||
-rw-r--r-- | guides/source/upgrading_ruby_on_rails.md | 6 |
19 files changed, 716 insertions, 313 deletions
diff --git a/guides/code/getting_started/Gemfile b/guides/code/getting_started/Gemfile index acd2ed5160..3d57012901 100644 --- a/guides/code/getting_started/Gemfile +++ b/guides/code/getting_started/Gemfile @@ -31,7 +31,7 @@ end gem 'jbuilder', '~> 1.2' # To use ActiveModel has_secure_password -# gem 'bcrypt-ruby', '~> 3.0.0' +# gem 'bcrypt-ruby', '~> 3.1.0' # Use unicorn as the app server # gem 'unicorn' diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md index 66e26c63cb..8be7a86d20 100644 --- a/guides/source/4_0_release_notes.md +++ b/guides/source/4_0_release_notes.md @@ -50,10 +50,47 @@ $ ruby /path/to/rails/railties/bin/rails new myapp --dev Major Features -------------- -TODO. Give a list and then talk about each of them briefly. We can point to relevant code commits or documentation from these sections. - [![Rails 4.0](images/rails4_features.png)](http://guides.rubyonrails.org/images/rails4_features.png) +### Upgrade + + * **Ruby 1.9.3** ([commit](https://github.com/rails/rails/commit/a0380e808d3dbd2462df17f5d3b7fcd8bd812496)) - Ruby 2.0 preferred; 1.9.3+ required + * **[New deprecation policy](http://www.youtube.com/watch?v=z6YgD6tVPQs)** - Deprecated features are warnings in Rails 4.0 and will be removed in Rails 4.1. + * **ActionPack page and action caching** ([commit](https://github.com/rails/rails/commit/b0a7068564f0c95e7ef28fc39d0335ed17d93e90)) - Page and action caching are extracted to a separate gem. Page and action caching requires too much manual intervention (manually expiring caches when the underlying model objects are updated). Instead, use Russian doll caching. + * **ActiveRecord observers** ([commit](https://github.com/rails/rails/commit/ccecab3ba950a288b61a516bf9b6962e384aae0b)) - Observers are extracted to a separate gem. Observers are only needed for page and action caching, and can lead to spaghetti code. + * **ActiveRecord session store** ([commit](https://github.com/rails/rails/commit/0ffe19056c8e8b2f9ae9d487b896cad2ce9387ad)) - The ActiveRecord session store is extracted to a separate gem. Storing sessions in SQL is costly. Instead, use cookie sessions, memcache sessions, or a custom session store. + * **ActiveModel mass assignment protection** ([commit](https://github.com/rails/rails/commit/f8c9a4d3e88181cee644f91e1342bfe896ca64c6)) - Rails 3 mass assignment protection is deprecated. Instead, use strong parameters. + * **ActiveResource** ([commit](https://github.com/rails/rails/commit/f1637bf2bb00490203503fbd943b73406e043d1d)) - ActiveResource is extracted to a separate gem. ActiveResource was not widely used. + * **vendor/plugins removed** ([commit](https://github.com/rails/rails/commit/853de2bd9ac572735fa6cf59fcf827e485a231c3)) - Use a Gemfile to manage installed gems. + +### ActionPack + + * **Strong parameters** ([commit](https://github.com/rails/rails/commit/a8f6d5c6450a7fe058348a7f10a908352bb6c7fc)) - Only allow whitelisted parameters to update model objects (`params.permit(:title, :text)`). + * **Routing concerns** ([commit](https://github.com/rails/rails/commit/0dd24728a088fcb4ae616bb5d62734aca5276b1b)) - In the routing DSL, factor out common subroutes (`comments` from `/posts/1/comments` and `/videos/1/comments`). + * **ActionController::Live** ([commit](https://github.com/rails/rails/commit/af0a9f9eefaee3a8120cfd8d05cbc431af376da3)) - Stream JSON with `response.stream`. + * **Declarative ETags** ([commit](https://github.com/rails/rails/commit/ed5c938fa36995f06d4917d9543ba78ed506bb8d)) - Add controller-level etag additions that will be part of the action etag computation + * **[Russian doll caching](http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works)** ([commit](https://github.com/rails/rails/commit/4154bf012d2bec2aae79e4a49aa94a70d3e91d49)) - Cache nested fragments of views. Each fragment expires based on a set of dependencies (a cache key). The cache key is usually a template version number and a model object. + * **Turbolinks** ([commit](https://github.com/rails/rails/commit/e35d8b18d0649c0ecc58f6b73df6b3c8d0c6bb74)) - Serve only one initial HTML page. When the user navigates to another page, use pushState to update the URL and use AJAX to update the title and body. + * **Decouple ActionView from ActionController** ([commit](https://github.com/rails/rails/commit/78b0934dd1bb84e8f093fb8ef95ca99b297b51cd)) - ActionView was decoupled from ActionPack and will be moved to a separated gem in Rails 4.1. + * **Do not depend on ActiveModel** ([commit](https://github.com/rails/rails/commit/166dbaa7526a96fdf046f093f25b0a134b277a68)) - ActionPack no longer depends on ActiveModel. + +### General + + * **ActiveModel::Model** ([commit](https://github.com/rails/rails/commit/3b822e91d1a6c4eab0064989bbd07aae3a6d0d08)) - `ActiveModel::Model`, a mixin to make normal Ruby objects to work with ActionPack out of box (ex. for `form_for`) + * **New scope API** ([commit](https://github.com/rails/rails/commit/50cbc03d18c5984347965a94027879623fc44cce)) - Scopes must always use callables. + * **Schema cache dump** ([commit](https://github.com/rails/rails/commit/5ca4fc95818047108e69e22d200e7a4a22969477)) - To improve Rails boot time, instead of loading the schema directly from the database, load the schema from a dump file. + * **Support for specifying transaction isolation level** ([commit](https://github.com/rails/rails/commit/392eeecc11a291e406db927a18b75f41b2658253)) - Choose whether repeatable reads or improved performance (less locking) is more important. + * **Dalli** ([commit](https://github.com/rails/rails/commit/82663306f428a5bbc90c511458432afb26d2f238)) - Use Dalli memcache client for the memcache store. + * **Notifications start & finish** ([commit](https://github.com/rails/rails/commit/f08f8750a512f741acb004d0cebe210c5f949f28)) - Active Support instrumentation reports start and finish notifications to subscribers. + * **Thread safe by default** ([commit](https://github.com/rails/rails/commit/5d416b907864d99af55ebaa400fff217e17570cd)) - Rails can run in threaded app servers without additional configuration. Note: Check that the gems you are using are threadsafe. + * **PATCH verb** ([commit](https://github.com/rails/rails/commit/eed9f2539e3ab5a68e798802f464b8e4e95e619e)) - In Rails, PATCH replaces PUT. PATCH is used for partial updates of resources. + +### Security + + * **match do not catch all** ([commit](https://github.com/rails/rails/commit/90d2802b71a6e89aedfe40564a37bd35f777e541)) - In the routing DSL, match requires the HTTP verb or verbs to be specified. + * **html entities escaped by default** ([commit](https://github.com/rails/rails/commit/5f189f41258b83d49012ec5a0678d827327e7543)) - Strings rendered in erb are escaped unless wrapped with `raw` or `html_safe` is called. + * **New security headers** ([commit](https://github.com/rails/rails/commit/6794e92b204572d75a07bd6413bdae6ae22d5a82)) - Rails sends the following headers with every HTTP request: `X-Frame-Options` (prevents clickjacking by forbidding the browser from embedding the page in a frame), `X-XSS-Protection` (asks the browser to halt script injection) and `X-Content-Type-Options` (prevents the browser from opening a jpeg as an exe). + Extraction of features to gems --------------------------- diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb index 9210c40c17..0a0a958e30 100644 --- a/guides/source/_welcome.html.erb +++ b/guides/source/_welcome.html.erb @@ -15,7 +15,7 @@ </p> <% end %> <p> - The guides for Rails 3.2.x are available at <a href="http://guides.rubyonrails.org/v3.2.13/">http://guides.rubyonrails.org/v3.2.13/</a>. + The guides for Rails 3.2.x are available at <a href="http://guides.rubyonrails.org/v3.2.14/">http://guides.rubyonrails.org/v3.2.14/</a>. </p> <p> The guides for Rails 2.3.x are available at <a href="http://guides.rubyonrails.org/v2.3.11/">http://guides.rubyonrails.org/v2.3.11/</a>. diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md index 87a08e8661..bf34799eb3 100644 --- a/guides/source/action_mailer_basics.md +++ b/guides/source/action_mailer_basics.md @@ -378,7 +378,7 @@ Just like with controller views, use `yield` to render the view inside the layout. You can also pass in a `layout: 'layout_name'` option to the render call inside -the format block to specify different layouts for different actions: +the format block to specify different layouts for different formats: ```ruby class UserMailer < ActionMailer::Base diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md index 18a5342a2f..7fe9b8b4af 100644 --- a/guides/source/active_record_querying.md +++ b/guides/source/active_record_querying.md @@ -514,7 +514,13 @@ SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5)) Post.where.not(author: author) ``` -In other words, this query can be generated by calling `where` with no argument, then immediately chain with `not` passing `where` conditions. +In other words, this query can be generated by calling `where` with no argument, +then immediately chain with `not` passing `where` conditions. This will generate +SQL code like this: + +```sql +SELECT * FROM posts WHERE (author_id != 1) +``` Ordering -------- @@ -543,11 +549,11 @@ Client.order("orders_count ASC, created_at DESC") Client.order("orders_count ASC", "created_at DESC") ``` -If you want to call `order` multiple times e.g. in different context, new order will prepend previous one +If you want to call `order` multiple times e.g. in different context, new order will append previous one ```ruby Client.order("orders_count ASC").order("created_at DESC") -# SELECT * FROM clients ORDER BY created_at DESC, orders_count ASC +# SELECT * FROM clients ORDER BY orders_count ASC, created_at DESC ``` Selecting Specific Fields @@ -711,7 +717,7 @@ Post.order('id DESC').limit(20).unscope(:order, :limit) = Post.all You can additionally unscope specific where clauses. For example: ```ruby -Post.where(id: 10).limit(1).unscope(:where, :limit).order('id DESC') = Post.order('id DESC') +Post.where(id: 10).limit(1).unscope({ where: :id }, :limit).order('id DESC') = Post.order('id DESC') ``` ### `only` diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md index 3bfc600e7c..d95b587e78 100644 --- a/guides/source/active_record_validations.md +++ b/guides/source/active_record_validations.md @@ -121,7 +121,7 @@ database only if the object is valid: The bang versions (e.g. `save!`) raise an exception if the record is invalid. The non-bang versions don't, `save` and `update` return `false`, -`create` just return the objects. +`create` just returns the object. ### Skipping Validations diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 7f65d920df..1915252122 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -96,12 +96,13 @@ INFO: The predicate for strings uses the Unicode-aware character class `[:space: WARNING: Note that numbers are not mentioned. In particular, 0 and 0.0 are **not** blank. -For example, this method from `ActionDispatch::Session::AbstractStore` uses `blank?` for checking whether a session key is present: +For example, this method from `ActionController::HttpAuthentication::Token::ControllerMethods` uses `blank?` for checking whether a token is present: ```ruby -def ensure_session_key! - if @key.blank? - raise ArgumentError, 'A key is required...' +def authenticate(controller, &login_procedure) + token, options = token_and_options(controller.request) + unless token.blank? + login_procedure.call(token, options) end end ``` @@ -420,9 +421,9 @@ NOTE: Defined in `active_support/core_ext/object/with_options.rb`. ### JSON support -Active Support provides a better implemention of `to_json` than the +json+ gem ordinarily provides for Ruby objects. This is because some classes, like +Hash+ and +OrderedHash+ needs special handling in order to provide a proper JSON representation. +Active Support provides a better implemention of `to_json` than the `json` gem ordinarily provides for Ruby objects. This is because some classes, like `Hash` and `OrderedHash` needs special handling in order to provide a proper JSON representation. -Active Support also provides an implementation of `as_json` for the <tt>Process::Status</tt> class. +Active Support also provides an implementation of `as_json` for the `Process::Status` class. NOTE: Defined in `active_support/core_ext/object/to_json.rb`. @@ -1987,7 +1988,7 @@ Produce a string representation of a number in human-readable words: 1234567890123456.to_s(:human) # => "1.23 Quadrillion" ``` -NOTE: Defined in `active_support/core_ext/numeric/formatting.rb`. +NOTE: Defined in `active_support/core_ext/numeric/conversions.rb`. Extensions to `Integer` ----------------------- @@ -2045,7 +2046,7 @@ BigDecimal.new(5.00, 6).to_s # => "5.0" ### `to_formatted_s` -Te method `to_formatted_s` provides a default specifier of "F". This means that a simple call to `to_formatted_s` or `to_s` will result in floating point representation instead of engineering notation: +The method `to_formatted_s` provides a default specifier of "F". This means that a simple call to `to_formatted_s` or `to_s` will result in floating point representation instead of engineering notation: ```ruby BigDecimal.new(5.00, 6).to_formatted_s # => "5.0" @@ -2432,7 +2433,7 @@ dup[1][2] = 4 array[1][2] == nil # => true ``` -NOTE: Defined in `active_support/core_ext/array/deep_dup.rb`. +NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`. ### Grouping @@ -2658,45 +2659,7 @@ hash[:b][:e] == nil # => true hash[:b][:d] == [3, 4] # => true ``` -NOTE: Defined in `active_support/core_ext/hash/deep_dup.rb`. - -### Diffing - -The method `diff` returns a hash that represents a diff of the receiver and the argument with the following logic: - -* Pairs `key`, `value` that exist in both hashes do not belong to the diff hash. - -* If both hashes have `key`, but with different values, the pair in the receiver wins. - -* The rest is just merged. - -```ruby -{a: 1}.diff(a: 1) -# => {}, first rule - -{a: 1}.diff(a: 2) -# => {:a=>1}, second rule - -{a: 1}.diff(b: 2) -# => {:a=>1, :b=>2}, third rule - -{a: 1, b: 2, c: 3}.diff(b: 1, c: 3, d: 4) -# => {:a=>1, :b=>2, :d=>4}, all rules - -{}.diff({}) # => {} -{a: 1}.diff({}) # => {:a=>1} -{}.diff(a: 1) # => {:a=>1} -``` - -An important property of this diff hash is that you can retrieve the original hash by applying `diff` twice: - -```ruby -hash.diff(hash2).diff(hash2) == hash -``` - -Diffing hashes may be useful for error messages related to expected option hashes for example. - -NOTE: Defined in `active_support/core_ext/hash/diff.rb`. +NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`. ### Working with Keys @@ -3831,13 +3794,13 @@ def default_helper_module! module_path = module_name.underscore helper module_path rescue MissingSourceFile => e - raise e unless e.is_missing? "#{module_path}_helper" + raise e unless e.is_missing? "helpers/#{module_path}_helper" rescue NameError => e raise e unless e.missing_name? "#{module_name}Helper" end ``` -NOTE: Defined in `active_support/core_ext/name_error.rb`. +NOTE: Defined in `actionpack/lib/abstract_controller/helpers.rb`. Extensions to `LoadError` ------------------------- @@ -3860,4 +3823,4 @@ rescue NameError => e end ``` -NOTE: Defined in `active_support/core_ext/load_error.rb`. +NOTE: Defined in `actionpack/lib/abstract_controller/helpers.rb`. diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index 6c4d7fe255..7334e8b843 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -5,9 +5,9 @@ This guide covers the asset pipeline. After reading this guide, you will know: -* How to understand what the asset pipeline is and what it does. +* What the asset pipeline is and what it does. * How to properly organize your application assets. -* How to understand the benefits of the asset pipeline. +* The benefits of the asset pipeline. * How to add a pre-processor to the pipeline. * How to package assets with a gem. @@ -16,44 +16,97 @@ After reading this guide, you will know: What is the Asset Pipeline? --------------------------- -The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB. +The asset pipeline provides a framework to concatenate and minify or compress +JavaScript and CSS assets. It also adds the ability to write these assets in +other languages and pre-processors such as CoffeeScript, Sass and ERB. -Making the asset pipeline a core feature of Rails means that all developers can benefit from the power of having their assets pre-processed, compressed and minified by one central library, Sprockets. This is part of Rails' "fast by default" strategy as outlined by DHH in his keynote at RailsConf 2011. +The asset pipeline is technically no longer a core feature of Rails 4, it has +been extracted out of the framework into the +[sprockets-rails](https://github.com/rails/sprockets-rails) gem. -The asset pipeline is enabled by default. It can be disabled in `config/application.rb` by putting this line inside the application class definition: +The asset pipeline is enabled by default. + +You can disable the asset pipeline while creating a new application by +passing the `--skip-sprockets` option. + +```bash +rails new appname --skip-sprockets +``` + +Rails 4 automatically adds the `sass-rails`, `coffee-rails` and `uglifier` +gems to your Gemfile, which are used by Sprockets for asset compression: ```ruby -config.assets.enabled = false +gem 'sass-rails' +gem 'uglifier' +gem 'coffee-rails' ``` -You can also disable the asset pipeline while creating a new application by passing the `--skip-sprockets` option. +Using the `--skip-sprockets` option will prevent Rails 4 from adding +`sass-rails` and `uglifier` to Gemfile, so if you later want to enable +the asset pipeline you will have to add those gems to your Gemfile. Also, +creating an application with the `--skip-sprockets` option will generate +a slightly different `config/application.rb` file, with a require statement +for the sprockets railtie that is commented-out. You will have to remove +the comment operator on that line to later enable the asset pipeline: -```bash -rails new appname --skip-sprockets +```ruby +# require "sprockets/railtie" ``` -You should use the defaults for all new applications unless you have a specific reason to avoid the asset pipeline. +To set asset compression methods, set the appropriate configuration options +in `production.rb` - `config.assets.css_compressor` for your CSS and +`config.assets.js_compressor` for your Javascript: +```ruby +config.assets.css_compressor = :yui +config.assets.js_compressor = :uglify +``` -### Main Features +NOTE: The `sass-rails` gem is automatically used for CSS compression if included +in Gemfile and no `config.assets.css_compressor` option is set. -The first feature of the pipeline is to concatenate assets. This is important in a production environment, because it can reduce the number of requests that a browser makes to render a web page. Web browsers are limited in the number of requests that they can make in parallel, so fewer requests can mean faster loading for your application. -Rails 2.x introduced the ability to concatenate JavaScript and CSS assets by placing `cache: true` at the end of the `javascript_include_tag` and `stylesheet_link_tag` methods. But this technique has some limitations. For example, it cannot generate the caches in advance, and it is not able to transparently include assets provided by third-party libraries. +### Main Features -Starting with version 3.1, Rails defaults to concatenating all JavaScript files into one master `.js` file and all CSS files into one master `.css` file. As you'll learn later in this guide, you can customize this strategy to group files any way you like. In production, Rails inserts an MD5 fingerprint into each filename so that the file is cached by the web browser. You can invalidate the cache by altering this fingerprint, which happens automatically whenever you change the file contents. +The first feature of the pipeline is to concatenate assets, which can reduce the +number of requests that a browser makes to render a web page. Web browsers are +limited in the number of requests that they can make in parallel, so fewer +requests can mean faster loading for your application. -The second feature of the asset pipeline is asset minification or compression. For CSS files, this is done by removing whitespace and comments. For JavaScript, more complex processes can be applied. You can choose from a set of built in options or specify your own. +Sprockets concatenates all JavaScript files into one master `.js` file and all +CSS files into one master `.css` file. As you'll learn later in this guide, you +can customize this strategy to group files any way you like. In production, +Rails inserts an MD5 fingerprint into each filename so that the file is cached +by the web browser. You can invalidate the cache by altering this fingerprint, +which happens automatically whenever you change the file contents. -The third feature of the asset pipeline is that it allows coding assets via a higher-level language, with precompilation down to the actual assets. Supported languages include Sass for CSS, CoffeeScript for JavaScript, and ERB for both by default. +The second feature of the asset pipeline is asset minification or compression. +For CSS files, this is done by removing whitespace and comments. For JavaScript, +more complex processes can be applied. You can choose from a set of built in +options or specify your own. + +The third feature of the asset pipeline is it allows coding assets via a +higher-level language, with precompilation down to the actual assets. Supported +languages include Sass for CSS, CoffeeScript for JavaScript, and ERB for both by +default. ### What is Fingerprinting and Why Should I Care? -Fingerprinting is a technique that makes the name of a file dependent on the contents of the file. When the file contents change, the filename is also changed. For content that is static or infrequently changed, this provides an easy way to tell whether two versions of a file are identical, even across different servers or deployment dates. +Fingerprinting is a technique that makes the name of a file dependent on the +contents of the file. When the file contents change, the filename is also +changed. For content that is static or infrequently changed, this provides an +easy way to tell whether two versions of a file are identical, even across +different servers or deployment dates. -When a filename is unique and based on its content, HTTP headers can be set to encourage caches everywhere (whether at CDNs, at ISPs, in networking equipment, or in web browsers) to keep their own copy of the content. When the content is updated, the fingerprint will change. This will cause the remote clients to request a new copy of the content. This is generally known as _cache busting_. +When a filename is unique and based on its content, HTTP headers can be set to +encourage caches everywhere (whether at CDNs, at ISPs, in networking equipment, +or in web browsers) to keep their own copy of the content. When the content is +updated, the fingerprint will change. This will cause the remote clients to +request a new copy of the content. This is generally known as _cache busting_. -The technique that Rails uses for fingerprinting is to insert a hash of the content into the name, usually at the end. For example a CSS file `global.css` could be renamed with an MD5 digest of its contents: +The technique sprockets uses for fingerprinting is to insert a hash of the +content into the name, usually at the end. For example a CSS file `global.css` ``` global-908e25f4bf641868d8683022a5b62f54.css @@ -61,7 +114,8 @@ global-908e25f4bf641868d8683022a5b62f54.css This is the strategy adopted by the Rails asset pipeline. -Rails' old strategy was to append a date-based query string to every asset linked with a built-in helper. In the source the generated code looked like this: +Rails' old strategy was to append a date-based query string to every asset linked +with a built-in helper. In the source the generated code looked like this: ``` /stylesheets/global.css?1309495796 @@ -69,68 +123,126 @@ Rails' old strategy was to append a date-based query string to every asset linke The query string strategy has several disadvantages: -1. **Not all caches will reliably cache content where the filename only differs by query parameters**<br> - [Steve Souders recommends](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/), "...avoiding a querystring for cacheable resources". He found that in this case 5-20% of requests will not be cached. Query strings in particular do not work at all with some CDNs for cache invalidation. +1. **Not all caches will reliably cache content where the filename only differs by +query parameters**<br> + [Steve Souders recommends](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/), + "...avoiding a querystring for cacheable resources". He found that in this +case 5-20% of requests will not be cached. Query strings in particular do not +work at all with some CDNs for cache invalidation. 2. **The file name can change between nodes in multi-server environments.**<br> - The default query string in Rails 2.x is based on the modification time of the files. When assets are deployed to a cluster, there is no guarantee that the timestamps will be the same, resulting in different values being used depending on which server handles the request. + The default query string in Rails 2.x is based on the modification time of +the files. When assets are deployed to a cluster, there is no guarantee that the +timestamps will be the same, resulting in different values being used depending +on which server handles the request. + 3. **Too much cache invalidation**<br> - 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. + 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. -Fingerprinting fixes these problems by avoiding query strings, and by ensuring that filenames are consistent based on their content. +Fingerprinting fixes these problems by avoiding query strings, and by ensuring +that filenames are consistent based on their content. -Fingerprinting is enabled by default for production and disabled for all other environments. You can enable or disable it in your configuration through the `config.assets.digest` option. +Fingerprinting is enabled by default for production and disabled for all other +environments. You can enable or disable it in your configuration through the +`config.assets.digest` option. More reading: * [Optimize caching](http://code.google.com/speed/page-speed/docs/caching.html) -* [Revving Filenames: don’t use querystring](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/) +* [Revving Filenames: don’t use +* querystring](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/) How to Use the Asset Pipeline ----------------------------- -In previous versions of Rails, all assets were located in subdirectories of `public` such as `images`, `javascripts` and `stylesheets`. With the asset pipeline, the preferred location for these assets is now the `app/assets` directory. Files in this directory are served by the Sprockets middleware included in the sprockets gem. +In previous versions of Rails, all assets were located in subdirectories of +`public` such as `images`, `javascripts` and `stylesheets`. With the asset +pipeline, the preferred location for these assets is now the `app/assets` +directory. Files in this directory are served by the Sprockets middleware. -Assets can still be placed in the `public` hierarchy. Any assets under `public` will be served as static files by the application or web server. You should use `app/assets` for files that must undergo some pre-processing before they are served. +Assets can still be placed in the `public` hierarchy. Any assets under `public` +will be served as static files by the application or web server. You should use +`app/assets` for files that must undergo some pre-processing before they are +served. -In production, Rails precompiles these files to `public/assets` by default. The precompiled copies are then served as static assets by the web server. The files in `app/assets` are never served directly in production. +In production, Rails precompiles these files to `public/assets` by default. The +precompiled copies are then served as static assets by the web server. The files +in `app/assets` are never served directly in production. ### Controller Specific Assets -When you generate a scaffold or a controller, Rails also generates a JavaScript file (or CoffeeScript file if the `coffee-rails` gem is in the `Gemfile`) and a Cascading Style Sheet file (or SCSS file if `sass-rails` is in the `Gemfile`) for that controller. - -For example, if you generate a `ProjectsController`, Rails will also add a new file at `app/assets/javascripts/projects.js.coffee` and another at `app/assets/stylesheets/projects.css.scss`. By default these files will be ready to use by your application immediately using the `require_tree` directive. See [Manifest Files and Directives](#manifest-files-and-directives) for more details on require_tree. - -You can also opt to include controller specific stylesheets and JavaScript files only in their respective controllers using the following: `<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag params[:controller] %>`. Ensure that you are not using the `require_tree` directive though, as this will result in your assets being included more than once. - -WARNING: When using asset precompilation (the production default), you will need to ensure that your controller assets will be precompiled when loading them on a per page basis. By default .coffee and .scss files will not be precompiled on their own. This will result in false positives during development as these files will work just fine since assets will be compiled on the fly. When running in production however, you will see 500 errors since live compilation is turned off by default. See [Precompiling Assets](#precompiling-assets) for more information on how precompiling works. - -NOTE: You must have an ExecJS supported runtime in order to use CoffeeScript. If you are using Mac OS X or Windows you have a JavaScript runtime installed in your operating system. Check [ExecJS](https://github.com/sstephenson/execjs#readme) documentation to know all supported JavaScript runtimes. - -You can also disable the generation of asset files when generating a controller by adding the following to your `config/application.rb` configuration: +When you generate a scaffold or a controller, Rails also generates a JavaScript +file (or CoffeeScript file if the `coffee-rails` gem is in the `Gemfile`) and a +Cascading Style Sheet file (or SCSS file if `sass-rails` is in the `Gemfile`) +for that controller. Additionally, when generating a scaffold, Rails generates +the file scaffolds.css (or scaffolds.css.scss if `sass-rails` is in the +`Gemfile`.) + +For example, if you generate a `ProjectsController`, Rails will also add a new +file at `app/assets/javascripts/projects.js.coffee` and another at +`app/assets/stylesheets/projects.css.scss`. By default these files will be ready +to use by your application immediately using the `require_tree` directive. See +[Manifest Files and Directives](#manifest-files-and-directives) for more details +on require_tree. + +You can also opt to include controller specific stylesheets and JavaScript files +only in their respective controllers using the following: + +`<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag +params[:controller] %>` + +When doing this, ensure you are not using the `require_tree` directive, as that +will result in your assets being included more than once. + +WARNING: When using asset precompilation, you will need to ensure that your +controller assets will be precompiled when loading them on a per page basis. By +default .coffee and .scss files will not be precompiled on their own. This will +result in false positives during development as these files will work just fine +since assets are compiled on the fly in development mode. When running in +production, however, you will see 500 errors since live compilation is turned +off by default. See [Precompiling Assets](#precompiling-assets) for more +information on how precompiling works. + +NOTE: You must have an ExecJS supported runtime in order to use CoffeeScript. +If you are using Mac OS X or Windows, you have a JavaScript runtime installed in +your operating system. Check +[ExecJS](https://github.com/sstephenson/execjs#readme) documentation to know all +supported JavaScript runtimes. + +You can also disable generation of controller specific asset files by adding the +following to your `config/application.rb` configuration: ```ruby -config.generators do |g| - g.assets false -end + config.generators do |g| + g.assets false + end ``` ### Asset Organization -Pipeline assets can be placed inside an application in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. +Pipeline assets can be placed inside an application in one of three locations: +`app/assets`, `lib/assets` or `vendor/assets`. -* `app/assets` is for assets that are owned by the application, such as custom images, JavaScript files or stylesheets. +* `app/assets` is for assets that are owned by the application, such as custom +images, JavaScript files or stylesheets. -* `lib/assets` is for your own libraries' code that doesn't really fit into the scope of the application or those libraries which are shared across applications. +* `lib/assets` is for your own libraries' code that doesn't really fit into the +scope of the application or those libraries which are shared across applications. -* `vendor/assets` is for assets that are owned by outside entities, such as code for JavaScript plugins and CSS frameworks. +* `vendor/assets` is for assets that are owned by outside entities, such as +code for JavaScript plugins and CSS frameworks. #### Search Paths -When a file is referenced from a manifest or a helper, Sprockets searches the three default asset locations for it. +When a file is referenced from a manifest or a helper, Sprockets searches the +three default asset locations for it. -The default locations are: `app/assets/images` and the subdirectories `javascripts` and `stylesheets` in all three asset locations, but these subdirectories are not special. Any path under `assets/*` will be searched. +The default locations are: the `images`, `javascripts` and `stylesheets` +directories under the `apps/assets` folder, but these subdirectories +are not special - any path under `assets/*` will be searched. For example, these files: @@ -162,72 +274,113 @@ is referenced as: //= require sub/something ``` -You can view the search path by inspecting `Rails.application.config.assets.paths` in the Rails console. +You can view the search path by inspecting +`Rails.application.config.assets.paths` in the Rails console. -Besides the standard `assets/*` paths, additional (fully qualified) paths can be added to the pipeline in `config/application.rb`. For example: +Besides the standard `assets/*` paths, additional (fully qualified) paths can be +added to the pipeline in `config/application.rb`. For example: ```ruby config.assets.paths << Rails.root.join("lib", "videoplayer", "flash") ``` -Paths are traversed in the order that they occur in the search path. By default, this means the files in `app/assets` take precedence, and will mask corresponding paths in `lib` and `vendor`. +Paths are traversed in the order they occur in the search path. By default, +this means the files in `app/assets` take precedence, and will mask +corresponding paths in `lib` and `vendor`. -It is important to note that files you want to reference outside a manifest must be added to the precompile array or they will not be available in the production environment. +It is important to note that files you want to reference outside a manifest must +be added to the precompile array or they will not be available in the production +environment. #### Using Index Files -Sprockets uses files named `index` (with the relevant extensions) for a special purpose. +Sprockets uses files named `index` (with the relevant extensions) for a special +purpose. -For example, if you have a jQuery library with many modules, which is stored in `lib/assets/library_name`, the file `lib/assets/library_name/index.js` serves as the manifest for all files in this library. This file could include a list of all the required files in order, or a simple `require_tree` directive. +For example, if you have a jQuery library with many modules, which is stored in +`lib/assets/library_name`, the file `lib/assets/library_name/index.js` serves as +the manifest for all files in this library. This file could include a list of +all the required files in order, or a simple `require_tree` directive. -The library as a whole can be accessed in the site's application manifest like so: +The library as a whole can be accessed in the application manifest like so: ```js //= require library_name ``` -This simplifies maintenance and keeps things clean by allowing related code to be grouped before inclusion elsewhere. +This simplifies maintenance and keeps things clean by allowing related code to +be grouped before inclusion elsewhere. ### Coding Links to Assets -Sprockets does not add any new methods to access your assets - you still use the familiar `javascript_include_tag` and `stylesheet_link_tag`. +Sprockets does not add any new methods to access your assets - you still use the +familiar `javascript_include_tag` and `stylesheet_link_tag`: ```erb -<%= stylesheet_link_tag "application" %> +<%= stylesheet_link_tag "application", media: "all" %> <%= javascript_include_tag "application" %> ``` -In regular views you can access images in the `assets/images` directory like this: +If using the turbolinks gem, which is included by default in Rails 4, then +include the 'data-turbolinks-track' option which causes turbolinks to check if +an asset has been updated and if so loads it into the page: + +```erb +<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %> +<%= javascript_include_tag "application", "data-turbolinks-track" => true %> +``` + +In regular views you can access images in the `public/assets/images` directory +like this: ```erb <%= image_tag "rails.png" %> ``` -Provided that the pipeline is enabled within your application (and not disabled in the current environment context), this file is served by Sprockets. If a file exists at `public/assets/rails.png` it is served by the web server. +Provided that the pipeline is enabled within your application (and not disabled +in the current environment context), this file is served by Sprockets. If a file +exists at `public/assets/rails.png` it is served by the web server. -Alternatively, a request for a file with an MD5 hash such as `public/assets/rails-af27b6a414e6da00003503148be9b409.png` is treated the same way. How these hashes are generated is covered in the [In Production](#in-production) section later on in this guide. +Alternatively, a request for a file with an MD5 hash such as +`public/assets/rails-af27b6a414e6da00003503148be9b409.png` is treated the same +way. How these hashes are generated is covered in the [In +Production](#in-production) section later on in this guide. -Sprockets will also look through the paths specified in `config.assets.paths` which includes the standard application paths and any path added by Rails engines. +Sprockets will also look through the paths specified in `config.assets.paths`, +which includes the standard application paths and any paths added by Rails +engines. -Images can also be organized into subdirectories if required, and they can be accessed by specifying the directory's name in the tag: +Images can also be organized into subdirectories if required, and then can be +accessed by specifying the directory's name in the tag: ```erb <%= image_tag "icons/rails.png" %> ``` -WARNING: If you're precompiling your assets (see [In Production](#in-production) below), linking to an asset that does not exist will raise an exception in the calling page. This includes linking to a blank string. As such, be careful using `image_tag` and the other helpers with user-supplied data. +WARNING: If you're precompiling your assets (see [In Production](#in-production) +below), linking to an asset that does not exist will raise an exception in the +calling page. This includes linking to a blank string. As such, be careful using +`image_tag` and the other helpers with user-supplied data. #### CSS and ERB -The asset pipeline automatically evaluates ERB. This means that if you add an `erb` extension to a CSS asset (for example, `application.css.erb`), then helpers like `asset_path` are available in your CSS rules: +The asset pipeline automatically evaluates ERB. This means if you add an +`erb` extension to a CSS asset (for example, `application.css.erb`), then +helpers like `asset_path` are available in your CSS rules: ```css .class { background-image: url(<%= asset_path 'image.png' %>) } ``` -This writes the path to the particular asset being referenced. In this example, it would make sense to have an image in one of the asset load paths, such as `app/assets/images/image.png`, which would be referenced here. If this image is already available in `public/assets` as a fingerprinted file, then that path is referenced. +This writes the path to the particular asset being referenced. In this example, +it would make sense to have an image in one of the asset load paths, such as +`app/assets/images/image.png`, which would be referenced here. If this image is +already available in `public/assets` as a fingerprinted file, then that path is +referenced. -If you want to use a [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme) — a method of embedding the image data directly into the CSS file — you can use the `asset_data_uri` helper. +If you want to use a [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme) — +a method of embedding the image data directly into the CSS file — you can use +the `asset_data_uri` helper. ```css #logo { background: url(<%= asset_data_uri 'logo.png' %>) } @@ -239,29 +392,34 @@ Note that the closing tag cannot be of the style `-%>`. #### CSS and Sass -When using the asset pipeline, paths to assets must be re-written and `sass-rails` provides `-url` and `-path` helpers (hyphenated in Sass, underscored in Ruby) for the following asset classes: image, font, video, audio, JavaScript and stylesheet. +When using the asset pipeline, paths to assets must be re-written and +`sass-rails` provides `-url` and `-path` helpers (hyphenated in Sass, +underscored in Ruby) for the following asset classes: image, font, video, audio, +JavaScript and stylesheet. * `image-url("rails.png")` becomes `url(/assets/rails.png)` * `image-path("rails.png")` becomes `"/assets/rails.png"`. -The more generic form can also be used but the asset path and class must both be specified: +The more generic form can also be used but the asset path and class must both be +specified: * `asset-url("rails.png", image)` becomes `url(/assets/rails.png)` * `asset-path("rails.png", image)` becomes `"/assets/rails.png"` #### JavaScript/CoffeeScript and ERB -If you add an `erb` extension to a JavaScript asset, making it something such as `application.js.erb`, then you can use the `asset_path` helper in your JavaScript code: +If you add an `erb` extension to a JavaScript asset, making it something such as +`application.js.erb`, you can then use the `asset_path` helper in your +JavaScript code: ```js -$('#logo').attr({ - src: "<%= asset_path('logo.png') %>" -}); +$('#logo').attr({ src: "<%= asset_path('logo.png') %>" }); ``` This writes the path to the particular asset being referenced. -Similarly, you can use the `asset_path` helper in CoffeeScript files with `erb` extension (e.g., `application.js.coffee.erb`): +Similarly, you can use the `asset_path` helper in CoffeeScript files with `erb` +extension (e.g., `application.js.coffee.erb`): ```js $('#logo').attr src: "<%= asset_path('logo.png') %>" @@ -269,10 +427,19 @@ $('#logo').attr src: "<%= asset_path('logo.png') %>" ### Manifest Files and Directives -Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ — instructions that tell Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets loads the files specified, processes them if necessary, concatenates them into one single file and then compresses them (if `Rails.application.config.assets.compress` is true). By serving one file rather than many, the load time of pages can be greatly reduced because the browser makes fewer requests. Compression also reduces the file size enabling the browser to download it faster. +Sprockets uses manifest files to determine which assets to include and serve. +These manifest files contain _directives_ — instructions that tell Sprockets +which files to require in order to build a single CSS or JavaScript file. With +these directives, Sprockets loads the files specified, processes them if +necessary, concatenates them into one single file and then compresses them (if +`Rails.application.config.assets.compress` is true). By serving one file rather +than many, the load time of pages can be greatly reduced because the browser +makes fewer requests. Compression also reduces file size, enabling the +browser to download them faster. -For example, a new Rails application includes a default `app/assets/javascripts/application.js` file which contains the following lines: +For example, a new Rails 4 application includes a default +`app/assets/javascripts/application.js` file containing the following lines: ```js // ... @@ -281,30 +448,65 @@ For example, a new Rails application includes a default `app/assets/javascripts/ //= require_tree . ``` -In JavaScript files, the directives begin with `//=`. In this case, the file is using the `require` and the `require_tree` directives. The `require` directive is used to tell Sprockets the files that you wish to require. Here, you are requiring the files `jquery.js` and `jquery_ujs.js` that are available somewhere in the search path for Sprockets. You need not supply the extensions explicitly. Sprockets assumes you are requiring a `.js` file when done from within a `.js` file. - -The `require_tree` directive tells Sprockets to recursively include _all_ JavaScript files in the specified directory into the output. These paths must be specified relative to the manifest file. You can also use the `require_directory` directive which includes all JavaScript files only in the directory specified, without recursion. - -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. - -Rails also creates a default `app/assets/stylesheets/application.css` file which contains these lines: +In JavaScript files, Sprockets directives begin with `//=`. In the above case, +the file is using the `require` and the `require_tree` directives. The `require` +directive is used to tell Sprockets the files you wish to require. Here, you are +requiring the files `jquery.js` and `jquery_ujs.js` that are available somewhere +in the search path for Sprockets. You need not supply the extensions explicitly. +Sprockets assumes you are requiring a `.js` file when done from within a `.js` +file. + +The `require_tree` directive tells Sprockets to recursively include _all_ +JavaScript files in the specified directory into the output. These paths must be +specified relative to the manifest file. You can also use the +`require_directory` directive which includes all JavaScript files only in the +directory specified, without recursion. + +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. + +Rails also creates a default `app/assets/stylesheets/application.css` file +which contains these lines: -```js +```css /* ... *= require_self *= require_tree . */ ``` -The directives that work in the JavaScript files also work in stylesheets (though obviously including stylesheets rather than JavaScript files). The `require_tree` directive in a CSS manifest works the same way as the JavaScript one, requiring all stylesheets from the current directory. +Rails 4 creates both `app/assets/javascripts/application.js` and +`app/assets/stylesheets/application.css` regardless of whether the +--skip-sprockets option is used when creating a new rails application. This is +so you can easily add asset pipelining later if you like. + +The directives that work in JavaScript files also work in stylesheets +(though obviously including stylesheets rather than JavaScript files). The +`require_tree` directive in a CSS manifest works the same way as the JavaScript +one, requiring all stylesheets from the current directory. -In this example `require_self` is used. This puts the CSS contained within the file (if any) at the precise location of the `require_self` call. If `require_self` is called more than once, only the last call is respected. +In this example, `require_self` is used. This puts the CSS contained within the +file (if any) at the precise location of the `require_self` call. If +`require_self` is called more than once, only the last call is respected. -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) instead of these Sprockets directives. Using Sprockets directives all Sass files exist within their own scope, making variables or mixins only available within the document they were defined in. +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) instead +of these Sprockets directives. Using Sprockets directives all Sass files exist +within their own scope, making variables or mixins only available within the +document they were defined in. -You can have as many manifest files as you need. For example the `admin.css` and `admin.js` manifest could contain the JS and CSS files that are used for the admin section of an application. +You can have as many manifest files as you need. For example, the `admin.css` +and `admin.js` manifest could contain the JS and CSS files that are used for the +admin section of an application. -The same remarks about ordering made above apply. In particular, you can specify individual files and they are compiled in the order specified. For example, you might concatenate three CSS files together this way: +The same remarks about ordering made above apply. In particular, you can specify +individual files and they are compiled in the order specified. For example, you +might concatenate three CSS files together this way: ```js /* ... @@ -314,21 +516,41 @@ The same remarks about ordering made above apply. In particular, you can specify */ ``` - ### Preprocessing -The file extensions used on an asset determine what preprocessing is applied. When a controller or a scaffold is generated with the default Rails gemset, a CoffeeScript file and a SCSS file are generated in place of a regular JavaScript and CSS file. The example used before was a controller called "projects", which generated an `app/assets/javascripts/projects.js.coffee` and an `app/assets/stylesheets/projects.css.scss` file. - -When these files are requested, they are processed by the processors provided by the `coffee-script` and `sass` gems and then sent back to the browser as JavaScript and CSS respectively. - -Additional layers of preprocessing can be requested by adding other extensions, where each extension is processed in a right-to-left manner. These should be used in the order the processing should be applied. For example, a stylesheet called `app/assets/stylesheets/projects.css.scss.erb` is first processed as ERB, then SCSS, and finally served as CSS. The same applies to a JavaScript file — `app/assets/javascripts/projects.js.coffee.erb` is processed as ERB, then CoffeeScript, and served as JavaScript. +The file extensions used on an asset determine what preprocessing is applied. +When a controller or a scaffold is generated with the default Rails gemset, a +CoffeeScript file and a SCSS file are generated in place of a regular JavaScript +and CSS file. The example used before was a controller called "projects", which +generated an `app/assets/javascripts/projects.js.coffee` and an +`app/assets/stylesheets/projects.css.scss` file. + +In development mode, or if the asset pipeline is disabled, when these files are +requested they are processed by the processors provided by the `coffee-script` +and `sass` gems and then sent back to the browser as JavaScript and CSS +respectively. When asset pipelining is enabled, these files are preprocessed and +placed in the `public/assets` directory for serving by either the Rails app or +web server. + +Additional layers of preprocessing can be requested by adding other extensions, +where each extension is processed in a right-to-left manner. These should be +used in the order the processing should be applied. For example, a stylesheet +called `app/assets/stylesheets/projects.css.scss.erb` is first processed as ERB, +then SCSS, and finally served as CSS. The same applies to a JavaScript file — +`app/assets/javascripts/projects.js.coffee.erb` is processed as ERB, then +CoffeeScript, and served as JavaScript. + +Keep in mind 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. -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. In Development -------------- -In development mode, assets are served as separate files in the order they are specified in the manifest file. +In development mode, assets are served as separate files in the order they are +specified in the manifest file. This manifest `app/assets/javascripts/application.js`: @@ -350,39 +572,52 @@ The `body` param is required by Sprockets. ### Turning Debugging Off -You can turn off debug mode by updating `config/environments/development.rb` to include: +You can turn off debug mode by updating `config/environments/development.rb` to +include: ```ruby config.assets.debug = false ``` -When debug mode is off, Sprockets concatenates and runs the necessary preprocessors on all files. With debug mode turned off the manifest above would generate instead: +When debug mode is off, Sprockets concatenates and runs the necessary +preprocessors on all files. With debug mode turned off the manifest above would +generate instead: ```html <script src="/assets/application.js"></script> ``` -Assets are compiled and cached on the first request after the server is started. Sprockets sets a `must-revalidate` Cache-Control HTTP header to reduce request overhead on subsequent requests — on these the browser gets a 304 (Not Modified) response. +Assets are compiled and cached on the first request after the server is started. +Sprockets sets a `must-revalidate` Cache-Control HTTP header to reduce request +overhead on subsequent requests — on these the browser gets a 304 (Not Modified) +response. -If any of the files in the manifest have changed between requests, the server responds with a new compiled file. +If any of the files in the manifest have changed between requests, the server +responds with a new compiled file. -Debug mode can also be enabled in the Rails helper methods: +Debug mode can also be enabled in Rails helper methods: ```erb <%= stylesheet_link_tag "application", debug: true %> <%= javascript_include_tag "application", debug: true %> ``` -The `:debug` option is redundant if debug mode is on. +The `:debug` option is redundant if debug mode is already on. -You could potentially also enable compression in development mode as a sanity check, and disable it on-demand as required for debugging. +You can also enable compression in development mode as a sanity check, and +disable it on-demand as required for debugging. In Production ------------- -In the production environment Rails uses the fingerprinting scheme outlined above. By default Rails assumes that assets have been precompiled and will be served as static assets by your web server. +In the production environment Sprockets uses the fingerprinting scheme outlined +above. By default Rails assumes assets have been precompiled and will be +served as static assets by your web server. -During the precompilation phase an MD5 is generated from the contents of the compiled files, and inserted into the filenames as they are written to disc. These fingerprinted names are used by the Rails helpers in place of the manifest name. +During the precompilation phase an MD5 is generated from the contents of the +compiled files, and inserted into the filenames as they are written to disc. +These fingerprinted names are used by the Rails helpers in place of the manifest +name. For example this: @@ -395,23 +630,34 @@ generates something like this: ```html <script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js"></script> -<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen" rel="stylesheet" /> +<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen" +rel="stylesheet" /> ``` -Note: with the Asset Pipeline the :cache and :concat options aren't used anymore, delete these options from the `javascript_include_tag` and `stylesheet_link_tag`. +Note: with the Asset Pipeline the :cache and :concat options aren't used +anymore, delete these options from the `javascript_include_tag` and +`stylesheet_link_tag`. +The fingerprinting behavior is controlled by the `config.assets.digest` +initialization option (which defaults to `true` for production and `false` for +everything else). -The fingerprinting behavior is controlled by the setting of `config.assets.digest` setting in Rails (which defaults to `true` for production and `false` for everything else). - -NOTE: Under normal circumstances the default option should not be changed. If there are no digests in the filenames, and far-future headers are set, remote clients will never know to refetch the files when their content changes. +NOTE: Under normal circumstances the default `config.assets.digest` option +should not be changed. If there are no digests in the filenames, and far-future +headers are set, remote clients will never know to refetch the files when their +content changes. ### Precompiling Assets -Rails comes bundled with a rake task to compile the asset manifests and other files in the pipeline to the disk. +Rails comes bundled with a rake task to compile the asset manifests and other +files in the pipeline. -Compiled assets are written to the location specified in `config.assets.prefix`. By default, this is the `public/assets` directory. +Compiled assets are written to the location specified in `config.assets.prefix`. +By default, this is the `/assets` directory. -You can call this task on the server during deployment to create compiled versions of your assets directly on the server. See the next section for information on compiling locally. +You can call this task on the server during deployment to create compiled +versions of your assets directly on the server. See the next section for +information on compiling locally. The rake task is: @@ -419,33 +665,43 @@ The rake task is: $ RAILS_ENV=production bundle exec rake assets:precompile ``` -Capistrano (v2.15.1 and above) includes a recipe to handle this in deployment. Add the following line to `Capfile`: +Capistrano (v2.15.1 and above) includes a recipe to handle this in deployment. +Add the following line to `Capfile`: ```ruby load 'deploy/assets' ``` -This links the folder specified in `config.assets.prefix` to `shared/assets`. If you already use this shared folder you'll need to write your own deployment task. - -It is important that this folder is shared between deployments so that remotely cached pages that reference the old compiled assets still work for the life of the cached page. +This links the folder specified in `config.assets.prefix` to `shared/assets`. +If you already use this shared folder you'll need to write your own deployment +task. -NOTE. If you are precompiling your assets locally, you can use `bundle install --without assets` on the server to avoid installing the assets gems (the gems in the assets group in the Gemfile). +It is important that this folder is shared between deployments so that remotely +cached pages referencing the old compiled assets still work for the life of +the cached page. -The default matcher for compiling files includes `application.js`, `application.css` and all non-JS/CSS files (this will include all image assets automatically): +The default matcher for compiling files includes `application.js`, +`application.css` and all non-JS/CSS files (this will include all image assets +automatically): ```ruby -[ Proc.new { |path| !%w(.js .css).include?(File.extname(path)) }, /application.(css|js)$/ ] +[ Proc.new { |path| !%w(.js .css).include?(File.extname(path)) }, +/application.(css|js)$/ ] ``` -NOTE. The matcher (and other members of the precompile array; see below) is applied to final compiled file names. This means that anything that compiles to JS/CSS is excluded, as well as raw JS/CSS files; for example, `.coffee` and `.scss` files are **not** automatically included as they compile to JS/CSS. +NOTE: The matcher (and other members of the precompile array; see below) is +applied to final compiled file names. This means anything that compiles to +JS/CSS is excluded, as well as raw JS/CSS files; for example, `.coffee` and +`.scss` files are **not** automatically included as they compile to JS/CSS. -If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the `precompile` array in `config/application.rb`: +If you have other manifests or individual stylesheets and JavaScript files to +include, you can add them to the `precompile` array in `config/application.rb`: ```ruby config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js'] ``` -Or you can opt to precompile all assets with something like this: +Or, you can opt to precompile all assets with something like this: ```ruby # config/application.rb @@ -466,38 +722,51 @@ config.assets.precompile << Proc.new do |path| end ``` -NOTE. Always specify an expected compiled filename that ends with js or css, even if you want to add Sass or CoffeeScript files to the precompile array. +NOTE. Always specify an expected compiled filename that ends with .js or .css, +even if you want to add Sass or CoffeeScript files to the precompile array. -The rake task also generates a `manifest.yml` that contains a list with all your assets and their respective fingerprints. This is used by the Rails helper methods to avoid handing the mapping requests back to Sprockets. A typical manifest file looks like: +The rake task also generates a `manifest-md5hash.json` that contains a list with +all your assets and their respective fingerprints. This is used by the Rails +helper methods to avoid handing the mapping requests back to Sprockets. A +typical manifest file looks like: -```yaml ---- -rails.png: rails-bd9ad5a560b5a3a7be0808c5cd76a798.png -jquery-ui.min.js: jquery-ui-7e33882a28fc84ad0e0e47e46cbf901c.min.js -jquery.min.js: jquery-8a50feed8d29566738ad005e19fe1c2d.min.js -application.js: application-3fdab497b8fb70d20cfc5495239dfc29.js -application.css: application-8af74128f904600e41a6e39241464e03.css +```ruby +{"files":{"application-723d1be6cc741a3aabb1cec24276d681.js":{"logical_path":"application.js","mtime":"2013-07-26T22:55:03-07:00","size":302506, +"digest":"723d1be6cc741a3aabb1cec24276d681"},"application-12b3c7dd74d2e9df37e7cbb1efa76a6d.css":{"logical_path":"application.css","mtime":"2013-07-26T22:54:54-07:00","size":1560, +"digest":"12b3c7dd74d2e9df37e7cbb1efa76a6d"},"application-1c5752789588ac18d7e1a50b1f0fd4c2.css":{"logical_path":"application.css","mtime":"2013-07-26T22:56:17-07:00","size":1591, +"digest":"1c5752789588ac18d7e1a50b1f0fd4c2"},"favicon-a9c641bf2b81f0476e876f7c5e375969.ico":{"logical_path":"favicon.ico","mtime":"2013-07-26T23:00:10-07:00","size":1406, +"digest":"a9c641bf2b81f0476e876f7c5e375969"},"my_image-231a680f23887d9dd70710ea5efd3c62.png":{"logical_path":"my_image.png","mtime":"2013-07-26T23:00:27-07:00","size":6646, +"digest":"231a680f23887d9dd70710ea5efd3c62"}},"assets"{"application.js": +"application-723d1be6cc741a3aabb1cec24276d681.js","application.css": +"application-1c5752789588ac18d7e1a50b1f0fd4c2.css", +"favicon.ico":"favicona9c641bf2b81f0476e876f7c5e375969.ico","my_image.png": +"my_image-231a680f23887d9dd70710ea5efd3c62.png"}} ``` -The default location for the manifest is the root of the location specified in `config.assets.prefix` ('/assets' by default). +The default location for the manifest is the root of the location specified in +`config.assets.prefix` ('/assets' by default). -NOTE: If there are missing precompiled files in production you will get an `Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError` exception indicating the name of the missing file(s). +NOTE: If there are missing precompiled files in production you will get an +`Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError` +exception indicating the name of the missing file(s). #### Far-future Expires Header -Precompiled assets exist on the filesystem and are served directly by your web server. They do not have far-future headers by default, so to get the benefit of fingerprinting you'll have to update your server configuration to add them. +Precompiled assets exist on the filesystem and are served directly by your web +server. They do not have far-future headers by default, so to get the benefit of +fingerprinting you'll have to update your server configuration to add those +headers. For Apache: ```apache -# The Expires* directives requires the Apache module `mod_expires` to be enabled. +# The Expires* directives requires the Apache module `mod_expires` to be +# enabled. <Location /assets/> # Use of ETag is discouraged when Last-Modified is present - Header unset ETag - FileETag None + Header unset ETag FileETag None # RFC says only cache for 1 year - ExpiresActive On - ExpiresDefault "access plus 1 year" + ExpiresActive On ExpiresDefault "access plus 1 year" </Location> ``` @@ -515,7 +784,13 @@ location ~ ^/assets/ { #### GZip Compression -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. +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. Nginx is able to do this automatically enabling `gzip_static`: @@ -528,25 +803,32 @@ location ~ ^/(assets)/ { } ``` -This directive is available if the core module that provides this feature was compiled with the web server. Ubuntu packages, even `nginx-light` have the module compiled. Otherwise, you may need to perform a manual compilation: +This directive is available if the core module that provides this feature was +compiled with the web server. Ubuntu/Debian packages, even `nginx-light`, have +the module compiled. Otherwise, you may need to perform a manual compilation: ```bash ./configure --with-http_gzip_static_module ``` -If you're compiling nginx with Phusion Passenger you'll need to pass that option when prompted. +If you're compiling nginx with Phusion Passenger you'll need to pass that option +when prompted. -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.) +A robust configuration for Apache is possible but tricky; please Google around. +(Or help update this Guide if you have a good configuration example for Apache.) ### Local Precompilation -There are several reasons why you might want to precompile your assets locally. Among them are: +There are several reasons why you might want to precompile your assets locally. +Among them are: * You may not have write access to your production file system. -* You may be deploying to more than one server, and want to avoid the duplication of work. +* You may be deploying to more than one server, and want to avoid +duplication of work. * You may be doing frequent deploys that do not include asset changes. -Local compilation allows you to commit the compiled files into source control, and deploy as normal. +Local compilation allows you to commit the compiled files into source control, +and deploy as normal. There are two caveats: @@ -559,15 +841,23 @@ In `config/environments/development.rb`, place the following line: config.assets.prefix = "/dev-assets" ``` -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. +The `prefix` change makes Sprockets 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 `/assets` in development, and you would +not see any local changes until you compile assets again. -You will also need to ensure that any compressors or minifiers are available on your development system. +You will also need to ensure any necessary compressors or minifiers are +available on your development system. -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. +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. ### Live Compilation -In some circumstances you may wish to use live compilation. In this mode all requests for assets in the pipeline are handled by Sprockets directly. +In some circumstances you may wish to use live compilation. In this mode all +requests for assets in the pipeline are handled by Sprockets directly. To enable this option set: @@ -575,13 +865,21 @@ To enable this option set: config.assets.compile = true ``` -On the first request the assets are compiled and cached as outlined in development above, and the manifest names used in the helpers are altered to include the MD5 hash. +On the first request the assets are compiled and cached as outlined in +development above, and the manifest names used in the helpers are altered to +include the MD5 hash. -Sprockets also sets the `Cache-Control` HTTP header to `max-age=31536000`. This signals all caches between your server and the client browser that this content (the file served) can be cached for 1 year. The effect of this is to reduce the number of requests for this asset from your server; the asset has a good chance of being in the local browser cache or some intermediate cache. +Sprockets also sets the `Cache-Control` HTTP header to `max-age=31536000`. This +signals all caches between your server and the client browser that this content +(the file served) can be cached for 1 year. The effect of this is to reduce the +number of requests for this asset from your server; the asset has a good chance +of being in the local browser cache or some intermediate cache. -This mode uses more memory, performs more poorly than the default and is not recommended. +This mode uses more memory, performs more poorly than the default and is not +recommended. -If you are deploying a production application to a system without any pre-existing JavaScript runtimes, you may want to add one to your Gemfile: +If you are deploying a production application to a system without any +pre-existing JavaScript runtimes, you may want to add one to your Gemfile: ```ruby group :production do @@ -591,36 +889,43 @@ end ### CDNs -If your assets are being served by a CDN, ensure they don't stick around in -your cache forever. This can cause problems. If you use +If your assets are being served by a CDN, ensure they don't stick around in your +cache forever. This can cause problems. If you use `config.action_controller.perform_caching = true`, Rack::Cache will use `Rails.cache` to store assets. This can cause your cache to fill up quickly. -Every cache is different, so evaluate how your CDN handles caching and make -sure that it plays nicely with the pipeline. You may find quirks related to -your specific set up, you may not. The defaults nginx uses, for example, -should give you no problems when used as an HTTP cache. +Every cache is different, so evaluate how your CDN handles caching and make sure +that it plays nicely with the pipeline. You may find quirks related to your +specific set up, you may not. The defaults nginx uses, for example, should give +you no problems when used as an HTTP cache. Customizing the Pipeline ------------------------ ### CSS Compression -There is currently one option for compressing CSS, YUI. The [YUI CSS compressor](http://yui.github.io/yuicompressor/css.html) provides minification. +There is currently one option for compressing CSS, YUI. The [YUI CSS +compressor]((http://yui.github.io/yuicompressor/css.html) provides +minification. -The following line enables YUI compression, and requires the `yui-compressor` gem. +The following line enables YUI compression, and requires the `yui-compressor` +gem. ```ruby config.assets.css_compressor = :yui ``` -The `config.assets.compress` must be set to `true` to enable CSS compression. - ### JavaScript Compression -Possible options for JavaScript compression are `:closure`, `:uglifier` and `:yui`. These require the use of the `closure-compiler`, `uglifier` or `yui-compressor` gems, respectively. +Possible options for JavaScript compression are `:closure`, `:uglifier` and +`:yui`. These require the use of the `closure-compiler`, `uglifier` or +`yui-compressor` gems, respectively. -The default Gemfile includes [uglifier](https://github.com/lautis/uglifier). This gem wraps [UglifyJS](https://github.com/mishoo/UglifyJS) (written for NodeJS) in Ruby. It compresses your code by removing white space and comments, shortening local variable names, and performing other micro-optimizations such as changing `if` and `else` statements to ternary operators where possible. +The default Gemfile includes [uglifier](https://github.com/lautis/uglifier). +This gem wraps [UglifyJS](https://github.com/mishoo/UglifyJS) (written for +NodeJS) in Ruby. It compresses your code by removing white space and comments, +shortening local variable names, and performing other micro-optimizations such +as changing `if` and `else` statements to ternary operators where possible. The following line invokes `uglifier` for JavaScript compression. @@ -628,13 +933,21 @@ The following line invokes `uglifier` for JavaScript compression. config.assets.js_compressor = :uglifier ``` -Note that `config.assets.compress` must be set to `true` to enable JavaScript compression +NOTE: You will need an [ExecJS](https://github.com/sstephenson/execjs#readme) +supported runtime in order to use `uglifier`. If you are using Mac OS X or +Windows you have a JavaScript runtime installed in your operating system. -NOTE: You will need an [ExecJS](https://github.com/sstephenson/execjs#readme) supported runtime in order to use `uglifier`. If you are using Mac OS X or Windows you have a JavaScript runtime installed in your operating system. Check the [ExecJS](https://github.com/sstephenson/execjs#readme) documentation for information on all of the supported JavaScript runtimes. +NOTE: The `config.assets.compress` initialization option is no longer used in +Rails 4 to enable either CSS or JavaScript compression. Setting it will have no +effect on the application. Instead, setting `config.assets.css_compressor` and +`config.assets.js_compressor` will control compression of CSS and JavaScript +assets. ### Using Your Own Compressor -The compressor config settings for CSS and JavaScript also take any object. This object must have a `compress` method that takes a string as the sole argument and it must return a string. +The compressor config settings for CSS and JavaScript also take any object. +This object must have a `compress` method that takes a string as the sole +argument and it must return a string. ```ruby class Transformer @@ -661,31 +974,44 @@ This can be changed to something else: config.assets.prefix = "/some_other_path" ``` -This is a handy option if you are updating an older project that didn't use the asset pipeline and that already uses this path or you wish to use this path for a new resource. +This is a handy option if you are updating an older project that didn't use the +asset pipeline and already uses this path or you wish to use this path for +a new resource. ### X-Sendfile Headers -The X-Sendfile header is a directive to the web server to ignore the response from the application, and instead serve a specified file from disk. This option is off by default, but can be enabled if your server supports it. When enabled, this passes responsibility for serving the file to the web server, which is faster. +The X-Sendfile header is a directive to the web server to ignore the response +from the application, and instead serve a specified file from disk. This option +is off by default, but can be enabled if your server supports it. When enabled, +this passes responsibility for serving the file to the web server, which is +faster. -Apache and nginx support this option, which can be enabled in `config/environments/production.rb`. +Apache and nginx support this option, which can be enabled in +`config/environments/production.rb`: ```ruby # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx ``` -WARNING: If you are upgrading an existing application and intend to use this option, take care to paste this configuration option only into `production.rb` and any other environments you define with production behavior (not `application.rb`). +WARNING: If you are upgrading an existing application and intend to use this +option, take care to paste this configuration option only into `production.rb` +and any other environments you define with production behavior (not +`application.rb`). Assets Cache Store ------------------ -The default Rails cache store will be used by Sprockets to cache assets in development and production. This can be changed by setting `config.assets.cache_store`. +The default Rails cache store will be used by Sprockets to cache assets in +development and production. This can be changed by setting +`config.assets.cache_store`: ```ruby config.assets.cache_store = :memory_store ``` -The options accepted by the assets cache store are the same as the application's cache store. +The options accepted by the assets cache store are the same as the application's +cache store. ```ruby config.assets.cache_store = :memory_store, { size: 32.megabytes } @@ -696,16 +1022,21 @@ Adding Assets to Your Gems Assets can also come from external sources in the form of gems. -A good example of this is the `jquery-rails` gem which comes with Rails as the standard JavaScript library gem. This gem contains an engine class which inherits from `Rails::Engine`. By doing this, Rails is informed that the directory for this gem may contain assets and the `app/assets`, `lib/assets` and `vendor/assets` directories of this engine are added to the search path of Sprockets. +A good example of this is the `jquery-rails` gem which comes with Rails as the +standard JavaScript library gem. This gem contains an engine class which +inherits from `Rails::Engine`. By doing this, Rails is informed that the +directory for this gem may contain assets and the `app/assets`, `lib/assets` and +`vendor/assets` directories of this engine are added to the search path of +Sprockets. Making Your Library or Gem a Pre-Processor ------------------------------------------ As Sprockets uses [Tilt](https://github.com/rtomayko/tilt) as a generic -interface to different templating engines, your gem should just -implement the Tilt template protocol. Normally, you would subclass -`Tilt::Template` and reimplement `evaluate` method to return final -output. Template source is stored at `@code`. Have a look at +interface to different templating engines, your gem should just implement the +Tilt template protocol. Normally, you would subclass `Tilt::Template` and +reimplement `evaluate` method to return final output. Template source is stored +at `@code`. Have a look at [`Tilt::Template`](https://github.com/rtomayko/tilt/blob/master/lib/tilt/template.rb) sources to learn more. @@ -730,31 +1061,30 @@ Sprockets.register_engine '.bang', BangBang::Template Upgrading from Old Versions of Rails ------------------------------------ -There are a few issues when upgrading. The first is moving the files from `public/` to the new locations. See [Asset Organization](#asset-organization) above for guidance on the correct locations for different file types. +There are a few issues when upgrading from Rails 3.0 or Rails 2.x. The first is +moving the files from `public/` to the new locations. See [Asset +Organization](#asset-organization) above for guidance on the correct locations +for different file types. -Next will be avoiding duplicate JavaScript files. Since jQuery is the default JavaScript library from Rails 3.1 onwards, you don't need to copy `jquery.js` into `app/assets` and it will be included automatically. +Next will be avoiding duplicate JavaScript files. Since jQuery is the default +JavaScript library from Rails 3.1 onwards, you don't need to copy `jquery.js` +into `app/assets` and it will be included automatically. -The third is updating the various environment files with the correct default options. The following changes reflect the defaults in version 3.1.0. +The third is updating the various environment files with the correct default +options. In `application.rb`: ```ruby -# Enable the asset pipeline -config.assets.enabled = true - # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' -# Change the path that assets are served from -# config.assets.prefix = "/assets" +# Change the path that assets are served from config.assets.prefix = "/assets" ``` In `development.rb`: ```ruby -# Do not compress assets -config.assets.compress = false - # Expands the lines which load the assets config.assets.debug = true ``` @@ -762,50 +1092,28 @@ config.assets.debug = true And in `production.rb`: ```ruby -# Compress JavaScripts and CSS -config.assets.compress = true - -# Choose the compressors to use -# config.assets.js_compressor = :uglifier -# config.assets.css_compressor = :yui +# Choose the compressors to use (if any) config.assets.js_compressor = +# :uglifier config.assets.css_compressor = :yui # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false -# Generate digests for assets URLs. +# Generate digests for assets URLs. This is planned for deprecation. config.assets.digest = true -# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) -# config.assets.precompile += %w( search.js ) +# Precompile additional assets (application.js, application.css, and all +# non-JS/CSS are already added) config.assets.precompile += %w( search.js ) ``` -You should not need to change `test.rb`. The defaults in the test environment are: `config.assets.compile` is true and `config.assets.compress`, `config.assets.debug` and `config.assets.digest` are false. +Rails 4 no longer sets default config values for Sprockets in `test.rb`, so +`test.rb` now requies Sprockets configuration. The old defaults in the test +environment are: `config.assets.compile = true`, `config.assets.compress = +false`, `config.assets.debug = false` and `config.assets.digest = false`. The following should also be added to `Gemfile`: ```ruby -# Gems used only for assets and not required -# in production environments by default. -group :assets do - gem 'sass-rails', "~> 3.2.3" - gem 'coffee-rails', "~> 3.2.1" - gem 'uglifier' -end -``` - -If you use the `assets` group with Bundler, please make sure that your `config/application.rb` has the following Bundler require statement: - -```ruby -# If you precompile assets before deploying to production, use this line -Bundler.require *Rails.groups(:assets => %w(development test)) -# If you want your assets lazily compiled in production, use this line -# Bundler.require(:default, :assets, Rails.env) -``` - -Instead of the generated version: - -```ruby -# Require the gems listed in Gemfile, including any gems -# you've limited to :test, :development, or :production. -Bundler.require(:default, Rails.env) +gem 'sass-rails', "~> 3.2.3" +gem 'coffee-rails', "~> 3.2.1" +gem 'uglifier' ``` diff --git a/guides/source/command_line.md b/guides/source/command_line.md index 218b4dd39a..5f98326c57 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -222,7 +222,7 @@ We will set up a simple resource called "HighScore" that will keep track of our ```bash $ rails generate scaffold HighScore game:string score:integer invoke active_record - create db/migrate/20120528060026_create_high_scores.rb + create db/migrate/20130717151933_create_high_scores.rb create app/models/high_score.rb invoke test_unit create test/models/high_score_test.rb @@ -244,18 +244,21 @@ $ rails generate scaffold HighScore game:string score:integer create app/helpers/high_scores_helper.rb invoke test_unit create test/helpers/high_scores_helper_test.rb + invoke jbuilder + create app/views/high_scores/index.json.jbuilder + create app/views/high_scores/show.json.jbuilder invoke assets invoke coffee create app/assets/javascripts/high_scores.js.coffee invoke scss create app/assets/stylesheets/high_scores.css.scss invoke scss - create app/assets/stylesheets/scaffolds.css.scss + identical app/assets/stylesheets/scaffolds.css.scss ``` The generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the `high_scores` table and fields), takes care of the route for the **resource**, and new tests for everything. -The migration requires that we **migrate**, that is, run some Ruby code (living in that `20120528060026_create_high_scores.rb`) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while. +The migration requires that we **migrate**, that is, run some Ruby code (living in that `20130717151933_create_high_scores.rb`) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while. ```bash $ rake db:migrate @@ -384,7 +387,7 @@ Active Record version 4.0.0 Action Pack version 4.0.0 Action Mailer version 4.0.0 Active Support version 4.0.0 -Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::EncryptedCookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag +Middleware Rack::Sendfile, ActionDispatch::Static, Rack::Lock, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::EncryptedCookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag Application root /home/foobar/commandsapp Environment development Database adapter sqlite3 diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md index 24e16ecd40..2f8a178376 100644 --- a/guides/source/contributing_to_ruby_on_rails.md +++ b/guides/source/contributing_to_ruby_on_rails.md @@ -264,7 +264,7 @@ The CHANGELOG is an important part of every release. It keeps the list of change You should add an entry to the CHANGELOG of the framework that you modified if you're adding or removing a feature, committing a bug fix or adding deprecation notices. Refactorings and documentation changes generally should not go to the CHANGELOG. -A CHANGELOG entry should summarize what was changed and should end with author's name. You can use multiple lines if you need more space and you can attach code examples indented with 4 spaces. If a change is related to a specific issue, you should attach issue's number. Here is an example CHANGELOG entry: +A CHANGELOG entry should summarize what was changed and should end with author's name and it should go on top of a CHANGELOG. You can use multiple lines if you need more space and you can attach code examples indented with 4 spaces. If a change is related to a specific issue, you should attach issue's number. Here is an example CHANGELOG entry: ``` * Summary of a change that briefly describes what was changed. You can use multiple diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md index 98f91c1ac6..50ee934b87 100644 --- a/guides/source/debugging_rails_applications.md +++ b/guides/source/debugging_rails_applications.md @@ -209,6 +209,37 @@ logger.tagged("BCX", "Jason") { logger.info "Stuff" } # Logs " logger.tagged("BCX") { logger.tagged("Jason") { logger.info "Stuff" } } # Logs "[BCX] [Jason] Stuff" ``` +### Impact of Logs on Performance +Logging will always have a small impact on performance of your rails app, + particularly when logging to disk.However, there are a few subtleties: + +Using the `:debug` level will have a greater performance penalty than `:fatal`, + as a far greater number of strings are being evaluated and written to the + log output (e.g. disk). + +Another potential pitfall is that if you have many calls to `Logger` like this + in your code: + +```ruby +logger.debug "Person attributes hash: #{@person.attributes.inspect}" +``` + +In the above example, There will be a performance impact even if the allowed +output level doesn't include debug. The reason is that Ruby has to evaluate +these strings, which includes instantiating the somewhat heavy `String` object +and interpolating the variables, and which takes time. +Therefore, it's recommended to pass blocks to the logger methods, as these are +only evaluated if the output level is the same or included in the allowed level +(i.e. lazy loading). The same code rewritten would be: + +```ruby +logger.debug {"Person attibutes hash: #{@person.attributes.inspect}"} +``` + +The contents of the block, and therefore the string interpolation, is only +evaluated if debug is enabled. This performance savings is only really +noticeable with large amounts of logging, but it's a good practice to employ. + Debugging with the `debugger` gem --------------------------------- @@ -301,7 +332,7 @@ This command shows you where you are in the code by printing 10 lines centered a 7 8 respond_to do |format| 9 format.html # index.html.erb - 10 format.json { render :json => @posts } + 10 format.json { render json: @posts } ``` If you repeat the `list` command, this time using just `l`, the next ten lines of the file will be printed out. @@ -337,7 +368,7 @@ On the other hand, to see the previous ten lines you should type `list-` (or `l- 7 8 respond_to do |format| 9 format.html # index.html.erb - 10 format.json { render :json => @posts } + 10 format.json { render json: @posts } ``` This way you can move inside the file, being able to see the code above and over the line you added the `debugger`. diff --git a/guides/source/development_dependencies_install.md b/guides/source/development_dependencies_install.md index 5647a4c1b7..ec25e09222 100644 --- a/guides/source/development_dependencies_install.md +++ b/guides/source/development_dependencies_install.md @@ -57,9 +57,24 @@ If you are on Fedora or CentOS, you can run $ sudo yum install libxml2 libxml2-devel libxslt libxslt-devel ``` +If you are running Arch Linux, you're done with: + +```bash +$ sudo pacman -S libxml2 libxslt +``` + +On FreeBSD, you just have to run: + +```bash +# pkg_add -r libxml2 libxslt +``` + +Alternatively, you can install the `textproc/libxml2` and `textproc/libxslt` +ports. + If you have any problems with these libraries, you can install them manually by compiling the source code. Just follow the instructions at the [Red Hat/CentOS section of the Nokogiri tutorials](http://nokogiri.org/tutorials/installing_nokogiri.html#red_hat__centos) . -Also, SQLite3 and its development files for the `sqlite3-ruby` gem — in Ubuntu you're done with just +Also, SQLite3 and its development files for the `sqlite3` gem — in Ubuntu you're done with just ```bash $ sudo apt-get install sqlite3 libsqlite3-dev @@ -71,6 +86,20 @@ And if you are on Fedora or CentOS, you're done with $ sudo yum install sqlite3 sqlite3-devel ``` +If you are on Arch Linux, you will need to run: + +```bash +$ sudo pacman -S sqlite +``` + +For FreeBSD users, you're done with: + +```bash +# pkg_add -r sqlite3 +``` + +Or compile the `databases/sqlite3` port. + Get a recent version of [Bundler](http://gembundler.com/) ```bash @@ -137,6 +166,25 @@ $ sudo yum install mysql-server mysql-devel $ sudo yum install postgresql-server postgresql-devel ``` +If you are running Arch Linux, MySQL isn't supported anymore so you will need to +use MariaDB instead (see [this announcement](https://www.archlinux.org/news/mariadb-replaces-mysql-in-repositories/)): + +```bash +$ sudo pacman -S mariadb libmariadbclient mariadb-clients +$ sudo pacman -S postgresql postgresql-libs +``` + +FreeBSD users will have to run the following: + +```bash +# pkg_add -r mysql56-client mysql56-server +# pkg_add -r postgresql92-client postgresql92-server +``` + +Or install them through ports (they are located under the `databases` folder). +If you run into troubles during the installation of MySQL, please see +[the MySQL documentation](http://dev.mysql.com/doc/refman/5.1/en/freebsd-installation.html). + After that, run: ```bash diff --git a/guides/source/engines.md b/guides/source/engines.md index d714f84731..a77be917a2 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -393,10 +393,15 @@ The form will be making a `POST` request to `/posts/:post_id/comments`, which wi ```ruby def create @post = Post.find(params[:post_id]) - @comment = @post.comments.create(params[:comment]) + @comment = @post.comments.create(comment_params) flash[:notice] = "Comment has been created!" redirect_to posts_path end + +private +def comment_params + params.require(:comment).permit(:text) +end ``` This is the final part required to get the new comment form working. Displaying the comments however, is not quite right yet. If you were to create a comment right now you would see this error: diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 9b2fa315a1..58bf8bbe90 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -575,6 +575,8 @@ If you submit the form again now, Rails will complain about not finding the `show` action. That's not very useful though, so let's add the `show` action before proceeding. +First we need to add a new `route` in `config/routes.rb`. + ```ruby post GET /posts/:id(.:format) posts#show ``` @@ -972,7 +974,7 @@ appear next to the "Show" link: <tr> <td><%= post.title %></td> <td><%= post.text %></td> - <td><%= link_to 'Show', post_path(post) %></td> + <td><%= link_to 'Show', post %></td> <td><%= link_to 'Edit', edit_post_path(post) %></td> </tr> <% end %> diff --git a/guides/source/i18n.md b/guides/source/i18n.md index 2b116c337a..046c7543f3 100644 --- a/guides/source/i18n.md +++ b/guides/source/i18n.md @@ -97,7 +97,7 @@ en: hello: "Hello world" ``` -This means, that in the `:en` locale, the key _hello_ will map to the _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Record validation messages in the [`activerecord/lib/active_record/locale/en.yml`](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml file or time and date formats in the [`activesupport/lib/active_support/locale/en.yml`](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml) file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend. +This means, that in the `:en` locale, the key _hello_ will map to the _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Record validation messages in the [`activerecord/lib/active_record/locale/en.yml`](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml) file or time and date formats in the [`activesupport/lib/active_support/locale/en.yml`](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml) file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend. The I18n library will use **English** as a **default locale**, i.e. if you don't set a different locale, `:en` will be used for looking up translations. @@ -137,7 +137,7 @@ If you want to translate your Rails application to a **single language other tha However, you would probably like to **provide support for more locales** in your application. In such case, you need to set and pass the locale between requests. -WARNING: You may be tempted to store the chosen locale in a _session_ or a <em>cookie</em>, however **do not do this**. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being [<em>RESTful</em>](http://en.wikipedia.org/wiki/Representational_State_Transfer. Read more about the RESTful approach in [Stefan Tilkov's articles](http://www.infoq.com/articles/rest-introduction). Sometimes there are exceptions to this rule and those are discussed below. +WARNING: You may be tempted to store the chosen locale in a _session_ or a <em>cookie</em>, however **do not do this**. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being [<em>RESTful</em>](http://en.wikipedia.org/wiki/Representational_State_Transfer). Read more about the RESTful approach in [Stefan Tilkov's articles](http://www.infoq.com/articles/rest-introduction). Sometimes there are exceptions to this rule and those are discussed below. The _setting part_ is easy. You can set the locale in a `before_action` in the `ApplicationController` like this: diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md index 5b6e5387ff..b5d66d08ba 100644 --- a/guides/source/layouts_and_rendering.md +++ b/guides/source/layouts_and_rendering.md @@ -375,9 +375,9 @@ Rails understands both numeric status codes and the corresponding symbols shown | | 423 | :locked | | | 424 | :failed_dependency | | | 426 | :upgrade_required | -| | 423 | :precondition_required | -| | 424 | :too_many_requests | -| | 426 | :request_header_fields_too_large | +| | 428 | :precondition_required | +| | 429 | :too_many_requests | +| | 431 | :request_header_fields_too_large | | **Server Error** | 500 | :internal_server_error | | | 501 | :not_implemented | | | 502 | :bad_gateway | diff --git a/guides/source/plugins.md b/guides/source/plugins.md index 695f25f8a9..9077e424c8 100644 --- a/guides/source/plugins.md +++ b/guides/source/plugins.md @@ -68,7 +68,7 @@ In this example you will add a method to String named `to_squawk`. To begin, cre require 'test_helper' -class CoreExtTest < Test::Unit::TestCase +class CoreExtTest < ActiveSupport::TestCase def test_to_squawk_prepends_the_word_squawk assert_equal "squawk! Hello World", "Hello World".to_squawk end @@ -136,7 +136,7 @@ To begin, set up your files so that you have: require 'test_helper' -class ActsAsYaffleTest < Test::Unit::TestCase +class ActsAsYaffleTest < ActiveSupport::TestCase end ``` @@ -173,7 +173,7 @@ To start out, write a failing test that shows the behavior you'd like: require 'test_helper' -class ActsAsYaffleTest < Test::Unit::TestCase +class ActsAsYaffleTest < ActiveSupport::TestCase def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field @@ -321,7 +321,7 @@ To start out, write a failing test that shows the behavior you'd like: # yaffle/test/acts_as_yaffle_test.rb require 'test_helper' -class ActsAsYaffleTest < Test::Unit::TestCase +class ActsAsYaffleTest < ActiveSupport::TestCase def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index b1a7865d10..642c70fd9d 100644 --- a/guides/source/rails_on_rack.md +++ b/guides/source/rails_on_rack.md @@ -5,7 +5,6 @@ This guide covers Rails integration with Rack and interfacing with other Rack co After reading this guide, you will know: -* How to create Rails Metal applications. * How to use Rack Middlewares in your Rails applications. * Action Pack's internal Middleware stack. * How to define a custom Middleware stack. @@ -119,6 +118,7 @@ $ rake middleware For a freshly generated Rails application, this might produce something like: ```ruby +use Rack::Sendfile use ActionDispatch::Static use Rack::Lock use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x000000029a0838> diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 5992e94cd8..73c783085e 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -151,11 +151,11 @@ Rails 4.0 no longer supports loading plugins from `vendor/plugins`. You must rep * The `delete` method in collection associations can now receive `Fixnum` or `String` arguments as record ids, besides records, pretty much like the `destroy` method does. Previously it raised `ActiveRecord::AssociationTypeMismatch` for such arguments. From Rails 4.0 on `delete` automatically tries to find the records matching the given ids before deleting them. -* Rails 4.0 has changed how orders get stacked in `ActiveRecord::Relation`. In previous versions of Rails, the new order was applied after the previously defined order. But this is no longer true. Check [Active Record Query guide](active_record_querying.html#ordering) for more information. +* In Rails 4.0 when a column or a table is renamed the related indexes are also renamed. If you have migrations which rename the indexes, they are no longer needed. * Rails 4.0 has changed `serialized_attributes` and `attr_readonly` to class methods only. You shouldn't use instance methods since it's now deprecated. You should change them to use class methods, e.g. `self.serialized_attributes` to `self.class.serialized_attributes`. -* Rails 4.0 has removed `attr_accessible` and `attr_protected` feature in favor of Strong Parameters. You can use the [Protected Attributes gem](https://github.com/rails/protected_attributes) to a smoothly upgrade path. +* Rails 4.0 has removed `attr_accessible` and `attr_protected` feature in favor of Strong Parameters. You can use the [Protected Attributes gem](https://github.com/rails/protected_attributes) for a smooth upgrade path. * If you are not using Protected Attributes, you can remove any options related to this gem such as `whitelist_attributes` or `mass_assignment_sanitizer` options. @@ -320,7 +320,7 @@ config.assets.js_compressor = :uglifier ### sass-rails -* `asset_url` with two arguments is deprecated. For example: `asset-url("rails.png", image)` becomes `asset-url("rails.png")` +* `asset-url` with two arguments is deprecated. For example: `asset-url("rails.png", image)` becomes `asset-url("rails.png")` Upgrading from Rails 3.1 to Rails 3.2 ------------------------------------- |