railties 3.1.0.rc5 → 3.1.0.rc6

Sign up to get free protection for your applications and to get access to all the features.
Files changed (35) hide show
  1. data/guides/rails_guides/generator.rb +4 -44
  2. data/guides/rails_guides/textile_extensions.rb +22 -3
  3. data/guides/source/3_1_release_notes.textile +429 -0
  4. data/guides/source/action_mailer_basics.textile +4 -2
  5. data/guides/source/active_record_validations_callbacks.textile +56 -13
  6. data/guides/source/active_resource_basics.textile +74 -0
  7. data/guides/source/active_support_core_extensions.textile +36 -0
  8. data/guides/source/asset_pipeline.textile +59 -60
  9. data/guides/source/command_line.textile +3 -1
  10. data/guides/source/configuring.textile +1 -1
  11. data/guides/source/getting_started.textile +11 -15
  12. data/guides/source/i18n.textile +1 -1
  13. data/guides/source/initialization.textile +4 -3
  14. data/guides/source/layouts_and_rendering.textile +2 -2
  15. data/guides/source/migrations.textile +23 -23
  16. data/guides/source/rails_application_templates.textile +1 -7
  17. data/lib/rails/application.rb +1 -3
  18. data/lib/rails/application/configuration.rb +1 -0
  19. data/lib/rails/engine.rb +3 -3
  20. data/lib/rails/generators/app_base.rb +12 -0
  21. data/lib/rails/generators/rails/app/templates/Gemfile +1 -8
  22. data/lib/rails/generators/rails/app/templates/config/application.rb +6 -4
  23. data/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +2 -2
  24. data/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt +7 -3
  25. data/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb +2 -2
  26. data/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec +22 -7
  27. data/lib/rails/generators/rails/plugin_new/templates/Gemfile +13 -7
  28. data/lib/rails/generators/rails/plugin_new/templates/app/mailers/.empty_directory +0 -0
  29. data/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/{application.html.erb.tt → %name%/application.html.erb.tt} +0 -0
  30. data/lib/rails/generators/rails/plugin_new/templates/lib/%name%/version.rb +3 -0
  31. data/lib/rails/paths.rb +4 -0
  32. data/lib/rails/railtie.rb +1 -0
  33. data/lib/rails/tasks/misc.rake +1 -1
  34. data/lib/rails/version.rb +1 -1
  35. metadata +34 -12
@@ -242,11 +242,11 @@ end
242
242
 
243
243
  h5. Sending Email To Multiple Recipients
244
244
 
245
- It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The <tt>to:</tt> key however expects a string so you have join the list of recipients using a comma.
245
+ It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The list of emails can be an array of email addresses or a single string with the addresses separated by commas.
246
246
 
247
247
  <ruby>
248
248
  class AdminMailer < ActionMailer::Base
249
- default :to => Admin.all.map(&:email).join(", "),
249
+ default :to => Admin.all.map(&:email),
250
250
  :from => "notification@example.com"
251
251
 
252
252
  def new_registration(user)
@@ -256,6 +256,8 @@ It is possible to send email to one or more recipients in one email (for e.g. in
256
256
  end
257
257
  </ruby>
258
258
 
259
+ The same format can be used to set carbon copy (Cc:) and blind carbon copy (Bcc:) recipients, by using the <tt>:cc</tt> and <tt>:bcc</tt> keys respectively.
260
+
259
261
  h5. Sending Email With Name
260
262
 
261
263
  Sometimes you wish to show the name of the person instead of just their email address when they receive the email. The trick to doing that is
@@ -569,11 +569,50 @@ end
569
569
 
570
570
  All validations inside of +with_options+ block will have automatically passed the condition +:if => :is_admin?+
571
571
 
572
- h3. Creating Custom Validation Methods
572
+ h3. Performing Custom Validations
573
573
 
574
- When the built-in validation helpers are not enough for your needs, you can write your own validation methods.
574
+ When the built-in validation helpers are not enough for your needs, you can write your own validators or validation methods as you prefer.
575
575
 
576
- Simply create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names.
576
+ h4. Custom Validators
577
+
578
+ Custom validators are classes that extend <tt>ActiveModel::Validator</tt>. These classes must implement a +validate+ method which takes a record as an argument and performs the validation on it. The custom validator is called using the +validates_with+ method.
579
+
580
+ <ruby>
581
+ class MyValidator < ActiveModel::Validator
582
+ def validate(record)
583
+ if record.name.starts_with? 'X'
584
+ record.errors[:name] << 'Need a name starting with X please!'
585
+ end
586
+ end
587
+ end
588
+
589
+ class Person
590
+ include ActiveModel::Validations
591
+ validates_with MyValidator
592
+ end
593
+ </ruby>
594
+
595
+ The easiest way to add custom validators for validating individual attributes is with the convenient <tt>ActiveModel::EachValidator</tt>. In this case, the custom validator class must implement a +validate_each+ method which takes three arguments: record, attribute and value which correspond to the instance, the attribute to be validated and the value of the attribute in the passed instance.
596
+
597
+ <ruby>
598
+ class EmailValidator < ActiveModel::EachValidator
599
+ def validate_each(record, attribute, value)
600
+ unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
601
+ record.errors[attribute] << (options[:message] || "is not an email")
602
+ end
603
+ end
604
+ end
605
+
606
+ class Person < ActiveRecord::Base
607
+ validates :email, :presence => true, :email => true
608
+ end
609
+ </ruby>
610
+
611
+ As shown in the example, you can also combine standard validations with your own custom validators.
612
+
613
+ h4. Custom Methods
614
+
615
+ You can also create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names.
577
616
 
578
617
  You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.
579
618
 
@@ -583,13 +622,15 @@ class Invoice < ActiveRecord::Base
583
622
  :discount_cannot_be_greater_than_total_value
584
623
 
585
624
  def expiration_date_cannot_be_in_the_past
586
- errors.add(:expiration_date, "can't be in the past") if
587
- !expiration_date.blank? and expiration_date < Date.today
625
+ if !expiration_date.blank? and expiration_date < Date.today
626
+ errors.add(:expiration_date, "can't be in the past")
627
+ end
588
628
  end
589
629
 
590
630
  def discount_cannot_be_greater_than_total_value
591
- errors.add(:discount, "can't be greater than total value") if
592
- discount > total_value
631
+ if discount > total_value
632
+ errors.add(:discount, "can't be greater than total value")
633
+ end
593
634
  end
594
635
  end
595
636
  </ruby>
@@ -710,8 +751,6 @@ class Person < ActiveRecord::Base
710
751
  end
711
752
  </ruby>
712
753
 
713
-
714
-
715
754
  h4. +errors.clear+
716
755
 
717
756
  The +clear+ method is used when you intentionally want to clear all the messages in the +errors+ collection. Of course, calling +errors.clear+ upon an invalid object won't actually make it valid: the +errors+ collection will now be empty, but the next time you call +valid?+ or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the +errors+ collection will be filled again.
@@ -758,6 +797,7 @@ h3. Displaying Validation Errors in the View
758
797
  Rails maintains an official plugin that provides helpers to display the error messages of your models in your view templates. You can install it as a plugin or as a Gem.
759
798
 
760
799
  h4. Installing as a plugin
800
+
761
801
  <shell>
762
802
  $ rails plugin install git://github.com/joelmoss/dynamic_form.git
763
803
  </shell>
@@ -765,6 +805,7 @@ $ rails plugin install git://github.com/joelmoss/dynamic_form.git
765
805
  h4. Installing as a Gem
766
806
 
767
807
  Add this line in your Gemfile:
808
+
768
809
  <ruby>
769
810
  gem "dynamic_form"
770
811
  </ruby>
@@ -1102,8 +1143,9 @@ Here's an example where we create a class with an +after_destroy+ callback for a
1102
1143
  <ruby>
1103
1144
  class PictureFileCallbacks
1104
1145
  def after_destroy(picture_file)
1105
- File.delete(picture_file.filepath)
1106
- if File.exists?(picture_file.filepath)
1146
+ if File.exists?(picture_file.filepath)
1147
+ File.delete(picture_file.filepath)
1148
+ end
1107
1149
  end
1108
1150
  end
1109
1151
  </ruby>
@@ -1121,8 +1163,9 @@ Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we
1121
1163
  <ruby>
1122
1164
  class PictureFileCallbacks
1123
1165
  def self.after_destroy(picture_file)
1124
- File.delete(picture_file.filepath)
1125
- if File.exists?(picture_file.filepath)
1166
+ if File.exists?(picture_file.filepath)
1167
+ File.delete(picture_file.filepath)
1168
+ end
1126
1169
  end
1127
1170
  end
1128
1171
  </ruby>
@@ -0,0 +1,74 @@
1
+ h2. Active Resource Basics
2
+
3
+ This guide should provide you with all you need to get started managing the connection between business objects and RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics.
4
+
5
+ endprologue.
6
+
7
+ WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
8
+
9
+ h3. Introduction
10
+
11
+ Active Resource allows you to connect with RESTful web services. So, in Rails, Resource classes inherited from +ActiveResource::Base+ and live in +app/models+.
12
+
13
+ h3. Configuration and Usage
14
+
15
+ Putting Active Resource to use is very similar to Active Record. It's as simple as creating a model class
16
+ that inherits from ActiveResource::Base and providing a <tt>site</tt> class variable to it:
17
+
18
+ <ruby>
19
+ class Person < ActiveResource::Base
20
+ self.site = "http://api.people.com:3000/"
21
+ end
22
+ </ruby>
23
+
24
+ Now the Person class is REST enabled and can invoke REST services very similarly to how Active Record invokes
25
+ life cycle methods that operate against a persistent store.
26
+
27
+ h3. Reading and Writing Data
28
+
29
+ Active Resource make request over HTTP using a standard JSON format. It mirrors the RESTful routing built into Action Controller but will also work with any other REST service that properly implements the protocol.
30
+
31
+ h4. Read
32
+
33
+ Read requests use the GET method and expect the JSON form of whatever resource/resources is/are being requested.
34
+
35
+ <ruby>
36
+ # Find a person with id = 1
37
+ person = Person.find(1)
38
+ # Check if a person exists with id = 1
39
+ Person.exists?(1) # => true
40
+ # Get all resources of Person class
41
+ Person.all
42
+ </ruby>
43
+
44
+ h4. Create
45
+
46
+ Creating a new resource submits the JSON form of the resource as the body of the request with HTTP POST method and parse the response into Active Resource object.
47
+
48
+ <ruby>
49
+ person = Person.create(:name => 'Vishnu')
50
+ person.id # => 1
51
+ </ruby>
52
+
53
+ h4. Update
54
+
55
+ To update an existing resource, 'save' method is used. This method make a HTTP PUT request in JSON format.
56
+
57
+ <ruby>
58
+ person = Person.find(1)
59
+ person.name = 'Atrai'
60
+ person.save
61
+ </ruby>
62
+
63
+ h4. Delete
64
+
65
+ 'destroy' method makes a HTTP DELETE request for an existing resource in JSON format to delete that resource.
66
+
67
+ <ruby>
68
+ person = Person.find(1)
69
+ person.destroy
70
+ </ruby>
71
+
72
+ h3. Changelog
73
+
74
+ * July 30, 2011: Initial version by "Vishnu Atrai":http://github.com/vatrai
@@ -2067,6 +2067,30 @@ shape_types = [Circle, Square, Triangle].sample(2)
2067
2067
 
2068
2068
  NOTE: Defined in +active_support/core_ext/array/random_access.rb+.
2069
2069
 
2070
+ h4. Adding Elements
2071
+
2072
+ h5. +prepend+
2073
+
2074
+ This method is an alias of <tt>Array#unshift</tt>.
2075
+
2076
+ <ruby>
2077
+ %w(a b c d).prepend('e') # => %w(e a b c d)
2078
+ [].prepend(10) # => [10]
2079
+ </ruby>
2080
+
2081
+ NOTE: Defined in +active_support/core_ext/array/prepend_and_append.rb+.
2082
+
2083
+ h5. +append+
2084
+
2085
+ This method is an alias of <tt>Array#<<</tt>.
2086
+
2087
+ <ruby>
2088
+ %w(a b c d).append('e') # => %w(a b c d e)
2089
+ [].append([1,2]) # => [[1,2]]
2090
+ </ruby>
2091
+
2092
+ NOTE: Defined in +active_support/core_ext/array/prepend_and_append.rb+.
2093
+
2070
2094
  h4. Options Extraction
2071
2095
 
2072
2096
  When the last argument in a method call is a hash, except perhaps for a +&block+ argument, Ruby allows you to omit the brackets:
@@ -2694,6 +2718,18 @@ hash # => {:a => 1}
2694
2718
 
2695
2719
  NOTE: Defined in +active_support/core_ext/hash/slice.rb+.
2696
2720
 
2721
+ h4. Extracting
2722
+
2723
+ The method +extract!+ removes and returns the key/value pairs matching the given keys.
2724
+
2725
+ <ruby>
2726
+ hash = {:a => 1, :b => 2}
2727
+ rest = hash.extract!(:a) # => {:a => 1}
2728
+ hash # => {:b => 2}
2729
+ </ruby>
2730
+
2731
+ NOTE: Defined in +active_support/core_ext/hash/slice.rb+.
2732
+
2697
2733
  h4. Indifferent Access
2698
2734
 
2699
2735
  The method +with_indifferent_access+ returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver:
@@ -1,6 +1,6 @@
1
1
  h2. Asset Pipeline
2
2
 
3
- This guide will cover the ideology of the asset pipeline introduced in Rails 3.1.
3
+ This guide covers the ideology of the asset pipeline introduced in Rails 3.1.
4
4
  By referring to this guide you will be able to:
5
5
 
6
6
  * Understand what the asset pipeline is and what it does
@@ -19,7 +19,7 @@ Prior to Rails 3.1 these features were added through third-party Ruby libraries
19
19
 
20
20
  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 2011 keynote at Railsconf.
21
21
 
22
- In new Rails 3.1 application the asset pipeline is enable by default. It can be disabled in +application.rb+ by putting this line inside the +Application+ class definition:
22
+ In new Rails 3.1 application the asset pipeline is enabled by default. It can be disabled in +application.rb+ by putting this line inside the +Application+ class definition:
23
23
 
24
24
  <plain>
25
25
  config.assets.enabled = false
@@ -30,19 +30,19 @@ It is recommended that you use the defaults for all new apps.
30
30
 
31
31
  h4. Main Features
32
32
 
33
- 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 needs to make to render a web page. While Rails already has a feature to concatenate these types of asset--by placing +:cache => true+ at the end of tags such as +javascript_include_tag+ and +stylesheet_link_tag+--, many people do not use it.
33
+ 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. While Rails already has a feature to concatenate these types of assetsi -- by placing +:cache => true+ at the end of tags such as +javascript_include_tag+ and +stylesheet_link_tag+ -- many people do not use it.
34
34
 
35
- 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.
35
+ 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.
36
36
 
37
- The second feature is to minify or compress. 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.
37
+ 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.
38
38
 
39
39
  The third feature is the ability to code these assets using another language, or language extension. These include SCSS or Sass for CSS, CoffeeScript for JavaScript, and ERB for both.
40
40
 
41
41
  h4. What is Fingerprinting and Why Should I Care?
42
42
 
43
- Fingerprinting is a technique where the filenames of content that is static or infrequently updated is altered to be unique to the content contained in the file.
43
+ Fingerprinting is a technique whereby the filenames of content that is static or infrequently updated is altered to be unique to the content contained in the file.
44
44
 
45
- 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 _cachebusting_.
45
+ 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 _cachebusting_.
46
46
 
47
47
  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 hash.
48
48
 
@@ -52,7 +52,7 @@ global.css => global-908e25f4bf641868d8683022a5b62f54.css
52
52
 
53
53
  This is the strategy adopted by the Rails asset pipeline.
54
54
 
55
- 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:
55
+ 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:
56
56
 
57
57
  <plain>
58
58
  /stylesheets/global.css?1309495796
@@ -73,7 +73,7 @@ This has several disadvantages:
73
73
 
74
74
  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.
75
75
 
76
- Fingerprinting avoids all these problems by ensuring filenames are consistent based on the content.
76
+ Fingerprinting avoids all these problems by ensuring filenames are consistent based on their content.
77
77
 
78
78
  More reading:
79
79
 
@@ -83,11 +83,11 @@ More reading:
83
83
 
84
84
  h3. How to Use the Asset Pipeline
85
85
 
86
- 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 will be served by the Sprockets middleware included in the sprockets gem.
86
+ 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.
87
87
 
88
88
  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.
89
89
 
90
- When a scaffold or controller is generated for the application, Rails will also generate a JavaScript file (or CoffeeScript if the +coffee-script+ gem is in the +Gemfile+) and a Cascading Style Sheet file (or SCSS if +sass-rails+ is in the +Gemfile+) file for that controller.
90
+ When a scaffold or controller is generated for the application, Rails also generates a JavaScript file (or CoffeeScript file if the +coffee-script+ gem is in the +Gemfile+) and a Cascading Style Sheet file (or SCSS file if +sass-rails+ is in the +Gemfile+) for that controller.
91
91
 
92
92
  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] %>+.
93
93
 
@@ -101,13 +101,13 @@ Assets can be placed inside an application in one of three locations: +app/asset
101
101
 
102
102
  +vendor/assets+ is for assets that are owned by outside entities, such as code for JavaScript plugins.
103
103
 
104
- All subdirectories that exist within these three locations will be 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 will be looked through to see if they contain an asset matching the name specified. Once an asset has been found, it's processed by Sprockets and served.
104
+ 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 looked through to see if they contain an asset matching the name specified. Once an asset has been found, it's processed by Sprockets and served.
105
105
 
106
106
  h4. Coding Links to Assets
107
107
 
108
- To access assets, we can use the same tags that we are generally familiar with:
108
+ To access assets, you use the same tags that you are generally familiar with:
109
109
 
110
- Sprockets does not add any new methods to require your assets, we still use the familiar +javascript_include_tag+ and +stylesheet_link_tag+.
110
+ Sprockets does not add any new methods to require your assets, you still use the familiar +javascript_include_tag+ and +stylesheet_link_tag+.
111
111
 
112
112
  <erb>
113
113
  <%= stylesheet_link_tag "application" %>
@@ -126,29 +126,29 @@ Images can be organized into directories if required, and they can be accessed b
126
126
  <%= image_tag "icons/rails.png" %>
127
127
  </erb>
128
128
 
129
- Providing that assets are enabled within our application (+config.assets.enabled+ in the current environment's file is not set to +false+), this file will be served by Sprockets unless a file at +public/assets/rails.png+ exists, in which case that file will be served.
129
+ Providing that assets are enabled within your application (+config.assets.enabled+ in the current environment's file is not set to +false+), this file is served by Sprockets unless a file at +public/assets/rails.png+ exists, in which case that file is served.
130
130
 
131
- Alternatively, a file with an MD5 hash after its name such as +public/assets/rails-af27b6a414e6da00003503148be9b409.png+ will also be picked up by Sprockets. How these hashes are generated is covered in the "Production Assets":#production_assets section later on in this guide.
131
+ Alternatively, a file with an MD5 hash after its name such as +public/assets/rails-af27b6a414e6da00003503148be9b409.png+ is also picked up by Sprockets. How these hashes are generated is covered in the "Production Assets":#production_assets section later on in this guide.
132
132
 
133
- Otherwise, Sprockets will look through the available paths until it finds a file that matches the name and then will serve it, first looking in the application's assets directories and then falling back to the various engines of the application.
133
+ Otherwise, Sprockets looks through the available paths until it finds a file that matches the name and then serves it, first looking in the application's assets directories and then falling back to the various engines of the application.
134
134
 
135
- If you want to use a "css 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.
135
+ If you want to use a "css 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.
136
136
 
137
137
  <plain>
138
138
  #logo { background: url(<%= asset_data_uri 'logo.png' %>)
139
139
  </plain>
140
140
 
141
- This will insert a correctly formatted data URI into the CSS source.
141
+ This inserts a correctly-formatted data URI into the CSS source.
142
142
 
143
143
  h5. CSS and ERB
144
144
 
145
- If you add an +erb+ extension to a CSS asset, making it something such as +application.css.erb+ then you can use the +asset_path+ helper in your CSS rules:
145
+ If you add an +erb+ extension to a CSS asset, making it something such as +application.css.erb+, then you can use the +asset_path+ helper in your CSS rules:
146
146
 
147
147
  <plain>
148
148
  .class{background-image:<%= asset_path 'image.png' %>}
149
149
  </plain>
150
150
 
151
- This will write 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 will be referenced.
151
+ 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.
152
152
 
153
153
  Note that the closing tag cannot be of the style +-%>+.
154
154
 
@@ -166,7 +166,7 @@ The more generic form can also be used but the asset path and class must both be
166
166
 
167
167
  h4. Manifest Files and Directives
168
168
 
169
- 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 will load the files specified, process them if necessary, concatenate them into one single file and then compress them (if +Rails.application.config.assets.compress+ is set to +true+). By serving one file rather than many, a page's load time is greatly reduced as there is not as many requests to make for each file.
169
+ 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 set to +true+). By serving one file rather than many, the load time of pages are greatly reduced as there are fewer requests to make.
170
170
 
171
171
  For example, in the default Rails application there's a +app/assets/javascripts/application.js+ file which contains the following lines:
172
172
 
@@ -176,9 +176,11 @@ For example, in the default Rails application there's a +app/assets/javascripts/
176
176
  //= require_tree .
177
177
  </plain>
178
178
 
179
- In JavaScript files, directives begin with +//=+. In this case, the following file is using the +require+ directive and the +require_tree+ directive. The +require+ directive tells Sprockets that we would like to require a file called +jquery.js+ that is available somewhere in the search path for Sprockets. By default, this is located inside the +vendor/assets/javascripts+ directory contained within the +jquery-rails+ gem. An identical event takes place for the +jquery_ujs+ require
179
+ 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.
180
180
 
181
- The +require_tree .+ directive tells Sprockets to include _all_ JavaScript files in this directory into the output. Only a path relative to the file can be specified.
181
+ NOTE. In Rails 3.1, the +jquery.js+ and +jquery_ujs.js+ files are located inside the +vendor/assets/javascripts+ directory contained within the +jquery-rails+ gem.
182
+
183
+ The +require_tree .+ directive tells Sprockets to include _all_ JavaScript files in this directory into the output. Only a path relative to the file can be specified. There is also a +require_directory+ directive which includes all JavaScript files only in the directory specified (no nesting).
182
184
 
183
185
  There's also a default +app/assets/stylesheets/application.css+ file which contains these lines:
184
186
 
@@ -189,13 +191,13 @@ There's also a default +app/assets/stylesheets/application.css+ file which conta
189
191
  */
190
192
  </plain>
191
193
 
192
- The directives that work in the JavaScript files will 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.
194
+ 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.
193
195
 
194
- In this example +require_self+ is used. This will put the CSS contained within the file (if any) at the top of any other CSS in this file unless +require_self+ is specified after another +require+ directive.
196
+ In this example +require_self+ is used. This puts the CSS contained within the file (if any) at the top of any other CSS in this file unless +require_self+ is specified after another +require+ directive.
195
197
 
196
198
  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.
197
199
 
198
- For some assets (like CSS) the compiled order is important. You can specify individual files and they will be compiled in the order specified:
200
+ For some assets (like CSS) the compiled order is important. You can specify individual files and they are compiled in the order specified:
199
201
 
200
202
  <plain>
201
203
  /* ...
@@ -208,36 +210,36 @@ For some assets (like CSS) the compiled order is important. You can specify indi
208
210
 
209
211
  h4. Preprocessing
210
212
 
211
- The file extensions used on an asset will determine what preprocessing will be applied. When a controller or a scaffold is generated with the default Rails gemset, a CoffeeScript file and a SCSS file will be 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 a +app/assets/stylesheets/projects.css.scss+ file.
213
+ 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 a +app/assets/stylesheets/projects.css.scss+ file.
212
214
 
213
- When these files are requested, they will be processed by the processors provided by the +coffee-script+ and +sass-rails+ gems and then sent back to the browser as JavaScript and CSS respectively.
215
+ When these files are requested, they are processed by the processors provided by the +coffee-script+ and +sass-rails+ gems and then sent back to the browser as JavaScript and CSS respectively.
214
216
 
215
- Additional layers of pre-processing can be requested by adding other extensions, where each extension will be 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+ would first be processed as ERB, then SCSS and finally served as CSS. The same applies to a JavaScript file - +app/assets/javascripts/projects.js.coffee.erb+ would be process as ERB, CoffeeScript and served as JavaScript.
217
+ Additional layers of pre-processing 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, CoffeeScript and served as JavaScript.
216
218
 
217
- Keep in mind that the order of these pre-processors is important. For example, if we called our 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 we would run into problems.
219
+ Keep in mind that the order of these pre-processors is important. For example, if you called your JavaScript file +app/assets/javascripts/projects.js.erb.coffee+ then it is processed with the CoffeeScript interpreter first, which wouldn't understand ERB and therefore you would run into problems.
218
220
 
219
221
  h3. In Development
220
222
 
221
- In the development environment assets are compiled and cached on the first request after the server is started. Sprockets sets a +must-validate+ cache-control http header to reduce request overhead on subsequent requests - on these the browser gets a 304 (not-modified) response.
223
+ In the development environment assets are compiled and cached on the first request after the server is started. Sprockets sets a +must-validate+ Cache-Control HTTP header to reduce request overhead on subsequent requests - on these the browser gets a 304 (not-modified) response.
222
224
 
223
- If any of the files in the manifest have changed between requests, the server will respond with a new compiled file.
225
+ If any of the files in the manifest have changed between requests, the server responds with a new compiled file.
224
226
 
225
227
  h4. Debugging Assets
226
228
 
227
- You can put +?debug_assets=true+ or +?debug_assets=1+ at the end of a URL and Sprockets will expand the lines which load the assets. For example, if we had an +app/assets/javascripts/application.js+ file containing these lines:
229
+ You can put +?debug_assets=true+ or +?debug_assets=1+ at the end of a URL and Sprockets expands the lines which load the assets. For example, if you had an +app/assets/javascripts/application.js+ file containing these lines:
228
230
 
229
231
  <plain>
230
232
  //= require "projects"
231
233
  //= require "tickets"
232
234
  </plain>
233
235
 
234
- By default, this would only render this line when used with +<%= javascript_include_tag "application" %>+ in a view or layout:
236
+ By default, this only renders this line when used with +<%= javascript_include_tag "application" %>+ in a view or layout:
235
237
 
236
238
  <html>
237
239
  <script src='/assets/application.js'></script>
238
240
  </html>
239
241
 
240
- When the +debug_assets+ parameter is set, this line will be expanded out into three separate lines, separating out the combined file into their parts.
242
+ When the +debug_assets+ parameter is set, this line is expanded out into three separate lines, separating out the combined file into their parts.
241
243
 
242
244
  <html>
243
245
  <script src='/assets/application.js'></script>
@@ -251,16 +253,16 @@ h3. In Production
251
253
 
252
254
  In the production environment, assets are served slightly differently.
253
255
 
254
- On the first request the assets are compiled and cached as described above, however the manifest names are altered to include an MD5 hash. Files names typically will look like these:
256
+ On the first request the assets are compiled and cached as described above, however the manifest names are altered to include an MD5 hash. Files names typically look like these:
255
257
 
256
258
  <plain>
257
259
  /assets/application-908e25f4bf641868d8683022a5b62f54.js
258
260
  /assets/application-4dd5b109ee3439da54f5bdfd78a80473.css
259
261
  </plain>
260
262
 
261
- The MD5 is generated from the contents of the compiled files, and is included in the http +Content-MD5+ header.
263
+ The MD5 is generated from the contents of the compiled files, and is included in the HTTP +Content-MD5+ header.
262
264
 
263
- 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.
265
+ 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.
264
266
 
265
267
  This behavior is controlled by the setting of +config.action_controller.perform_caching+ setting in Rails (which is +true+ for production, +false+ for everything else). This value is propagated to Sprockets during initialization for use when action_controller is not available.
266
268
 
@@ -268,7 +270,7 @@ h4. Precompiling Assets
268
270
 
269
271
  Even though assets are served by Rack::Cache with far-future headers, in high traffic sites this may not be fast enough.
270
272
 
271
- Rails comes bundled with a rake task to compile the manifests to files on disc. These are located in the +public/assets+ directory where they will be served by your web server instead of the Rails application.
273
+ Rails comes bundled with a rake task to compile the manifests to files on disc. These are located in the +public/assets+ directory where they are served by your web server instead of the Rails application.
272
274
 
273
275
  The rake task is:
274
276
 
@@ -276,19 +278,17 @@ The rake task is:
276
278
  rake assets:precompile
277
279
  </plain>
278
280
 
279
- You can run this as part of a Capistrano deployment:
281
+ Capistrano (v2.8.0+) has a recipe to handle this in deployment. Add the following line to +Capfile+:
280
282
 
281
283
  <erb>
282
- before 'deploy:symlink' do
283
- run "cd #{release_path}; RAILS_ENV=#{rails_env} rake assets:precompile"
284
- end
284
+ load 'deploy/assets'
285
285
  </erb>
286
286
 
287
- If you are not precompiling your assets, and you are using the default cache file store (which is the file system), you will need to symlink +rails_root/tmp/cache/assets+ from the shared folder that is part of the Capistrano deployment structure in order to persist the cached file between deployments.
287
+ This links the folder specified in +config.assets.prefix+ to +shared/assets+. If you already use this folder you'll need to write your own deployment task.
288
288
 
289
- TODO: Extend above task to allow for this and add task to set it up (See commits 8f0e0b6 and 704ee0df). Note: Capistrano folks are working on a recipe - update this when it available (see https://github.com/capistrano/capistrano/pull/35).
289
+ 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.
290
290
 
291
- The default matcher for compiling files will include +application.js+, +application.css+ and all files that do not end in +js+ or +css+:
291
+ The default matcher for compiling files includes +application.js+, +application.css+ and all files that do not end in +js+ or +css+:
292
292
 
293
293
  <ruby>
294
294
  [ /\w+\.(?!js|css).+/, /application.(css|js)$/ ]
@@ -297,7 +297,7 @@ The default matcher for compiling files will include +application.js+, +applicat
297
297
  If you have other manifests or individual stylesheets and JavaScript files to include, you can append them to the +precompile+ array:
298
298
 
299
299
  <erb>
300
- config.assets.precompile << ['admin.js', 'admin.css', 'swfObject.js']
300
+ config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
301
301
  </erb>
302
302
 
303
303
  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.
@@ -320,7 +320,7 @@ For Apache:
320
320
 
321
321
  TODO: NGINX instructions
322
322
 
323
- When files are precompiled Sprockets also creates "Gzip":http://en.wikipedia.org/wiki/Gzip (.gz) version of your assets. This avoids the server having to do this for any requests; it can simply read the compressed files from disc. You must configure your server to use gzip compression and serve the compressed assets that will be stored in the public/assets folder. The following configuration options can be used:
323
+ When files are precompiled, Sprockets also creates a "Gzip":http://en.wikipedia.org/wiki/Gzip (.gz) version of your assets. This avoids the server having to do this for any requests; it can simply read the compressed files from disc. You must configure your server to use gzip compression and serve the compressed assets that will be stored in the public/assets folder. The following configuration options can be used:
324
324
 
325
325
  TODO: Apache instructions
326
326
 
@@ -332,7 +332,7 @@ h4. CSS Compression
332
332
 
333
333
  There is currently one option for compressing CSS - YUI. This Gem extends the CSS syntax and offers minification.
334
334
 
335
- The following line will enable YUI compression, and requires the +yui-compressor+ gem.
335
+ The following line enables YUI compression, and requires the +yui-compressor+ gem.
336
336
 
337
337
  <erb>
338
338
  config.assets.css_compressor = :yui
@@ -344,19 +344,19 @@ h4. JavaScript
344
344
 
345
345
  Possible options for JavaScript compression are +:closure+, +:uglifier+ and +:yui+. These require the use of the +closure-compiler+, +uglifier+ or +yui-compressor+ gems respectively.
346
346
 
347
- 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 compress your code by removing white spaces and other magical things like changing your +if+ and +else+ statements to ternary operators where possible.
347
+ 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.
348
348
 
349
- The following line will invoke uglifier for JavaScript compression.
349
+ The following line invokes +uglifier+ for JavaScript compression.
350
350
 
351
351
  <erb>
352
- config.assets.js_compressor = :uglifier
352
+ config.assets.js_compressor = :uglifier
353
353
  </erb>
354
354
 
355
355
  The +config.assets.compress+ must be set to +true+ to enable JavaScript compression
356
356
 
357
357
  h4. Using Your Own Compressor
358
358
 
359
- The compressor config settings for CSS and JavaScript will 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.
359
+ 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.
360
360
 
361
361
  <erb>
362
362
  class Transformer
@@ -366,7 +366,7 @@ class Transformer
366
366
  end
367
367
  </erb>
368
368
 
369
- To enable this pass a +new+ Object to the config option in +application.rb+:
369
+ To enable this, pass a +new+ Object to the config option in +application.rb+:
370
370
 
371
371
  <erb>
372
372
  config.assets.css_compressor = Transformer.new
@@ -387,16 +387,15 @@ This is a handy option if you have any existing project (pre Rails 3.1) that alr
387
387
 
388
388
  h4. X-Sendfile Headers
389
389
 
390
- The X-Sendfile header is a directive to the server to ignore the response from the application, and instead serve the file specified in the headers. In production Rails (via Sprockets) does not send the asset - just the location and a zero-length response - relying on the web server to do the file serving, which is usually faster. Both Apache and nginx support this option.
390
+ The X-Sendfile header is a directive to the server to ignore the response from the application, and instead serve the file specified in the headers. 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.
391
391
 
392
- The configuration is available in <tt>config/environments/production.rb</tt>.
392
+ Apache and nginx support this option which is enabled in <tt>config/environments/production.rb</tt>.
393
393
 
394
394
  <erb>
395
- config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx
395
+ # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
396
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
396
397
  </erb>
397
398
 
398
- You should check that your server or hosting service actually supports this, otherwise comment it out.
399
-
400
399
  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 not +application.rb+) and any other environment you define with production behavior.
401
400
 
402
401
  h3. How Caching Works