diff options
author | Vijay Dev <vijaydev.cse@gmail.com> | 2012-01-04 20:19:25 +0530 |
---|---|---|
committer | Vijay Dev <vijaydev.cse@gmail.com> | 2012-01-04 20:19:25 +0530 |
commit | 40cf1269074a181a23f362a910dfaf2a02f7e562 (patch) | |
tree | 31751bcb3dfe284d46d44e91e1cca9813becd459 | |
parent | 52303019cba0c82e4ee227ffec0640ee26986957 (diff) | |
parent | 6fca9315ca3706e30da73c230a1b2908652200d7 (diff) | |
download | rails-40cf1269074a181a23f362a910dfaf2a02f7e562.tar.gz rails-40cf1269074a181a23f362a910dfaf2a02f7e562.tar.bz2 rails-40cf1269074a181a23f362a910dfaf2a02f7e562.zip |
Merge branch 'master' of github.com:lifo/docrails
-rw-r--r-- | actionpack/lib/action_view/helpers/number_helper.rb | 73 | ||||
-rw-r--r-- | railties/guides/source/asset_pipeline.textile | 114 |
2 files changed, 112 insertions, 75 deletions
diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb index 1c0fdb8ff9..3db1394df7 100644 --- a/actionpack/lib/action_view/helpers/number_helper.rb +++ b/actionpack/lib/action_view/helpers/number_helper.rb @@ -32,22 +32,29 @@ module ActionView # in the +options+ hash. # # ==== Options - # * <tt>:area_code</tt> - Adds parentheses around the area code. - # * <tt>:delimiter</tt> - Specifies the delimiter to use (defaults to "-"). - # * <tt>:extension</tt> - Specifies an extension to add to the end of the - # generated number. + # + # * <tt>:area_code</tt> - Adds parentheses around the area code. + # * <tt>:delimiter</tt> - Specifies the delimiter to use (defaults to "-"). + # * <tt>:extension</tt> - Specifies an extension to add to the end of the + # generated number. # * <tt>:country_code</tt> - Sets the country code for the phone number. + # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. # # ==== Examples + # # number_to_phone(5551234) # => 555-1234 + # number_to_phone("5551234") # => 555-1234 # number_to_phone(1235551234) # => 123-555-1234 # number_to_phone(1235551234, :area_code => true) # => (123) 555-1234 # number_to_phone(1235551234, :delimiter => " ") # => 123 555 1234 # number_to_phone(1235551234, :area_code => true, :extension => 555) # => (123) 555-1234 x 555 # number_to_phone(1235551234, :country_code => 1) # => +1-123-555-1234 + # number_to_phone("123a456") # => 123a456 + # + # number_to_phone("1234a567", :raise => true) # => InvalidNumberError # # number_to_phone(1235551234, :country_code => 1, :extension => 1343, :delimiter => ".") - # => +1.123.555.1234 x 1343 + # # => +1.123.555.1234 x 1343 def number_to_phone(number, options = {}) return unless number @@ -82,6 +89,7 @@ module ActionView # in the +options+ hash. # # ==== Options + # # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale). # * <tt>:precision</tt> - Sets the level of precision (defaults to 2). # * <tt>:unit</tt> - Sets the denomination of the currency (defaults to "$"). @@ -94,12 +102,17 @@ module ActionView # an hyphen to the formatted number given by <tt>:format</tt>). # Accepts the same fields than <tt>:format</tt>, except # <tt>%n</tt> is here the absolute value of the number. + # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. # # ==== Examples + # # number_to_currency(1234567890.50) # => $1,234,567,890.50 # number_to_currency(1234567890.506) # => $1,234,567,890.51 # number_to_currency(1234567890.506, :precision => 3) # => $1,234,567,890.506 # number_to_currency(1234567890.506, :locale => :fr) # => 1 234 567 890,51 € + # number_to_currency("123a456") # => $123a456 + # + # number_to_currency("123a456", :raise => true) # => InvalidNumberError # # number_to_currency(-1234567890.50, :negative_format => "(%u%n)") # # => ($1,234,567,890.50) @@ -141,23 +154,33 @@ module ActionView end - # Formats a +number+ as a percentage string (e.g., 65%). You can customize the - # format in the +options+ hash. + # Formats a +number+ as a percentage string (e.g., 65%). You can customize the format in the +options+ hash. # # ==== Options - # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale). - # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3). - # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, the # of fractional digits (defaults to +false+) - # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to "."). - # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ""). - # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator (defaults to +false+) + # + # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current + # locale). + # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3). + # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, + # the # of fractional digits (defaults to +false+). + # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults + # to "."). + # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ""). + # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator + # (defaults to +false+). + # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. # # ==== Examples + # # number_to_percentage(100) # => 100.000% + # number_to_percentage("98") # => 98.000% # number_to_percentage(100, :precision => 0) # => 100% # number_to_percentage(1000, :delimiter => '.', :separator => ',') # => 1.000,000% # number_to_percentage(302.24398923423, :precision => 5) # => 302.24399% # number_to_percentage(1000, :locale => :fr) # => 1 000,000% + # number_to_percentage("98a") # => 98a% + # + # number_to_percentage("98a", :raise => true) # => InvalidNumberError def number_to_percentage(number, options = {}) return unless number @@ -184,19 +207,26 @@ module ActionView # customize the format in the +options+ hash. # # ==== Options + # # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale). # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ","). # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to "."). + # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. # # ==== Examples + # # number_with_delimiter(12345678) # => 12,345,678 + # number_with_delimiter("123456") # => 123,456 # number_with_delimiter(12345678.05) # => 12,345,678.05 # number_with_delimiter(12345678, :delimiter => ".") # => 12.345.678 # number_with_delimiter(12345678, :delimiter => ",") # => 12,345,678 # number_with_delimiter(12345678.05, :separator => " ") # => 12,345,678 05 # number_with_delimiter(12345678.05, :locale => :fr) # => 12 345 678,05 + # number_with_delimiter("112a") # => 112a # number_with_delimiter(98765432.98, :delimiter => " ", :separator => ",") # # => 98 765 432,98 + # + # number_with_delimiter("112a", :raise => true) # => raise InvalidNumberError def number_with_delimiter(number, options = {}) options.symbolize_keys! @@ -224,12 +254,15 @@ module ActionView # You can customize the format in the +options+ hash. # # ==== Options - # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale). - # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3). - # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, the # of fractional digits (defaults to +false+) - # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to "."). - # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ""). - # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator (defaults to +false+) + # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale). + # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3). + # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, + # the # of fractional digits (defaults to +false+). + # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults + # to "."). + # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ""). + # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator + # (defaults to +false+). # # ==== Examples # number_with_precision(111.2345) # => 111.235 @@ -240,8 +273,10 @@ module ActionView # number_with_precision(111.2345, :precision => 1, :significant => true) # => 100 # number_with_precision(13, :precision => 5, :significant => true) # => 13.000 # number_with_precision(111.234, :locale => :fr) # => 111,234 + # # number_with_precision(13, :precision => 5, :significant => true, :strip_insignificant_zeros => true) # # => 13 + # # number_with_precision(389.32314, :precision => 4, :significant => true) # => 389.3 # number_with_precision(1111.2345, :precision => 2, :separator => ',', :delimiter => '.') # # => 1.111,23 diff --git a/railties/guides/source/asset_pipeline.textile b/railties/guides/source/asset_pipeline.textile index 05cb8888a0..da7d46ef71 100644 --- a/railties/guides/source/asset_pipeline.textile +++ b/railties/guides/source/asset_pipeline.textile @@ -6,7 +6,7 @@ By referring to this guide you will be able to: * Understand what the asset pipeline is and what it does * Properly organize your application assets * Understand the benefits of the asset pipeline -* Adding a pre-processor to the pipeline +* Add a pre-processor to the pipeline * Package assets with a gem endprologue. @@ -17,7 +17,7 @@ The asset pipeline provides a framework to concatenate and minify or compress Ja Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets. Rails 3.1 is integrated with Sprockets through Action Pack which depends on the +sprockets+ gem, by default. -By having this as a core feature of Rails, 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. +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. In Rails 3.1, the asset pipeline is enabled by default. It can be disabled in +config/application.rb+ by putting this line inside the application class definition: @@ -25,34 +25,34 @@ In Rails 3.1, the asset pipeline is enabled by default. It can be disabled in +c config.assets.enabled = false </ruby> -You can also disable it while creating a new application by passing the <tt>--skip-sprockets</tt> option. +You can also disable the asset pipeline while creating a new application by passing the <tt>--skip-sprockets</tt> option. <plain> rails new appname --skip-sprockets </plain> -It is recommended that you use the defaults for all new apps. +You should use the defaults for all new applications unless you have a specific reason to avoid the asset pipeline. h4. Main Features -The first feature of the pipeline is to concatenate assets. This is important in a production environment, as it reduces the number of requests that a browser must make to render a web page. +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 must make 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. -While Rails already has a feature to concatenate these types of assets by placing +:cache => true+ at the end of tags such as +javascript_include_tag+ and +stylesheet_link_tag+, it has a series of limitations. For example, it cannot generate the caches in advance, and it is not able to transparently include assets provided by third-party libraries. +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. -The default behavior in Rails 3.1 and onward is to concatenate all files into one master file each for JS and CSS. However, you can separate files or groups of files if required (see below). In production, an MD5 fingerprint is inserted into each filename so that the file is cached by the web browser but can be invalidated if the fingerprint is altered. +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 second feature is to minify or compress assets. For CSS, this usually involves 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 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 is the ability to code these assets using another language, or language extension. These include Sass for CSS, CoffeeScript for JavaScript, and ERB for both. +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. h4. What is Fingerprinting and Why Should I Care? -Fingerprinting is a technique whereby the filenames of content that is static or infrequently updated are altered to be unique to the content contained in the file. +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 (at ISPs, in browsers) to keep their own copy of the content. When the content is updated, the fingerprint will change and the remote clients will request the new file. 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 most effective technique is to insert a hash of the content into the name, usually at the end. For example a CSS file +global.css+ is hashed and the filename is updated to incorporate the digest, for example becoming: +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: <plain> global-908e25f4bf641868d8683022a5b62f54.css @@ -60,28 +60,30 @@ global-908e25f4bf641868d8683022a5b62f54.css This is the strategy adopted by the Rails asset pipeline. -Rails' old strategy was to append a 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: <plain> /stylesheets/global.css?1309495796 </plain> -This has several disadvantages: +The query string strategy has several disadvantages: <ol> <li> - <strong>Not all caches will cache content with a query string</strong>.<br> + <strong>Not all caches will reliably cache content where the filename only differs by query parameters</strong>.<br> "Steve Souders recommends":http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/, "...avoiding a querystring for cacheable resources". He found that in this case 5-20% of requests will not be cached. Query strings in particular do not work at all with some CDNs for cache invalidation. </li> <li> <strong>The file name can change between nodes in multi-server environments.</strong><br> - The query string in Rails 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. + </li> + <li> + <strong>Too much cache invalidation</strong><br /> + When static assets are deployed with each new release of code, the mtime of _all_ these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed. </li> </ol> -The other problem is that when static assets are deployed with each new release of code, the mtime of _all_ these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed. - -Fingerprinting fixes these problems by avoiding query strings, and by ensuring 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. @@ -95,19 +97,19 @@ h3. 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. -This is not to say that assets can (or should) no longer be placed in +public+; they still can be and will be served as static files by the application or web server. You would only use +app/assets+ if you wish your files to 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, the default is to precompile these files to +public/assets+ so that they can be more efficiently delivered by the web server. +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. -When a scaffold or controller is generated for the application, 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. +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 a +ProjectsController+ is generated, there will be a new file at +app/assets/javascripts/projects.js.coffee+ and another at +app/assets/stylesheets/projects.css.scss+. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as +<%= javascript_include_tag params[:controller] %>+ or +<%= stylesheet_link_tag params[: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+. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as +<%= javascript_include_tag params[:controller] %>+ or +<%= stylesheet_link_tag params[:controller] %>+. -NOTE: You will need an "ExecJS":https://github.com/sstephenson/execjs#readme 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. +NOTE: You must have an "ExecJS":https://github.com/sstephenson/execjs#readme 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. h4. Asset Organization -Assets can be placed inside an application in one of three locations: +app/assets+, +lib/assets+ or +vendor/assets+. +Assets that must be precompiled 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. @@ -115,7 +117,7 @@ Assets can be placed inside an application in one of three locations: +app/asset +vendor/assets+ is for assets that are owned by outside entities, such as code for JavaScript plugins. -All subdirectories that exist within these three locations are added to the search path for Sprockets (visible by calling +Rails.application.config.assets.paths+ in a console). When an asset is requested, these paths are traversed to see if they contain an asset matching the name specified. Once an asset has been found, it's processed by Sprockets and served. +All subdirectories that exist within these three locations are added to the search path for Sprockets. You can see this search path by inspecting +Rails.application.config.assets.paths+ in the Rails console. When a client requests an asset, these paths are traversed (in the order that they occur in the search path) to see if they contain an asset matching the name specified. If an asset is found, it's processed by Sprockets and served. You can add additional (fully qualified) paths to the pipeline in +config/application.rb+. For example: @@ -138,7 +140,7 @@ In regular views you can access images in the +assets/images+ directory like thi <%= image_tag "rails.png" %> </erb> -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 webserver. +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. @@ -152,7 +154,7 @@ Images can also be organized into subdirectories if required, and they can be ac h5. CSS and ERB -If you add an +erb+ extension to a CSS asset, making it something such as +application.css.erb+, then helpers like +asset_path+ are available in your CSS rules: +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: <plain> .class { background-image: url(<%= asset_path 'image.png' %>) } @@ -202,9 +204,9 @@ $('#logo').attr src: "<%= asset_path('logo.png') %>" h4. 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 are greatly reduced as there are fewer requests to make. +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. -For example, in the default Rails application there's a +app/assets/javascripts/application.js+ file which contains the following lines: +For example, a new Rails application includes a default +app/assets/javascripts/application.js+ file which contains the following lines: <plain> // ... @@ -217,11 +219,11 @@ In JavaScript files, the directives begin with +//=+. In this case, the file is NOTE. In Rails 3.1 the +jquery-rails+ gem provides the +jquery.js+ and +jquery_ujs.js+ files via the asset pipeline. You won't see them in the application tree. -The +require_tree+ directive tells Sprockets to recursively include _all_ JavaScript files in this directory into the output. Only a path relative to the manifest file can be specified. There is also a +require_directory+ directive which includes all JavaScript files only in the directory specified (no nesting). +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, require it before in the manifest. Note that the family of +require+ directives prevents files from being included twice in the output. +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. -There's also a default +app/assets/stylesheets/application.css+ file which contains these lines: +Rails also creates a default +app/assets/stylesheets/application.css+ file which contains these lines: <plain> /* ... @@ -230,15 +232,15 @@ There's also a default +app/assets/stylesheets/application.css+ file which conta */ </plain> -The directives that work in the JavaScript files also work in stylesheets, obviously including stylesheets rather than JavaScript files. The +require_tree+ directive here works the same way as the JavaScript one, requiring all stylesheets from the current directory. +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. 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, use the "Sass +@import+ rule":http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import instead of the 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. -The same remarks about ordering made above apply. In particular, you can specify individual files and they are compiled in the order specified: +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: <plain> /* ... @@ -312,7 +314,7 @@ You could potentially also enable compression in development mode as a sanity ch h3. In Production -In the production environment Rails uses the fingerprinting scheme outlined above. By default it is assumed that assets have been precompiled and will be served as static assets by your web server. +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. 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. @@ -330,7 +332,7 @@ generates something like this: <link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen" rel="stylesheet" type="text/css" /> </html> -The fingerprinting behavior is controlled by the setting of +config.assets.digest+ setting in Rails (which is +true+ for production, +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. @@ -338,9 +340,9 @@ h4. Precompiling Assets Rails comes bundled with a rake task to compile the asset manifests and other files in the pipeline to the disk. -Compiled assets are written to the location specified in +config.assets.prefix+. The default setting will use the +public/assets+ directory. +Compiled assets are written to the location specified in +config.assets.prefix+. By default, this is the +public/assets+ directory. -You must use this task either during deployment or locally if you do not have write access to your production filesystem. +You can call this task on the server during deployment to create compiled versions of your assets directly on the server. If you do not have write access to your production file system, you can call this task locally and then deploy the compiled assets. The rake task is: @@ -357,7 +359,7 @@ test +rake assets:precompile+ locally before deploying. It may expose bugs where your assets reference application objects or methods, since those are still in scope in development mode regardless of the value of this flag. -Capistrano (v2.8.0 and above) has a recipe to handle this in deployment. Add the following line to +Capfile+: +Capistrano (v2.8.0 and above) includes a recipe to handle this in deployment. Add the following line to +Capfile+: <erb> load 'deploy/assets' @@ -381,7 +383,7 @@ If you have other manifests or individual stylesheets and JavaScript files to in config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js'] </erb> -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 and avoids handing the mapping requests back to Sprockets. A typical manifest file looks like: +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: <plain> --- @@ -404,7 +406,7 @@ NOTE: If there are missing precompiled files in production you will get an <tt>S h5. Server Configuration -Precompiled assets exist on the filesystem and are served directly by your webserver. 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 them. For Apache: @@ -451,7 +453,7 @@ This directive is available if the core module that provides this feature was co If you're compiling nginx with Phusion Passenger you'll need to pass that option when prompted. -Unfortunately, a robust configuration for Apache is possible but tricky; please Google around. +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.) h4. Live Compilation @@ -467,9 +469,9 @@ On the first request the assets are compiled and cached as outlined in developme 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 poorer than the default and is not recommended. +This mode uses more memory, performs more poorly than the default and is not recommended. -When 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: <plain> group :production do @@ -495,7 +497,7 @@ h4. 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. -The default Gemfile includes "uglifier":https://github.com/lautis/uglifier. This gem wraps "UglifierJS":https://github.com/mishoo/UglifyJS (written for NodeJS) in Ruby. It compresses your code by removing white space and other magical things like changing your +if+ and +else+ statements to ternary operators where possible. +The default Gemfile includes "uglifier":https://github.com/lautis/uglifier. This gem wraps "UglifierJS":https://github.com/mishoo/UglifyJS (written for NodeJS) in Ruby. It compresses your code by removing white space. It also includes other optimizations such as changing your +if+ and +else+ statements to ternary operators where possible. The following line invokes +uglifier+ for JavaScript compression. @@ -503,13 +505,13 @@ The following line invokes +uglifier+ for JavaScript compression. config.assets.js_compressor = :uglifier </erb> -The +config.assets.compress+ must be set to +true+ to enable JavaScript compression +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. Check "ExecJS":https://github.com/sstephenson/execjs#readme documentation to know all supported JavaScript runtimes. +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. h4. 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. <erb> class Transformer @@ -519,7 +521,7 @@ class Transformer end </erb> -To enable this, pass a +new+ Object to the config option in +application.rb+: +To enable this, pass a +new+ object to the config option in +application.rb+: <erb> config.assets.css_compressor = Transformer.new @@ -536,13 +538,13 @@ This can be changed to something else: config.assets.prefix = "/some_other_path" </erb> -This is a handy option if you have any existing project (pre Rails 3.1) 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 existing project (pre Rails 3.1) that already uses this path or you wish to use this path for a new resource. h4. 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. -Apache and nginx support this option which is enabled in <tt>config/environments/production.rb</tt>. +Apache and nginx support this option, which can be enabled in <tt>config/environments/production.rb</tt>. <erb> # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache @@ -619,7 +621,7 @@ config.assets.digest = true # config.assets.precompile += %w( search.js ) </erb> -There are no changes to +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. +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. The following should also be added to +Gemfile+: @@ -633,7 +635,7 @@ group :assets do end </plain> -If you use the +assets+ group with Bundler, please make sure that your +config/application.rb+ has the following Bundler require statement. +If you use the +assets+ group with Bundler, please make sure that your +config/application.rb+ has the following Bundler require statement: <ruby> if defined?(Bundler) @@ -644,7 +646,7 @@ if defined?(Bundler) end </ruby> -Instead of the old Rails 3.0 one +Instead of the old Rails 3.0 version: <ruby> # If you have a Gemfile, require the gems listed there, including any gems |