aboutsummaryrefslogtreecommitdiffstats
path: root/railties
diff options
context:
space:
mode:
authorEmilio Tagua <miloops@gmail.com>2011-02-15 12:01:04 -0300
committerEmilio Tagua <miloops@gmail.com>2011-02-15 12:01:04 -0300
commit8ee0b4414890f919594c1a388d987b5b7364a505 (patch)
tree6c6c6aa19da0eb8066d2f0b9b02b08f2cc696c29 /railties
parent348c0ec7c656b3691aa4e687565d28259ca0f693 (diff)
parentc9f1ab5365319e087e1b010a3f90626a2b8f080b (diff)
downloadrails-8ee0b4414890f919594c1a388d987b5b7364a505.tar.gz
rails-8ee0b4414890f919594c1a388d987b5b7364a505.tar.bz2
rails-8ee0b4414890f919594c1a388d987b5b7364a505.zip
Merge remote branch 'rails/master' into identity_map
Conflicts: activerecord/examples/performance.rb activerecord/lib/active_record/association_preload.rb activerecord/lib/active_record/associations.rb activerecord/lib/active_record/associations/association_proxy.rb activerecord/lib/active_record/autosave_association.rb activerecord/lib/active_record/base.rb activerecord/lib/active_record/nested_attributes.rb activerecord/test/cases/relations_test.rb
Diffstat (limited to 'railties')
-rwxr-xr-xrailties/Rakefile6
-rw-r--r--railties/guides/rails_guides.rb4
-rw-r--r--railties/guides/rails_guides/generator.rb11
-rw-r--r--railties/guides/source/2_2_release_notes.textile6
-rw-r--r--railties/guides/source/2_3_release_notes.textile2
-rw-r--r--railties/guides/source/3_0_release_notes.textile18
-rw-r--r--railties/guides/source/action_controller_overview.textile9
-rw-r--r--railties/guides/source/action_mailer_basics.textile2
-rw-r--r--railties/guides/source/action_view_overview.textile32
-rw-r--r--railties/guides/source/active_record_basics.textile2
-rw-r--r--railties/guides/source/active_record_querying.textile149
-rw-r--r--railties/guides/source/active_support_core_extensions.textile26
-rw-r--r--railties/guides/source/ajax_on_rails.textile22
-rw-r--r--railties/guides/source/api_documentation_guidelines.textile8
-rw-r--r--railties/guides/source/association_basics.textile6
-rw-r--r--railties/guides/source/configuring.textile37
-rw-r--r--railties/guides/source/contribute.textile4
-rw-r--r--railties/guides/source/contributing_to_rails.textile311
-rw-r--r--railties/guides/source/contributing_to_ruby_on_rails.textile370
-rw-r--r--railties/guides/source/credits.html.erb4
-rw-r--r--railties/guides/source/debugging_rails_applications.textile6
-rw-r--r--railties/guides/source/form_helpers.textile38
-rw-r--r--railties/guides/source/generators.textile67
-rw-r--r--railties/guides/source/getting_started.textile14
-rw-r--r--railties/guides/source/i18n.textile28
-rw-r--r--railties/guides/source/index.html.erb6
-rw-r--r--railties/guides/source/initialization.textile3540
-rw-r--r--railties/guides/source/layout.html.erb12
-rw-r--r--railties/guides/source/layouts_and_rendering.textile4
-rw-r--r--railties/guides/source/nested_model_forms.textile4
-rw-r--r--railties/guides/source/performance_testing.textile6
-rw-r--r--railties/guides/source/plugins.textile104
-rw-r--r--railties/guides/source/rails_application_templates.textile18
-rw-r--r--railties/guides/source/rails_on_rack.textile13
-rw-r--r--railties/guides/source/routing.textile33
-rw-r--r--railties/guides/source/ruby_on_rails_guides_guidelines.textile18
-rw-r--r--railties/guides/source/security.textile10
-rw-r--r--railties/guides/source/testing.textile14
-rw-r--r--railties/guides/w3c_validator.rb4
-rw-r--r--railties/lib/rails/application.rb5
-rw-r--r--railties/lib/rails/application/configuration.rb25
-rw-r--r--railties/lib/rails/cli.rb2
-rw-r--r--railties/lib/rails/commands.rb2
-rw-r--r--railties/lib/rails/commands/application.rb12
-rw-r--r--railties/lib/rails/commands/dbconsole.rb10
-rw-r--r--railties/lib/rails/commands/plugin.rb7
-rw-r--r--railties/lib/rails/engine.rb188
-rw-r--r--railties/lib/rails/generators.rb2
-rw-r--r--railties/lib/rails/generators/app_base.rb14
-rw-r--r--railties/lib/rails/generators/base.rb2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile9
-rw-r--r--railties/lib/rails/generators/rails/app/templates/README4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/gitignore2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js2701
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js280
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js88
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb4
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb5
-rw-r--r--railties/lib/rails/generators/test_case.rb2
-rw-r--r--railties/lib/rails/paths.rb8
-rw-r--r--railties/lib/rails/rack/logger.rb2
-rw-r--r--railties/test/application/initializers/i18n_test.rb30
-rw-r--r--railties/test/application/rake_test.rb36
-rw-r--r--railties/test/generators/app_generator_test.rb19
-rw-r--r--railties/test/generators/migration_generator_test.rb7
-rw-r--r--railties/test/generators/model_generator_test.rb51
-rw-r--r--railties/test/generators/plugin_new_generator_test.rb7
-rw-r--r--railties/test/generators_test.rb18
-rw-r--r--railties/test/railties/engine_test.rb28
-rw-r--r--railties/test/railties/shared_tests.rb10
71 files changed, 3558 insertions, 4992 deletions
diff --git a/railties/Rakefile b/railties/Rakefile
index 5137bee761..26fa0bf6a5 100755
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -18,7 +18,7 @@ namespace :test do
Dir["test/#{dir}/*_test.rb"].each do |file|
next true if file.include?("fixtures")
ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
- system(ruby, '-Itest', "-I#{File.dirname(__FILE__)}/../activesupport/lib", file)
+ sh(ruby, '-Itest', "-I#{File.dirname(__FILE__)}/../activesupport/lib", file)
end
end
end
@@ -46,8 +46,8 @@ task :generate_guides do
end
task :update_ujs do
- system "curl http://github.com/rails/prototype-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js"
- system "curl http://github.com/rails/jquery-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js"
+ system "curl https://github.com/rails/prototype-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js"
+ system "curl https://github.com/rails/jquery-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js"
end
# Validate guides -------------------------------------------------------------------------
diff --git a/railties/guides/rails_guides.rb b/railties/guides/rails_guides.rb
index dfbb06cc76..feb5fe3937 100644
--- a/railties/guides/rails_guides.rb
+++ b/railties/guides/rails_guides.rb
@@ -24,14 +24,14 @@ rescue LoadError
end
begin
- gem 'RedCloth', '>= 4.1.1'
require 'redcloth'
rescue Gem::LoadError
+ # This can happen if doc:guides is executed in an application.
$stderr.puts('Generating guides requires RedCloth 4.1.1+.')
$stderr.puts(<<ERROR) if bundler?
Please add
- gem 'RedCloth', '>= 4.1.1'
+ gem 'RedCloth', '~> 4.2'
to the Gemfile, run
diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb
index 0a2170a09e..154355cac1 100644
--- a/railties/guides/rails_guides/generator.rb
+++ b/railties/guides/rails_guides/generator.rb
@@ -32,12 +32,16 @@
#
# Separate many using commas:
#
-# # generates only
+# # generates only association_basics.html and migrations.html
# ONLY=assoc,migrations ruby rails_guides.rb
#
# Note that if you are working on a guide generation will by default process
# only that one, so ONLY is rarely used nowadays.
#
+# LANGUAGE
+# Use LANGUAGE when you want to generate translated guides in <tt>source/<LANGUAGE></tt>
+# folder (such as <tt>source/es</tt>). Ignore it when generating English guides.
+#
# EDGE
# Set to "1" to indicate generated guides should be marked as edge. This
# inserts a badge and changes the preamble of the home page.
@@ -63,6 +67,7 @@ module RailsGuides
GUIDES_RE = /\.(?:textile|html\.erb)$/
def initialize(output=nil)
+ @lang = ENV['LANGUAGE']
initialize_dirs(output)
create_output_dir_if_needed
set_flags_from_environment
@@ -76,8 +81,8 @@ module RailsGuides
private
def initialize_dirs(output)
@guides_dir = File.join(File.dirname(__FILE__), '..')
- @source_dir = File.join(@guides_dir, "source")
- @output_dir = output || File.join(@guides_dir, "output")
+ @source_dir = File.join(@guides_dir, "source", @lang.to_s)
+ @output_dir = output || File.join(@guides_dir, "output", @lang.to_s)
end
def create_output_dir_if_needed
diff --git a/railties/guides/source/2_2_release_notes.textile b/railties/guides/source/2_2_release_notes.textile
index 5628d7e52f..8e2d528eee 100644
--- a/railties/guides/source/2_2_release_notes.textile
+++ b/railties/guides/source/2_2_release_notes.textile
@@ -260,15 +260,15 @@ h4. Other Action Controller Changes
* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds
* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
* +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI).
-* +render+ now supports a +:js+ option to render plain vanilla javascript with the right mime type.
+* +render+ now supports a +:js+ option to render plain vanilla JavaScript with the right mime type.
* Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+.
h3. Action View
* +javascript_include_tag+ and +stylesheet_link_tag+ support a new +:recursive+ option to be used along with +:all+, so that you can load an entire tree of files with a single line of code.
-* The included Prototype javascript library has been upgraded to version 1.6.0.3.
-* +RJS#page.reload+ to reload the browser's current location via javascript
+* The included Prototype JavaScript library has been upgraded to version 1.6.0.3.
+* +RJS#page.reload+ to reload the browser's current location via JavaScript
* The +atom_feed+ helper now takes an +:instruct+ option to let you insert XML processing instructions.
h3. Action Mailer
diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile
index 72fe723687..67743a4797 100644
--- a/railties/guides/source/2_3_release_notes.textile
+++ b/railties/guides/source/2_3_release_notes.textile
@@ -278,7 +278,7 @@ Mime::JS =~ "text/javascript" => true
Mime::JS =~ "application/javascript" => true
</ruby>
-The other change is that the framework now uses the +Mime::JS+ when checking for javascript in various spots, making it handle those alternatives cleanly.
+The other change is that the framework now uses the +Mime::JS+ when checking for JavaScript in various spots, making it handle those alternatives cleanly.
* Lead Contributor: "Seth Fitzsimmons":http://www.workingwithrails.com/person/5510-seth-fitzsimmons
diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile
index adb1c755df..db5a9ce644 100644
--- a/railties/guides/source/3_0_release_notes.textile
+++ b/railties/guides/source/3_0_release_notes.textile
@@ -357,15 +357,15 @@ Validations have been moved from Active Record into Active Model, providing an i
* There is now a <tt>validates :attribute, options_hash</tt> shortcut method that allows you to pass options for all the validates class methods, you can pass more than one option to a validate method.
* The +validates+ method has the following options:
- * <tt>:acceptance => Boolean</tt>.
- * <tt>:confirmation => Boolean</tt>.
- * <tt>:exclusion => { :in => Enumerable }</tt>.
- * <tt>:inclusion => { :in => Enumerable }</tt>.
- * <tt>:format => { :with => Regexp, :on => :create }</tt>.
- * <tt>:length => { :maximum => Fixnum }</tt>.
- * <tt>:numericality => Boolean</tt>.
- * <tt>:presence => Boolean</tt>.
- * <tt>:uniqueness => Boolean</tt>.
+** <tt>:acceptance => Boolean</tt>.
+** <tt>:confirmation => Boolean</tt>.
+** <tt>:exclusion => { :in => Enumerable }</tt>.
+** <tt>:inclusion => { :in => Enumerable }</tt>.
+** <tt>:format => { :with => Regexp, :on => :create }</tt>.
+** <tt>:length => { :maximum => Fixnum }</tt>.
+** <tt>:numericality => Boolean</tt>.
+** <tt>:presence => Boolean</tt>.
+** <tt>:uniqueness => Boolean</tt>.
NOTE: All the Rails version 2.3 style validation methods are still supported in Rails 3.0, the new validates method is designed as an additional aid in your model validations, not a replacement for the existing API.
diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 0d6919a205..be015c4f9b 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -368,6 +368,7 @@ class UsersController < ApplicationController
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users}
+ format.json { render :json => @users}
end
end
end
@@ -736,16 +737,12 @@ GET /clients/1.pdf
h3. Parameter Filtering
-Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [FILTERED] in the log.
<ruby>
-class ApplicationController < ActionController::Base
- filter_parameter_logging :password
-end
+config.filter_parameters << :password
</ruby>
-The method works recursively through all levels of the +params+ hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.
-
h3. Rescue
Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the +ActiveRecord::RecordNotFound+ exception.
diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile
index b77a0be37b..6ee17ee5b8 100644
--- a/railties/guides/source/action_mailer_basics.textile
+++ b/railties/guides/source/action_mailer_basics.textile
@@ -248,7 +248,7 @@ It is possible to send email to one or more recipients in one email (for e.g. in
class AdminMailer < ActionMailer::Base
default :to => Admin.all.map(&:email).join(", "),
:from => "notification@example.com"
-
+
def new_registration(user)
@user = user
mail(:subject => "New User Signup: #{@user.email}")
diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile
index 051baa660c..e1fc0e7732 100644
--- a/railties/guides/source/action_view_overview.textile
+++ b/railties/guides/source/action_view_overview.textile
@@ -231,7 +231,7 @@ input("post", "title") # =>
h4. AssetTagHelper
-This module provides methods for generating HTML that links views to assets such as images, javascripts, stylesheets, and feeds.
+This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.
By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting +ActionController::Base.asset_host+ in the application configuration, typically in +config/environments/production.rb+. For example, let's say your asset host is +assets.example.com+:
@@ -242,7 +242,7 @@ image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png
h5. register_javascript_expansion
-Register one or more javascript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register javascript files that the plugin installed in public/javascripts.
+Register one or more JavaScript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register JavaScript files that the plugin installed in +public/javascripts+.
<ruby>
ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
@@ -278,7 +278,7 @@ auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS
h5. image_path
-Computes the path to an image asset in the public images directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path.
+Computes the path to an image asset in the +public/images+ directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path.
<ruby>
image_path("edit.png") # => /images/edit.png
@@ -286,7 +286,7 @@ image_path("edit.png") # => /images/edit.png
h5. image_tag
-Returns an html image tag for the source. The source can be a full path or a file that exists in your public images directory.
+Returns an html image tag for the source. The source can be a full path or a file that exists in your +public/images+ directory.
<ruby>
image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" />
@@ -294,26 +294,26 @@ image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" />
h5. javascript_include_tag
-Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of javascript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root.
+Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of JavaScript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root.
<ruby>
javascript_include_tag "common" # =>
<script type="text/javascript" src="/javascripts/common.js"></script>
</ruby>
-To include the Prototype and Scriptaculous javascript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well.
+To include the Prototype and Scriptaculous JavaScript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well.
<ruby>
javascript_include_tag :defaults
</ruby>
-You can also include all javascripts in the javascripts directory using +:all+ as the source.
+You can also include all JavaScript files in the +public/javascripts+ directory using +:all+ as the source.
<ruby>
javascript_include_tag :all
</ruby>
-You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment).
+You can also cache multiple JavaScript files into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment).
<ruby>
javascript_include_tag :all, :cache => true # =>
@@ -322,7 +322,7 @@ javascript_include_tag :all, :cache => true # =>
h5. javascript_path
-Computes the path to a javascript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path.
+Computes the path to a JavaScript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path.
<ruby>
javascript_path "common" # => /javascripts/common.js
@@ -352,7 +352,7 @@ stylesheet_link_tag :all, :cache => true
h5. stylesheet_path
-Computes the path to a stylesheet asset in the public stylesheets directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
+Computes the path to a stylesheet asset in the +public/stylesheets+ directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
<ruby>
stylesheet_path "application" # => /stylesheets/application.css
@@ -367,14 +367,14 @@ This helper makes building an ATOM feed easy. Here's a full usage example:
*config/routes.rb*
<ruby>
-map.resources :posts
+resources :posts
</ruby>
*app/controllers/posts_controller.rb*
<ruby>
def index
- @posts = Post.find(:all)
+ @posts = Post.all
respond_to do |format|
format.html
@@ -439,7 +439,7 @@ The +capture+ method allows you to extract part of a template into a variable. Y
<% @greeting = capture do %>
<p>Welcome! The date and time is <%= Time.now %></p>
<% end %>
-<ruby>
+</ruby>
The captured variable can then be used anywhere else.
@@ -809,7 +809,7 @@ end
Sample usage (selecting the associated Author for an instance of Post, +@post+):
<ruby>
-collection_select(:post, :author_id, Author.find(:all), :id, :name_with_initial, {:prompt => true})
+collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true})
</ruby>
If @post.author_id is already 1, this would return:
@@ -910,7 +910,7 @@ Create a select tag and a series of contained option tags for the provided objec
Example with @post.person_id => 1:
<ruby>
-select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true })
+select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
</ruby>
could become:
@@ -1076,7 +1076,7 @@ h4. JavaScriptHelper
Provides functionality for working with JavaScript in your views.
-Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +&lt;%= javascript_include_tag :defaults, :cache => true %&gt;+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the public/javascripts directory.
+Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +&lt;%= javascript_include_tag :defaults, :cache => true %&gt;+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the +public/javascripts+ directory.
h5. button_to_function
diff --git a/railties/guides/source/active_record_basics.textile b/railties/guides/source/active_record_basics.textile
index f0081b48c0..b7926f3a3b 100644
--- a/railties/guides/source/active_record_basics.textile
+++ b/railties/guides/source/active_record_basics.textile
@@ -180,7 +180,7 @@ Active Record provides a rich API for accessing data within a database. Below ar
<ruby>
# find all users named David who are Code Artists and sort by created_at in reverse chronological order
- users = User.all(:conditions => { :name => 'David', :occupation => 'Code Artist'}, :order => 'created_at DESC')
+ users = User.where(:name => 'David', :occupation => 'Code Artist').order('created_at DESC')
</ruby>
You can learn more about querying an Active Record model in the "Active Record Query Interface":"active_record_querying.html" guide.
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile
index b9ad7ccbd2..64a68f7592 100644
--- a/railties/guides/source/active_record_querying.textile
+++ b/railties/guides/source/active_record_querying.textile
@@ -19,8 +19,6 @@ Code examples throughout this guide will refer to one or more of the following m
TIP: All of the following models use +id+ as the primary key, unless specified otherwise.
-<br />
-
<ruby>
class Client < ActiveRecord::Base
has_one :address
@@ -150,7 +148,7 @@ SQL equivalent of the above is:
SELECT * FROM clients WHERE (clients.id IN (1,10))
</sql>
-<tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
+WARNING: <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
h4. Retrieving Multiple Objects in Batches
@@ -337,7 +335,7 @@ This code will generate SQL like this:
SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
</sql>
-h4. Ordering
+h3. Ordering
To retrieve records from the database in a specific order, you can use the +order+ method.
@@ -361,7 +359,7 @@ Or ordering by multiple fields:
Client.order("orders_count ASC, created_at DESC")
</ruby>
-h4. Selecting Specific Fields
+h3. Selecting Specific Fields
By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+.
@@ -397,7 +395,7 @@ You can also call SQL functions within the select option. For example, if you wo
Client.select("DISTINCT(name)")
</ruby>
-h4. Limit and Offset
+h3. Limit and Offset
To apply +LIMIT+ to the SQL fired by the +Model.find+, you can specify the +LIMIT+ using +limit+ and +offset+ methods on the relation.
@@ -425,7 +423,7 @@ will return instead a maximum of 5 clients beginning with the 31st. The SQL look
SELECT * FROM clients LIMIT 5, 30
</sql>
-h4. Group
+h3. Group
To apply a +GROUP BY+ clause to the SQL fired by the finder, you can specify the +group+ method on the find.
@@ -440,10 +438,10 @@ And this will give you a single +Order+ object for each date where there are ord
The SQL that would be executed would be something like this:
<sql>
-SELECT * FROM orders GROUP BY date(created_at)
+SELECT * FROM orders GROUP BY date(created_at) ORDER BY created_at
</sql>
-h4. Having
+h3. Having
SQL uses the +HAVING+ clause to specify conditions on the +GROUP BY+ fields. You can add the +HAVING+ clause to the SQL fired by the +Model.find+ by adding the +:having+ option to the find.
@@ -461,7 +459,37 @@ SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15'
This will return single order objects for each day, but only for the last month.
-h4. Readonly Objects
+h3. Overriding Conditions
+
+You can specify certain conditions to be excepted by using the +except+ method.
+
+For example:
+
+<ruby>
+Post.where('id > 10').limit(20).order('id asc').except(:order)
+</ruby>
+
+The SQL that would be executed:
+
+<sql>
+SELECT * FROM posts WHERE id > 10 LIMIT 20
+</sql>
+
+You can also override conditions using the +only+ method.
+
+For example:
+
+<ruby>
+Post.where('id > 10').limit(20).order('id desc').only(:order, :where)
+</ruby>
+
+The SQL that would be executed:
+
+<sql>
+SELECT * FROM posts WHERE id > 10 ORDER BY id DESC
+</sql>
+
+h3. Readonly Objects
Active Record provides +readonly+ method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception.
@@ -471,9 +499,9 @@ client.visits += 1
client.save
</ruby>
-As +client+ is explicitly set to be a readonly object, the above code will raise an +ActiveRecord::ReadOnlyRecord+ exception when calling +client.save+ with an updated value of _visists_.
+As +client+ is explicitly set to be a readonly object, the above code will raise an +ActiveRecord::ReadOnlyRecord+ exception when calling +client.save+ with an updated value of _visits_.
-h4. Locking Records for Update
+h3. Locking Records for Update
Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.
@@ -482,7 +510,7 @@ Active Record provides two locking mechanisms:
* Optimistic Locking
* Pessimistic Locking
-h5. Optimistic Locking
+h4. Optimistic Locking
Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An +ActiveRecord::StaleObjectError+ exception is thrown if that has occurred and the update is ignored.
@@ -517,7 +545,7 @@ class Client < ActiveRecord::Base
end
</ruby>
-h5. Pessimistic Locking
+h4. Pessimistic Locking
Pessimistic locking uses a locking mechanism provided by the underlying database. Using +lock+ when building a relation obtains an exclusive lock on the selected rows. Relations using +lock+ are usually wrapped inside a transaction for preventing deadlock conditions.
@@ -569,9 +597,7 @@ SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id =
h4. Using Array/Hash of Named Associations
-WARNING: This method only works with +INNER JOIN+,
-
-<br />
+WARNING: This method only works with +INNER JOIN+.
Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying +JOIN+ clause for those associations when using the +joins+ method.
@@ -666,7 +692,7 @@ Eager loading is the mechanism for loading the associated records of the objects
Consider the following code, which finds 10 clients and prints their postcodes:
<ruby>
-clients = Client.all(:limit => 10)
+clients = Client.limit(10)
clients.each do |client|
puts client.address.postcode
@@ -721,6 +747,92 @@ h4. Specifying Conditions on Eager Loaded Associations
Even though Active Record lets you specify conditions on the eager loaded associations just like +joins+, the recommended way is to use "joins":#joining-tables instead.
+h3. Scopes
+
+Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. All scope methods will return an +ActiveRecord::Relation+ object which will allow for further methods (such as other scopes) to be called on it.
+
+To define a simple scope, we use the +scope+ method inside the class, passing the ARel query that we'd like run when this scope is called:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :published, where(:published => true)
+end
+</ruby>
+
+Just like before, these methods are also chainable:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :published, where(:published => true).joins(:category)
+end
+</ruby>
+
+Scopes are also chainable within scopes:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :published, where(:published => true)
+ scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
+end
+</ruby>
+
+To call this +published+ scope we can call it on either the class:
+
+<ruby>
+Post.published => [published posts]
+</ruby>
+
+Or on an association consisting of +Post+ objects:
+
+<ruby>
+category = Category.first
+category.posts.published => [published posts belonging to this category]
+</ruby>
+
+h4. Working with times
+
+If you're working with dates or times within scopes, due to how they are evaluated, you will need to use a lambda so that the scope is evaluated every time.
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :last_week, lambda { where("created_at < ?", Time.zone.now ) }
+end
+</ruby>
+
+Without the +lambda+, this +Time.zone.now+ will only be called once.
+
+h4. Passing in arguments
+
+When a +lambda+ is used for a +scope+, it can take arguments:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :1_week_before, lambda { |time| where("created_at < ?", time)
+end
+</ruby>
+
+This may then be called using this:
+
+<ruby>
+Post.1_week_before(Time.zone.now)
+</ruby>
+
+However, this is just duplicating the functionality that would be provided to you by a class method.
+
+<ruby>
+class Post < ActiveRecord::Base
+ def self.1_week_before(time)
+ where("created_at < ?", time)
+ end
+end
+</ruby>
+
+Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects:
+
+<ruby>
+category.posts.1_week_before(time)
+</ruby>
+
h3. Dynamic Finders
For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +first_name+ on your +Client+ model for example, you get +find_by_first_name+ and +find_all_by_first_name+ for free from Active Record. If you have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+ methods.
@@ -882,6 +994,7 @@ For options, please see the parent section, "Calculations":#calculations.
h3. Changelog
+* December 23 2010: Add documentation for the +scope+ method. "Ryan Bigg":http://ryanbigg.com
* April 7, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* February 3, 2010: Update to Rails 3 by "James Miller":credits.html#bensie
* February 7, 2009: Second version by "Pratik":credits.html#lifo
diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile
index 2e295aec3d..cf9ebf44e6 100644
--- a/railties/guides/source/active_support_core_extensions.textile
+++ b/railties/guides/source/active_support_core_extensions.textile
@@ -498,7 +498,7 @@ h4. Attributes
h5. +alias_attribute+
-Model attributes have a reader, a writer, and a predicate. You can aliase a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
+Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
<ruby>
class User < ActiveRecord::Base
@@ -563,7 +563,7 @@ h5. Internal Attributes
When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That's remarkably important for libraries.
-Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby builtin +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
+Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby built-in +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
The macro +attr_internal+ is a synonym for +attr_internal_accessor+:
@@ -991,7 +991,7 @@ a2.x # => 2, overridden in a2
The generation of the writer instance method can be prevented by setting the option +:instance_writer+ to false, as in
<ruby>
-module AcitveRecord
+module ActiveRecord
class Base
class_attribute :table_name_prefix, :instance_writer => false
self.table_name_prefix = ""
@@ -1001,7 +1001,7 @@ end
A model may find that option useful as a way to prevent mass-assignment from setting the attribute.
-For convenience +class_attribute+ defines also an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+.
+For convenience +class_attribute+ also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+.
NOTE: Defined in +active_support/core_ext/class/attribute.rb+
@@ -1264,7 +1264,7 @@ Active Support adds that functionality to <tt>%</tt> in previous versions of Rub
NOTE: Defined in +active_support/core_ext/string/interpolation.rb+.
-h4. +starts_with?+ and +ends_width?+
+h4. +starts_with?+ and +ends_with?+
Active Support defines 3rd person aliases of +String#start_with?+ and +String#end_with?+:
@@ -1568,7 +1568,7 @@ The method +tableize+ is +underscore+ followed by +pluralize+.
"InvoiceLine".tableize # => "invoice_lines"
</ruby>
-As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes de class name and checks a few options that may affect the returned string.
+As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.
NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
@@ -1868,7 +1868,7 @@ The sum of an empty collection is zero by default, but this is customizable:
[].sum(1) # => 1
</ruby>
-If a block is given +sum+ becomes an iterator that yields the elements of the collection and sums the returned values:
+If a block is given, +sum+ becomes an iterator that yields the elements of the collection and sums the returned values:
<ruby>
(1..5).sum {|n| n * 2 } # => 30
@@ -1896,7 +1896,7 @@ h4. +each_with_object+
The +inject+ method offers iteration with an accumulator:
<ruby>
-[2, 3, 4].inject(1) {|acc, i| product*i } # => 24
+[2, 3, 4].inject(1) {|product, i| product*i } # => 24
</ruby>
The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome:
@@ -1942,7 +1942,7 @@ The method +many?+ is shorthand for +collection.size > 1+:
<% end %>
</erb>
-If an optional block is given +many?+ only takes into account those elements that return true:
+If an optional block is given, +many?+ only takes into account those elements that return true:
<ruby>
@see_more = videos.many? {|video| video.category == params[:category]}
@@ -1952,7 +1952,7 @@ NOTE: Defined in +active_support/core_ext/enumerable.rb+.
h4. +exclude?+
-The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the builtin +include?+:
+The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the built-in +include?+:
<ruby>
to_visit << node if visited.exclude?(node)
@@ -2007,7 +2007,7 @@ User.exists?(:email => params[:email])
That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.
-If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where kind of loses its role.
+If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.
In those cases, you may give an options hash a distinguished treatment with +extract_options!+. That method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise returns an empty hash.
@@ -3389,12 +3389,12 @@ Modifies the datetime format output by the formatter class associated with this
<ruby>
class Logger::FormatWithTime < Logger::Formatter
cattr_accessor(:datetime_format) { "%Y%m%d%H%m%S" }
-
+
def self.call(severity, timestamp, progname, msg)
"#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n"
end
end
-
+
logger = Logger.new("log/development.log")
logger.formatter = Logger::FormatWithTime
logger.info("<- is the current time")
diff --git a/railties/guides/source/ajax_on_rails.textile b/railties/guides/source/ajax_on_rails.textile
index 972e7ea840..3d7fcdc198 100644
--- a/railties/guides/source/ajax_on_rails.textile
+++ b/railties/guides/source/ajax_on_rails.textile
@@ -1,10 +1,10 @@
h2. AJAX on Rails
-This guide covers the built-in Ajax/Javascript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics:
+This guide covers the built-in Ajax/JavaScript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics:
* Quick introduction to AJAX and related technologies
-* Handling Javascript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us
-* Testing Javascript functionality
+* Handling JavaScript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us
+* Testing JavaScript functionality
endprologue.
@@ -12,7 +12,7 @@ h3. Hello AJAX - a Quick Intro
If you are a 'show me the code' type of person, you might want to skip this part and jump to the RJS section right away. However, I would really recommend to read it - you'll need the basics of DOM, http requests and other topics discussed here to really understand Ajax on Rails.
-h4. Asynchronous Javascript + XML
+h4. Asynchronous JavaScript + XML
Basic terminology, new style of creating web apps
@@ -31,7 +31,7 @@ How do 'standard' and AJAX requests differ, why does this matter for understandi
h3. Built-in Rails Helpers
-Rails' Javascript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose Javascript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other Javascript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views.
+Rails' JavaScript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose JavaScript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other JavaScript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views.
To get access to these helpers, all you have to do is to include the prototype framework in your pages - typically in your master layout, application.html.erb - like so:
<ruby>
@@ -136,7 +136,7 @@ link_to_remote "Add new item",
:before => "$('progress').show()",
:complete => "$('progress').hide()",
:success => "display_item_added(request)",
- :failure => "display_error(request)",
+ :failure => "display_error(request)"
</ruby>
** *:type* If you want to fire a synchronous request for some obscure reason (blocking the browser while the request is processed and doesn't return a status code), you can use the +:type+ option with the value of +:synchronous+.
* Finally, using the +html_options+ parameter you can add HTML attributes to the generated tag. It works like the same parameter of the +link_to+ helper. There are interesting side effects for the +href+ and +onclick+ parameters though:
@@ -153,7 +153,7 @@ There are three different ways of adding AJAX forms to your view using Rails Pro
* +form_remote_tag+ AJAXifies the form by serializing and sending it's data in the background
* +submit_to_remote+ and +button_to_remote+ is more rarely used than the previous two. Rather than creating an AJAX form, you add a button/input
-Let's se them in action one by one!
+Let's see them in action one by one!
h5. +remote_form_for+
@@ -183,7 +183,7 @@ h3. JavaScript the Rails way: RJS
In the last section we sent some AJAX requests to the server, and inserted the HTML response into the page (with the +:update+ option). However, sometimes a more complicated interaction with the page is needed, which you can either achieve with JavaScript... or with RJS! You are sending JavaScript instructions to the server in both cases, but while in the former case you have to write vanilla JavaScript, in the second you can code Rails, and sit back while Rails generates the JavaScript for you - so basically RJS is a Ruby DSL to write JavaScript in your Rails code.
-h4. Javascript without RJS
+h4. JavaScript without RJS
First we'll check out how to send JavaScript to the server manually. You are practically never going to need this, but it's interesting to understand what's going on under the hood.
@@ -329,9 +329,9 @@ h4. Drag and Drop
-h3. Testing Javascript
+h3. Testing JavaScript
-Javascript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with Javascript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it:
+JavaScript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with JavaScript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it:
* (Fire)Watir
* Selenium
@@ -339,4 +339,4 @@ Javascript testing reminds me the definition of the world 'classic' by Mark Twai
* Cucumber+Webrat
* Mention stuff like screw.unit/jsSpec
-Note to self: check out the RailsConf JS testing video \ No newline at end of file
+Note to self: check out the RailsConf JS testing video
diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile
index e3ccd6396c..68665dce98 100644
--- a/railties/guides/source/api_documentation_guidelines.textile
+++ b/railties/guides/source/api_documentation_guidelines.textile
@@ -6,7 +6,7 @@ endprologue.
h3. RDoc
-The Rails API documentation is generated with RDoc 2.5. Please consult the documentation for help with the "markup":http://rdoc.rubyforge.org/RDoc.html, and take into account also these "additional directives":http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html.
+The Rails API documentation is generated with RDoc 2.5. Please consult the documentation for help with the "markup":http://rdoc.rubyforge.org/RDoc/Markup.html, and take into account also these "additional directives":http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html.
h3. Wording
@@ -27,7 +27,7 @@ Communicate to the reader the current way of doing things, both explicitly and i
Documentation has to be concise but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil?
-The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. Historically there has been lack of consistency regarding this, but we checked with David when docrails started. All Rails documentation consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be fenomenal :).
+The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be fenomenal :).
Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERb. When in doubt, please have a look at some authoritative source like their official documentation.
@@ -46,10 +46,10 @@ Short docs do not need an explicit "Examples" label to introduce snippets, they
# Converts a collection of elements into a formatted string by calling
# <tt>to_s</tt> on all elements and joining them.
#
-# Blog.find(:all).to_formatted_s # => "First PostSecond PostThird Post"
+# Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
</ruby>
-On the other hand big chunks of structured documentation may have a separate "Examples" section:
+On the other hand, big chunks of structured documentation may have a separate "Examples" section:
<ruby>
# ==== Examples
diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile
index 62abc40c81..f22f41e8b1 100644
--- a/railties/guides/source/association_basics.textile
+++ b/railties/guides/source/association_basics.textile
@@ -65,7 +65,7 @@ To learn more about the different types of associations, read the next section o
h3. The Types of Associations
-In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:
+In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of associations:
* +belongs_to+
* +has_one+
@@ -1135,7 +1135,7 @@ h6(#has_many-collection-find). <tt><em>collection</em>.find(...)</tt>
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
<ruby>
-@open_orders = @customer.orders.find(:all, :conditions => "open = 1")
+@open_orders = @customer.orders.all(:conditions => "open = 1")
</ruby>
NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions.
@@ -1564,7 +1564,7 @@ h6(#has_and_belongs_to_many-collection-find). <tt><em>collection</em>.find(...)<
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
<ruby>
-@new_assemblies = @part.assemblies.find(:all,
+@new_assemblies = @part.assemblies.all(
:conditions => ["created_at > ?", 2.days.ago])
</ruby>
diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile
index d5faf3da2c..eee18f1131 100644
--- a/railties/guides/source/configuring.textile
+++ b/railties/guides/source/configuring.textile
@@ -154,7 +154,7 @@ Every Rails application comes with a standard set of middleware which it uses in
* +Rails::Rack::Logger+ Will notify the logs that the request has began. After request is complete, flushes all the logs.
* +ActionDispatch::ShowExceptions+ rescues any exception returned by the application and renders nice exception pages if the request is local or if +config.consider_all_requests_local+ is set to _true_. If +config.action_dispatch.show_exceptions+ is set to _false_, exceptions will be raised regardless.
* +ActionDispatch::RemoteIp+ checks for IP spoofing attacks. Configurable with the +config.action_dispatch.ip_spoofing_check+ and +config.action_dispatch.trusted_proxies+ settings.
-* +Rack::Sendfile+ The Sendfile middleware intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. Configurable with +config.action_dispatch_
+* +Rack::Sendfile+ The Sendfile middleware intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. Configurable with +config.action_dispatch.x_sendfile_header+
* +ActionDispatch::Callbacks+ Runs the prepare callbacks before serving the request.
* +ActiveRecord::ConnectionAdapters::ConnectionManagement+ cleans active connections after each request, unless the +rack.test+ key in the request environment is set to _true_.
* +ActiveRecord::QueryCache+ caches all +SELECT+ queries generated in a request. If an +INSERT+ or +UPDATE+ takes place then the cache is cleaned.
@@ -190,6 +190,12 @@ Middlewares can also be completely swapped out and replaced with others:
config.middleware.swap ActionDispatch::BestStandardsSupport, Magical::Unicorns
</ruby>
+They can also be removed from the stack completely:
+
+<ruby>
+ config.middleware.delete ActionDispatch::BestStandardsSupport
+</ruby>
+
h4. Configuring i18n
* +config.i18n.default_locale+ sets the default locale of an application used for i18n. Defaults to +:en+.
@@ -272,11 +278,11 @@ h4. Configuring Action Dispatch
* +config.action_dispatch.tld_length+ sets the TLD (top-level domain) length for the application. Defaults to +1+.
-* +ActionDispatch::Callbacks.before+ takes a block of code to run before the request.
+* +ActionDispatch::Callbacks.before+ takes a block of code to run before the request.
* +ActionDispatch::Callbacks.to_prepare+ takes a block to run after +ActionDispatch::Callbacks.before+, but before the request. Runs for every request in +development+ mode, but only once for +production+ or environments with +cache_classes+ set to +true+.
-* +ActionDispatch::Callbacks.after+ takes a block of code to run after the request.
+* +ActionDispatch::Callbacks.after+ takes a block of code to run after the request.
h4. Configuring Action View
@@ -370,8 +376,15 @@ There are a few configuration options available in Active Support:
* +ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations.
+* +ActiveSupport::Deprecation.behavior+ alternative setter to +config.active_support.deprecation+ which configures the behavior of deprecation warnings for Rails.
+
+* +ActiveSupport::Deprecation.silence+ takes a block in which all deprecation warnings are silenced.
+
+* +ActiveSupport::Deprecation.silenced+ sets whether or not to display deprecation warnings.
+
* +ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+.
+
h3. Rails Environment Settings
Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails:
@@ -384,6 +397,15 @@ Some parts of Rails can also be configured externally by supplying environment v
* +ENV["RAILS_CACHE_ID"]+ and +ENV["RAILS_APP_VERSION"]+ are used to generate expanded cache keys in Rails' caching code. This allows you to have multiple separate caches from the same application.
+
+h3. Using Initializer Files
+
+After loading the framework and any gems and plugins in your application, Rails turns to loading initializers. An initializer is any file of Ruby code stored under +config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks, plugins and gems are loaded, such as options to configure settings for these parts.
+
+NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the initializers folder on down.
+
+TIP: If you have any ordering dependency in your initializers, you can control the load order by naming. For example, +01_critical.rb+ will be loaded before +02_normal.rb+.
+
h3. Initialization events
Rails has 5 initialization events which can be hooked into (listed in order that they are ran):
@@ -392,7 +414,7 @@ Rails has 5 initialization events which can be hooked into (listed in order that
* +before_initialize+: This is run directly before the initialization process of the application occurs with the +:bootstrap_hook+ initializer near the beginning of the Rails initialization process.
-* +to_prepare+: Run after the initializers are ran for all Railties (including the application itself), but before eager loading and the middleware stack is built.
+* +to_prepare+: Run after the initializers are ran for all Railties (including the application itself), but before eager loading and the middleware stack is built.
* +before_eager_load+: This is run directly before eager loading occurs, which is the default behaviour for the _production_ environment and not for the +development+ enviroment.
@@ -411,7 +433,7 @@ initializer "active_support.initialize_whiny_nils" do |app|
end
</ruby>
-The +initializer+ method takes three arguments with the first being the name for the initializer and the second being an options hash (not shown here) and the third being a block. The +:before+ key in the options hash can be specified to specify which initializer this new initializer must run before, and the +:after+ key will specify which initializer to run this initializer _after_.
+The +initializer+ method takes three arguments with the first being the name for the initializer and the second being an options hash (not shown here) and the third being a block. The +:before+ key in the options hash can be specified to specify which initializer this new initializer must run before, and the +:after+ key will specify which initializer to run this initializer _after_.
Initializers defined using the +initializer+ method will be ran in the order they are defined in, with the exception of ones that use the +:before+ or +:after+ methods.
@@ -458,7 +480,7 @@ You might have expected an instance of Array.
The error occurred while evaluating nil.each
</plain>
-*+active_support.deprecation_behavior+* Sets up deprecation reporting for environments, defaulting to +log+ for development, +notify+ for production and +stderr+ for test. If a value isn't set for +config.active_support.deprecation+ then this initializer will prompt the user to configure this line in the current environment's +config/environments+ file.
+*+active_support.deprecation_behavior+* Sets up deprecation reporting for environments, defaulting to +:log+ for development, +:notify+ for production and +:stderr+ for test. If a value isn't set for +config.active_support.deprecation+ then this initializer will prompt the user to configure this line in the current environment's +config/environments+ file. Can be set to an array of values.
*+active_support.initialize_time_zone+* Sets the default time zone for the application based off the +config.time_zone+ setting, which defaults to "UTC".
@@ -538,8 +560,7 @@ TIP: If you have any ordering dependency in your initializers, you can control t
*+set_routes_reloader+* Configures Action Dispatch to reload the routes file using +ActionDispatch::Callbacks.to_prepare+.
-*+disable_dependency_loading+*
-
+*+disable_dependency_loading+* Disables the automatic dependency loading if the +config.cache_classes+ is set to +true+ and +config.dependency_loading+ is set to +false+.
h3. Changelog
diff --git a/railties/guides/source/contribute.textile b/railties/guides/source/contribute.textile
index 3d4607de1d..8d19d78324 100644
--- a/railties/guides/source/contribute.textile
+++ b/railties/guides/source/contribute.textile
@@ -13,8 +13,8 @@ h3. How to Contribute?
* Assets are stored in the +railties/guides/assets+ directory.
* Sample format : "Active Record Associations":http://github.com/lifo/docrails/blob/3e56a3832415476fdd1cb963980d0ae390ac1ed3/railties/guides/source/association_basics.textile.
* Sample output : "Active Record Associations":association_basics.html.
-* You can build the Guides during testing by running +rake generate_guides+ in the +railties+ directory.
-* You're encouraged to validate XHTML for the generated guides before commiting your changes by running +rake validate_guides+ in the +railties+ directory.
+* You can build the Guides during testing by running +bundle exec rake generate_guides+ in the +railties+ directory.
+* You're encouraged to validate XHTML for the generated guides before commiting your changes by running +bundle exec rake validate_guides+ in the +railties+ directory.
* Edge guides "can be consulted online":http://edgeguides.rubyonrails.org/. That website is generated periodically from docrails.
h3. What to Contribute?
diff --git a/railties/guides/source/contributing_to_rails.textile b/railties/guides/source/contributing_to_rails.textile
deleted file mode 100644
index 1a1f4e9858..0000000000
--- a/railties/guides/source/contributing_to_rails.textile
+++ /dev/null
@@ -1,311 +0,0 @@
-h2. Contributing to Rails
-
-This guide covers ways in which _you_ can become a part of the ongoing development of Rails. After reading it, you should be familiar with:
-
-* Using Lighthouse to report issues with Rails
-* Cloning edge Rails and running the test suite
-* Helping to resolve existing issues
-* Contributing to the Rails documentation
-* Contributing to the Rails code
-
-Rails is not "someone else's framework." Over the years, hundreds of people have contributed code ranging from a single character to massive architectural changes, all with the goal of making Rails better for everyone. Even if you don't feel up to writing code yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches to contributing documentation.
-
-endprologue.
-
-h3. Reporting a Rails Issue
-
-Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Rails, this is the place to start. You'll need to create a (free) Lighthouse account in order to comment on issues or to upload tests or patches.
-
-NOTE: Bugs in the most recent released version of Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this Guide you'll find out how to get edge Rails for testing.
-
-h4. Creating a Bug Report
-
-If you've found a problem in Rails, you can start by "adding a new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new to the Rails Lighthouse. At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.
-
-You shouldn't assign the bug to a particular core developer (through the *Who's Responsible* select list) unless you know for sure which developer will be handling any patch. The core team periodically reviews issues and assigns developers and milestones to them.
-
-You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the *Choose some tags* textbox), rather than creating new tags.
-
-Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment.
-
-h4. Special Treatment for Security Issues
-
-If you've found a security vulnerability in Rails, please do *not* report it via a Lighthouse ticket. Lighthouse tickets are public as soon as they are entered. Instead, you should use the dedicated email address "security@rubyonrails.org":mailto:security@rubyonrails.org to report any vulnerabilities. This alias is monitored and the core team will work with you to quickly and completely address any such vulnerabilities.
-
-WARNING: Just to emphasize the point, _please do not report security vulnerabilities on public Lighthouse tickets_. This will only expose your fellow Rails developers to needless risks.
-
-You should receive an acknowledgement and detailed response to any reported security issue within 48 hours. If you don't think you're getting adequate response from the security alias, refer to the "Rails security policy page":http://rubyonrails.org/security for direct emails for the current Rails security coordinators.
-
-h4. What About Feature Requests?
-
-Please don't put "feature request" tickets into Lighthouse. If there's a new feature that you want to see added to Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Rails. If you enter a wishlist item in Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
-
-h3. Running the Rails Test Suite
-
-To move on from submitting bugs to helping resolve existing issues or contributing your own code to Rails, you _must_ be able to run the Rails test suite. In this section of the guide you'll learn how to set up the tests on your own computer.
-
-h4. Install git
-
-Rails uses git for source code control. You won’t be able to do anything without the Rails source code, and this is a prerequisite. The "git homepage":http://git-scm.com/ has installation instructions. If you’re on OS X, use the "Git for OS X":http://code.google.com/p/git-osx-installer/ installer. If you're unfamiliar with git, there are a variety of resources on the net that will help you learn more:
-
-* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/everyday.html will teach you just enough about git to get by.
-* The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow.
-* "GitHub":http://github.com/guides/home offers links to a variety of git resources.
-* "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license.
-
-h4. Get the Rails Source Code
-
-Don’t fork the main Rails repository. Instead, you want to clone it to your own computer. Navigate to the folder where you want the source code (it will create its own /rails subdirectory) and run:
-
-<shell>
-git clone git://github.com/rails/rails.git
-cd rails
-</shell>
-
-h4. Set up and Run the Tests
-
-All of the Rails tests must pass with any code you submit, otherwise you have no chance of getting code accepted. This means you need to be able to run the tests. First, you need to install all Rails dependencies with bundler:
-
-NOTE: Ensure you install bundler v1.0
-
-<shell>
-gem install bundler
-bundle install --without db
-</shell>
-
-The second command will install all dependencies, except MySQL and PostgreSQL. We will come back at these soon. With dependencies installed, you can run the whole Rails test suite with:
-
-<shell>
-rake test
-</shell>
-
-You can also run tests for an specific framework, like Action Pack, by going into its directory and executing the same command:
-
-<shell>
-cd actionpack
-rake test
-</shell>
-
-h4. Testing Active Record
-
-By default, when you run Active Record tests, it will execute the test suite three times, one for each of the main databases: SQLite3, MySQL and PostgreSQL. If you are adding a feature that is not specific to the database, you can run the test suite (or just one file) for just one of them. Here is an example for SQLite3:
-
-<shell>
-cd activerecord
-rake test_sqlite3
-rake test_sqlite3 TEST=test/cases/validations_test.rb
-</shell>
-
-If you want to use another database, as MySQL, you need to create a user named +rails+ with privileges on the test databases.
-
-<shell>
-mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.*
- to 'rails'@'localhost';
-mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.*
- to 'rails'@'localhost';
-</shell>
-
-Now you'll have to install Active Record dependencies. This step is a little tricky because just running +bundle install+ without the +--without db+ parameter won't get those dependencies installed. It turns out that bundler remembers the +--without db+ parameter between calls so you'll have to manually override this. (See the "+bundle_install+ man page":http://gembundler.com/man/bundle-install.1.html for details)
-
-The easiest way to do this is to remove bundler's config file and then run +install+ again:
-
-<shell>
-rm .bundle/config
-bundle install
-</shell>
-
-INFO: If you don't feel comfortable deleting bundler's config file, you can achieve the same effect by manually removing the "+BUNDLE_WITHOUT: db+" line on +.bundle/config+.
-
-Finally, enter this from the +activerecord+ directory to create the test databases:
-
-<shell>
-rake mysql:build_databases
-</shell>
-
-NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation.
-
-If you’re using another database, check the files under +activerecord/test/connections+ in the Rails source code for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails.
-
-You can now run tests as you did for +sqlite3+:
-
-<shell>
-rake test_mysql
-</shell>
-
-You can also replace +mysql+ with +postgresql+, +jdbcmysql+, +jdbcsqlite3+ or +jdbcpostgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the Rails continuous integration server runs.
-
-NOTE: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite 3. Subtle differences between the various Active Record database adapters have been behind the rejection of many patches that looked OK when tested only against MySQL.
-
-h4. Older versions of Rails
-
-If you want to work add a fix to older versions of Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to Rails 2.3 branch:
-
-<shell>
-git branch --track 2-3-stable origin/2-3-stable
-git checkout 2-3-stable
-</shell>
-
-TIP: You may want to "put your git branch name in your shell prompt":http://github.com/guides/put-your-git-branch-name-in-your-shell-prompt to make it easier to remember which version of the code you're working with.
-
-h3. Helping to Resolve Existing Issues
-
-As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find hundreds of issues already requiring attention. What can you do for these? Quite a bit, actually:
-
-h4. Verifying Bug Reports
-
-For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing.
-
-If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem.
-
-If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the Rails source: looking at the existing test files will teach you how to write more tests for Rails. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section.
-
-Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.
-
-h4. Testing Patches
-
-You can also help out by examining patches that have been submitted to Rails via Lighthouse. To apply someone's changes you need to first create a branch of the Rails source code:
-
-<shell>
-git checkout -b testing_branch
-</shell>
-
-Then you can apply their patch:
-
-<shell>
-git apply their-patch-file.diff
-</shell>
-
-After applying a patch, test it out! Here are some things to think about:
-
-* Does the patch actually work?
-* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
-* Does the documentation still seem right to you?
-* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?
-
-Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:
-
-<blockquote>
-I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too.
-</blockquote>
-
-If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the patch. Once three people have approved it, add the "verified" tag. This will bring it to the attention of a core team member who will review the changes looking for the same kinds of things.
-
-h3. Contributing to the Rails Documentation
-
-Another area where you can help out if you're not yet ready to take the plunge to writing Rails core code is with Rails documentation. You can help with the Rails Guides or the Rails API documentation.
-
-TIP: "docrails":http://github.com/lifo/docrails/tree/master is the documentation branch for Rails with an *open commit policy*, it has public write access. Documentation changes made as part of the "docrails":http://github.com/lifo/docrails/tree/master project are merged back to the Rails master code from time to time. Check out the "original announcement":http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch for more details.
-
-h4. The Rails Guides
-
-The "Rails Guides":http://guides.rubyonrails.org/ are a set of online resources that are designed to make people productive with Rails and to understand how all of the pieces fit together. These guides (including this one!) are written as part of the "docrails":http://github.com/lifo/docrails/tree/master project. If you have an idea for a new guide, or improvements for an existing guide, you can refer to the "contribution page":contribute.html for instructions on getting involved.
-
-h4. The Rails API Documentation
-
-The "Rails API documentation":http://api.rubyonrails.org/ is automatically generated from the Rails source code via "RDoc":http://rdoc.rubyforge.org/. If you find some part of the documentation to be incomplete, confusing, or just plain wrong, you can step in and fix it.
-
-To contribute an update to the API documentation, you can contact "lifo":http://github.com/lifo on GitHub and ask for commit rights to the docrails repository and push your changes to the docrails repository. Please follow the "docrails RDoc conventions":http://wiki.github.com/lifo/docrails/rails-api-documentation-conventions when contributing the changes.
-
-h3. The Rails Wiki
-
-The "Rails wiki":http://wiki.rubyonrails.org/ is a collection of user-generated and freely-editable information about Rails. It covers everything from getting started to FAQs to how-tos and popular plugins. To contribute to the wiki, just find some useful information that isn't there already and add it. There are style guidelines to help keep the wiki a coherent resources; see the section on "contributing to the wiki":http://wiki.rubyonrails.org/#contributing_to_the_wiki for more details.
-
-h3. Contributing to the Rails Code
-
-When you're ready to take the plunge, one of the most helpful ways to contribute to Rails is to actually submit source code. Here's a step-by-step listing of the things you need to do to make this a successful experience.
-
-h4. Learn the Language and the Framework
-
-Learn at least _something_ about Ruby and Rails. If you don’t understand the syntax of the language, common Ruby idioms, and the code that already exists in Rails, you’re unlikely to be able to build a good patch (that is, one that will get accepted). You don’t have to know every in-and-out of the language and the framework; some of the Rails code is fiendishly complex. But Rails is probably not appropriate as the first place that you ever write Ruby code. You should at least understand (though not necessarily memorize) "The Ruby Programming Language":http://www.amazon.com/gp/product/0596516177?ie=UTF8&linkCode=as2&camp=1789&creative=390957&creativeASIN=0596516177 and have browsed the Rails source code.
-
-h4. Fork the Rails Source Code
-
-Fork Rails. You’re not going to put your patches right into the master branch, OK? This is where you need that copy of Rails that you cloned earlier. Think of a name for your new branch and run
-
-<shell>
-git checkout -b my_new_branch
-</shell>
-
-It doesn’t really matter what name you use, because this branch will only exist on your local computer.
-
-h4. Write Your Code
-
-Now get busy and add your code to Rails (or edit the existing code). You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind:
-
-* Get the code right
-* Use Rails idioms and helpers
-* Include tests that fail without your code, and pass with it
-* Update the documentation
-
-h4. Follow the Coding Conventions
-
-Rails follows a simple set of coding style conventions.
-
-* Two spaces, no tabs
-* Prefer +&amp;&amp;+/+||+ over +and+/+or+
-* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+
-* Follow the conventions you see used in the source already
-
-h4. Sanity Check
-
-You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either.
-
-You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches.
-
-h4. Commit Your Changes
-
-When you're happy with the code on your computer, you need to commit the changes to git:
-
-<shell>
-git commit -a -m "Here is a commit message"
-</shell>
-
-h4. Update Rails
-
-Update your copy of Rails. It’s pretty likely that other changes to core Rails have happened while you were working. Go get them:
-
-<shell>
-git checkout master
-git pull
-</shell>
-
-Now reapply your patch on top of the latest changes:
-
-<shell>
-git checkout my_new_branch
-git rebase master
-</shell>
-
-No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.
-
-h4. Create a Patch
-
-Now you can create a patch file to share with other developers (and with the Rails core team). Still in your branch, run
-
-<shell>
-git commit -a
-git format-patch master --stdout > my_new_patch.diff
-</shell>
-
-Sanity check the results of this operation: open the diff file in your text editor of choice and make sure that no unintended changes crept in.
-
-h4. Create a Lighthouse Ticket
-
-Now create a ticket with your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense.
-
-h4. Get Some Feedback
-
-Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the rubyonrails-core mailing list or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know.
-
-h4. Iterate as Necessary
-
-It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin.
-
-And then...think about your next contribution!
-
-h3. Changelog
-
-* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
-* August 1, 2009: Updates/amplifications by "Mike Gunderloy":credits.html#mgunderloy
-* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy
-
diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile
new file mode 100644
index 0000000000..4f51c0f859
--- /dev/null
+++ b/railties/guides/source/contributing_to_ruby_on_rails.textile
@@ -0,0 +1,370 @@
+h2. Contributing to Ruby on Rails
+
+This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails. After reading it, you should be familiar with:
+
+* Using Lighthouse to report issues
+* Cloning master and running the test suite
+* Helping to resolve existing issues
+* Contributing to the Ruby on Rails documentation
+* Contributing to the Ruby on Rails code
+
+Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation. All with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.
+
+endprologue.
+
+h3. Reporting an Issue
+
+Ruby on Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) Lighthouse account in order to comment on issues or to upload patches.
+
+NOTE: Bugs in the most recent released version of Ruby on Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide you'll find out how to get edge Rails for testing.
+
+h4. Creating a Bug Report
+
+If you've found a problem in Ruby on Rails which is not a security risk do a search in Lighthouse in case it was already reported. If you find no ticket addressing it you can "add a new one":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new. (See the next section for reporting security issues.)
+
+At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.
+
+You shouldn't assign the bug to a particular core developer unless you know for sure which developer will be handling that issue. The core team periodically reviews issues and assigns developers and milestones to them.
+
+You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the "Choose some tags" textbox), rather than creating new tags.
+
+Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment.
+
+h4. Special Treatment for Security Issues
+
+WARNING: Please do not report security vulnerabilities on public Lighthouse tickets. The "Rails security policy page":http://rubyonrails.org/security details the procedure to follow for security issues.
+
+h4. What About Feature Requests?
+
+Please don't put "feature request" tickets into Lighthouse. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wishlist item in Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
+
+h3. Running the Test Suite
+
+To move on from submitting bugs to helping resolve existing issues or contributing your own code to Ruby on Rails, you _must_ be able to run its test suite. In this section of the guide you'll learn how to set up the tests on your own computer.
+
+h4. Install git
+
+Ruby on Rails uses git for source code control. The "git homepage":http://git-scm.com/ has installation instructions. There are a variety of resources on the net that will help you get familiar with git:
+
+* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/everyday.html will teach you just enough about git to get by.
+* The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow.
+* "GitHub":http://github.com/guides/home offers links to a variety of git resources.
+* "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license.
+
+h4. Clone the Ruby on Rails Repository
+
+Navigate to the folder where you want the Ruby on Rails source code (it will create its own +rails+ subdirectory) and run:
+
+<shell>
+git clone git://github.com/rails/rails.git
+cd rails
+</shell>
+
+h4. Set up and Run the Tests
+
+The test suite must pass with any submitted code. No matter whether you are writing a new patch, or evaluating someone else's, you need to be able to run the tests.
+
+Install first libxml2 and libxslt together with their development files for Nokogiri. In Ubuntu that's
+
+<shell>
+sudo apt-get install libxml2 libxml2-dev libxslt1-dev
+</shell>
+
+Also, SQLite3 and its development files for the +sqlite3-ruby+ gem, in Ubuntu you're done with
+
+<shell>
+sudo apt-get install sqlite3 libsqlite3-dev
+</shell>
+
+Get a recent version of "Bundler":http://gembundler.com/:
+
+<shell>
+gem install bundler
+</shell>
+
+and run:
+
+<shell>
+bundle install --without db
+</shell>
+
+This command will install all dependencies except the MySQL and PostgreSQL Ruby drivers. We will come back at these soon. With dependencies installed, you can run the test suite with:
+
+<shell>
+rake test
+</shell>
+
+You can also run tests for an specific framework, like Action Pack, by going into its directory and executing the same command:
+
+<shell>
+cd actionpack
+rake test
+</shell>
+
+h4. Warnings
+
+The test suite runs with warnings enabled. Ideally Ruby on Rails should issue no warning, but there may be a few, and also some from third-party libraries. Please ignore (or fix!) them if any, and submit patches that do not issue new warnings.
+
+As of this writing they are specially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag:
+
+<shell>
+RUBYOPT=-W0 rake test
+</shell>
+
+h4. Testing Active Record
+
+The test suite of Active Record attempts to run four times, once for SQLite3, once for each of the two MySQL gems (+mysql+ and +mysql2+), and once for PostgreSQL. We are going to see now how to setup the environment for them.
+
+WARNING: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite3. Subtle differences between the various adapters have been behind the rejection of many patches that looked OK when tested only against MySQL.
+
+h5. SQLite3
+
+The gem +sqlite3-ruby+ does not belong to the "db" group indeed, if you followed the instructions above you're ready. This is how you run the Active Record test suite only for SQLite3:
+
+<shell>
+cd activerecord
+rake test_sqlite3
+</shell>
+
+h5. MySQL and PostgreSQL
+
+To be able to run the suite for MySQL and PostgreSQL we need their gems. Install first the servers, their client libraries, and their development files. In Ubuntu just run
+
+<shell>
+sudo apt-get install mysql-server libmysqlclient15-dev
+sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
+</shell>
+
+After that run:
+
+<shell>
+rm .bundle/config
+bundle install
+</shell>
+
+We need first to delete +.bundle/config+ because Bundler remembers in that file that we didn't want to install the "db" group (alternatively you can edit the file).
+
+In order to be able to run the test suite against MySQL you need to create a user named +rails+ with privileges on the test databases:
+
+<shell>
+mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.*
+ to 'rails'@'localhost';
+mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.*
+ to 'rails'@'localhost';
+</shell>
+
+and create the test databases:
+
+<shell>
+cd activerecord
+rake mysql:build_databases
+</shell>
+
+PostgreSQL's authentication works differently. A simple way to setup the development environment for example is to run with your development account
+
+<shell>
+sudo -u postgres createuser --superuser $USER
+</shell>
+
+and after that create the test databases with
+
+<shell>
+cd activerecord
+rake postgresql:build_databases
+</shell>
+
+NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation.
+
+If you’re using another database, check the files under +activerecord/test/connections+ for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails.
+
+You can now run tests as you did for +sqlite3+, the tasks are
+
+<shell>
+test_mysql
+test_mysql2
+test_postgresql
+</shell>
+
+respectively. As we mentioned before
+
+<shell>
+rake test
+</shell>
+
+will now run the four of them in turn.
+
+You can also invoke +test_jdbcmysql+, +test_jdbcsqlite3+ or +test_jdbcpostgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the continuous integration server runs.
+
+h4. Older versions of Ruby on Rails
+
+If you want to add a fix to older versions of Ruby on Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to the 2-3-stable branch:
+
+<shell>
+git branch --track 2-3-stable origin/2-3-stable
+git checkout 2-3-stable
+</shell>
+
+TIP: You may want to "put your git branch name in your shell prompt":http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/ to make it easier to remember which version of the code you're working with.
+
+h3. Helping to Resolve Existing Issues
+
+As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
+
+h4. Verifying Bug Reports
+
+For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing.
+
+If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem.
+
+If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the source code: looking at the existing test files will teach you how to write more tests. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section.
+
+Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.
+
+h4. Testing Patches
+
+You can also help out by examining patches that have been submitted to Ruby on Rails via Lighthouse. To apply someone's changes you need to first create a dedicated branch:
+
+<shell>
+git checkout -b testing_branch
+</shell>
+
+Then you can apply their patch:
+
+<shell>
+git am their-patch-file.diff
+</shell>
+
+After applying a patch, test it out! Here are some things to think about:
+
+* Does the patch actually work?
+* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
+* Does it have proper documentation coverage? Should documentation elsewhere be updated?
+* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?
+
+Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:
+
+<blockquote>
+I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too.
+</blockquote>
+
+If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the patch. Once three people have approved it, add the "verified" tag. This will bring it to the attention of a core team member who will review the changes looking for the same kinds of things.
+
+h3. Contributing to the Rails Documentation
+
+Ruby on Rails has two main sets of documentation: The guides help you to learn Ruby on Rails, and the API is a reference.
+
+You can create a ticket in Lighthouse to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":http://github.com/lifo/docrails/tree/master. docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation.
+
+When working with documentation, please take into account the "API Documentation Guidelines":api_documentation_guidelines.html and the "Ruby on Rails Guides Guidelines":ruby_on_rails_guides_guidelines.html.
+
+NOTE: As explained above, ordinary code patches should have proper documentation coverage. docrails is only used for isolated documentation improvements.
+
+WARNING: docrails has a very strict policy: no code can be touched whatsoever, no matter how trivial or small the change. Only RDoc and guides can be edited via docrails.
+
+If you have an idea for a new guide you can refer to the "contribution page":contribute.html for instructions on getting involved.
+
+h3. Contributing to the Rails Code
+
+h4. Clone the Rails Repository
+
+The first thing you need to do to be able to contribute code is to clone the repository:
+
+<shell>
+git clone git://github.com/rails/rails.git
+</shell>
+
+and create a dedicated branch:
+
+<shell>
+cd rails
+git checkout -b my_new_branch
+</shell>
+
+It doesn’t really matter what name you use, because this branch will only exist on your local computer.
+
+h4. Write Your Code
+
+Now get busy and add or edit code. You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind:
+
+* Get the code right
+* Use Rails idioms and helpers
+* Include tests that fail without your code, and pass with it
+* Update the documentation, the surrounding one, examples elsewhere, guides, whatever is affected by your contribution
+
+h4. Follow the Coding Conventions
+
+Rails follows a simple set of coding style conventions.
+
+* Two spaces, no tabs
+* Prefer +&amp;&amp;+/+||+ over +and+/+or+
+* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+
+* Follow the conventions you see used in the source already
+
+h4. Sanity Check
+
+You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either.
+
+You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches.
+
+h4. Commit Your Changes
+
+When you're happy with the code on your computer, you need to commit the changes to git:
+
+<shell>
+git commit -a -m "Here is a commit message"
+</shell>
+
+h4. Update master
+
+It’s pretty likely that other changes to master have happened while you were working. Go get them:
+
+<shell>
+git checkout master
+git pull
+</shell>
+
+Now reapply your patch on top of the latest changes:
+
+<shell>
+git checkout my_new_branch
+git rebase master
+</shell>
+
+No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.
+
+h4. Create a Patch
+
+Now you can create a patch file to share with other developers (and with the core team). Still in your branch, run
+
+<shell>
+git commit -a
+git format-patch master --stdout > my_new_patch.diff
+</shell>
+
+Sanity check the results of this operation: open the diff file in your text editor of choice and make sure that no unintended changes crept in.
+
+h4. Create a Lighthouse Ticket
+
+Now create a ticket with your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense.
+
+h4. Get Some Feedback
+
+Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the rubyonrails-core mailing list or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know.
+
+h4. Iterate as Necessary
+
+It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin.
+
+And then...think about your next contribution!
+
+h3. Rails Contributors
+
+All contributions, either via master or docrails, get credit in "Rails Contributors":http://contributors.rubyonrails.org.
+
+h3. Changelog
+
+* December 28, 2010: Complete revision by "Xavier Noria":credits.html#fxn
+* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
+* August 1, 2009: Updates/amplifications by "Mike Gunderloy":credits.html#mgunderloy
+* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy
+
diff --git a/railties/guides/source/credits.html.erb b/railties/guides/source/credits.html.erb
index 825e042628..8c2f1ffeb6 100644
--- a/railties/guides/source/credits.html.erb
+++ b/railties/guides/source/credits.html.erb
@@ -20,7 +20,7 @@ Ruby on Rails Guides: Credits
<% end %>
<%= author('Xavier Noria', 'fxn', 'fxn.png') do %>
- Xavier has been into Rails since 2005, he is currently a Rails consultant. Xavier is Rails committer and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as &quot;fxn&quot;.
+ Xavier Noria has been into Ruby on Rails since 2005. He is a Rails committer and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Xavier is currently a Ruby on Rails consultant. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as &quot;fxn&quot;.
<% end %>
<h3 class="section">Rails Guides Designers</h3>
@@ -52,7 +52,7 @@ Ruby on Rails Guides: Credits
<% end %>
<%= author('James Miller', 'bensie') do %>
- James Miller is a software developer for <a href="http://www.jk-tech.com">JK Tech</a> in San Diego, CA. Find me on GitHub, Gmail, Twitter, and Freenode as &quot;bensie&quot;.
+ James Miller is a software developer for <a href="http://www.jk-tech.com">JK Tech</a> in San Diego, CA. You can find James on GitHub, Gmail, Twitter, and Freenode as &quot;bensie&quot;.
<% end %>
<%= author('Emilio Tagua', 'miloops') do %>
diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile
index 2c8a6619c2..b84d7d088d 100644
--- a/railties/guides/source/debugging_rails_applications.textile
+++ b/railties/guides/source/debugging_rails_applications.textile
@@ -269,7 +269,7 @@ If you got there by a browser request, the browser tab containing the request wi
For example:
<shell>
-@posts = Post.find(:all)
+@posts = Post.all
(rdb:7)
</shell>
@@ -302,7 +302,7 @@ This command shows you where you are in the code by printing 10 lines centered a
3 # GET /posts.xml
4 def index
5 debugger
-=> 6 @posts = Post.find(:all)
+=> 6 @posts = Post.all
7
8 respond_to do |format|
9 format.html # index.html.erb
@@ -380,7 +380,7 @@ Any expression can be evaluated in the current context. To evaluate an expressio
This example shows how you can print the instance_variables defined within the current context:
<shell>
-@posts = Post.find(:all)
+@posts = Post.all
(rdb:11) instance_variables
["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"]
</shell>
diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile
index e178a60307..40db43079c 100644
--- a/railties/guides/source/form_helpers.textile
+++ b/railties/guides/source/form_helpers.textile
@@ -9,6 +9,7 @@ In this guide you will:
* Generate select boxes from multiple types of data
* Understand the date and time helpers Rails provides
* Learn what makes a file upload form different
+* Learn some cases of building forms to external resources
* Find out where to look for complex forms
endprologue.
@@ -644,7 +645,7 @@ Fundamentally HTML forms don't know about any sort of structured data, all they
TIP: You may find you can try out examples in this section faster by using the console to directly invoke Rails' parameter parser. For example,
<ruby>
-ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789"
+ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789"
# => {"name"=>"fred", "phone"=>"0123456789"}
</ruby>
@@ -763,6 +764,40 @@ As a shortcut you can append [] to the name and omit the +:index+ option. This i
produces exactly the same output as the previous example.
+h3. Forms to external resources
+
+If you need to post some data to an external resource it is still great to build your from using rails form helpers. But sometimes you need to set an +authenticity_token+ for this resource. You can do it by passing an +:authenticity_token => 'your_external_token'+ parameter to the +form_tag+ options:
+
+<erb>
+<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %>
+ Form contents
+<% end %>
+</erb>
+
+Sometimes when you submit data to an external resource, like payment gateway, fields you can use in your form are limited by an external API. So you may want not to generate an +authenticity_token+ hidden field at all. For doing this just pass +false+ to the +:authenticity_token+ option:
+
+<erb>
+<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %>
+ Form contents
+<% end %>
+</erb>
+
+The same technique is available for the +form_for+ too:
+
+<erb>
+<%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f|
+ Form contents
+<% end %>
+</erb>
+
+Or if you don't want to render an +authenticity_token+ field:
+
+<erb>
+<%= form_for @invoice, :url => external_url, :authenticity_token => false do |f|
+ Form contents
+<% end %>
+</erb>
+
h3. Building Complex Forms
Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include:
@@ -776,6 +811,7 @@ Many apps grow beyond simple forms editing a single object. For example when cre
h3. Changelog
+* February 5, 2011: Added 'Forms to external resources' section. Timothy N. Tsvetkov <timothy.tsvetkov@gmail.com>
* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
h3. Authors
diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile
index 6945f6f9bb..3adbbfa7aa 100644
--- a/railties/guides/source/generators.textile
+++ b/railties/guides/source/generators.textile
@@ -371,16 +371,16 @@ h3. Application templates
Now that you've seen how generators can be used _inside_ an application, did you know they can also be used to _generate_ applications too? This kind of generator is referred as a "template".
<ruby>
- gem("rspec-rails", :group => "test")
- gem("cucumber-rails", :group => "test")
-
- if yes?("Would you like to install Devise?")
- gem("devise")
- generate("devise:install")
- model_name = ask("What would you like the user model to be called? [user]")
- model_name = "user" if model_name.blank?
- generate("devise", model_name)
- end
+gem("rspec-rails", :group => "test")
+gem("cucumber-rails", :group => "test")
+
+if yes?("Would you like to install Devise?")
+ gem("devise")
+ generate("devise:install")
+ model_name = ask("What would you like the user model to be called? [user]")
+ model_name = "user" if model_name.blank?
+ generate("devise", model_name)
+end
</ruby>
In the above template we specify that the application relies on the +rspec-rails+ and +cucumber-rails+ gem so these two will be added to the +test+ group in the +Gemfile+. Then we pose a question to the user about whether or not they would like to install Devise. If the user replies "y" or "yes" to this question, then the template will add Devise to the +Gemfile+ outside of any group and then runs the +devise:install+ generator. This template then takes the users input and runs the +devise+ generator, with the user's answer from the last question being passed to this generator.
@@ -396,14 +396,14 @@ This command will generate the +Thud+ application, and then apply the template t
Templates don't have to be stored on the local system, the +-m+ option also supports online templates:
<shell>
- rails new thud -m https://gist.github.com/722911
+ rails new thud -m https://gist.github.com/722911.txt
</shell>
Whilst the final section of this guide doesn't cover how to generate the most awesome template known to man, it will take you through the methods available at your disposal so that you can develop it yourself. These same methods are also available for generators.
h3. Generator methods
-The following are methods available for both generators and templates for Rails.
+The following are methods available for both generators and templates for Rails.
NOTE: Methods provided by Thor are not covered this guide and can be found in "Thor's documentation":http://rdoc.info/github/wycats/thor/master/Thor/Actions.html
@@ -428,8 +428,8 @@ h4. +gem+
Specifies a gem dependency of the application.
<ruby>
- gem("rspec", :group => "test", :version => "2.1.0")
- gem("devise", "1.1.5")
+gem("rspec", :group => "test", :version => "2.1.0")
+gem("devise", "1.1.5")
</ruby>
Available options are:
@@ -470,10 +470,9 @@ Adds a line to +config/application.rb+ directly after the application class defi
This method can also take a block:
<ruby>
- application do
- "config.asset_host = 'http://example.com'"
- end
- end
+application do
+ "config.asset_host = 'http://example.com'"
+end
</ruby>
Available options are:
@@ -481,9 +480,9 @@ Available options are:
* +:env+ - Specify an environment for this configuration option. If you wish to use this option with the block syntax the recommended syntax is as follows:
<ruby>
- application(nil, :env => "development") do
- "config.asset_host = 'http://localhost:3000'"
- end
+application(nil, :env => "development") do
+ "config.asset_host = 'http://localhost:3000'"
+end
</ruby>
h4. +git+
@@ -526,9 +525,9 @@ Places a file into +lib+ which contains the specified code.
This method also takes a block:
<ruby>
- lib("super_special.rb") do
- puts "Super special!"
- end
+lib("super_special.rb") do
+ puts "Super special!"
+end
</ruby>
h4. +rakefile+
@@ -542,13 +541,13 @@ Creates a Rake file in the +lib/tasks+ directory of the application.
This method also takes a block:
<ruby>
- rakefile("test.rake") do
- %Q{
- task :rock => :environment do
- puts "Rockin'"
- end
- }
- end
+rakefile("test.rake") do
+ %Q{
+ task :rock => :environment do
+ puts "Rockin'"
+ end
+ }
+end
</ruby>
h4. +initializer+
@@ -562,9 +561,9 @@ Creates an initializer in the +config/initializers+ directory of the application
This method also takes a block:
<ruby>
- initializer("begin.rb") do
- puts "Almost done!"
- end
+initializer("begin.rb") do
+ puts "Almost done!"
+end
</ruby>
h4. +generate+
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile
index e371632d87..82700532c0 100644
--- a/railties/guides/source/getting_started.textile
+++ b/railties/guides/source/getting_started.textile
@@ -163,7 +163,7 @@ $ rails new blog
This will create a Rails application called Blog in a directory called blog.
-TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails -h</tt>.
+TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails new -h</tt>.
After you create the blog application, switch to its folder to continue work directly in that application:
@@ -184,7 +184,7 @@ In any case, Rails will create a folder in your working directory called <tt>blo
|doc/|In-depth documentation for your application.|
|lib/|Extended modules for your application (not covered in this guide).|
|log/|Application log files.|
-|public/|The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go.|
+|public/|The only folder seen to the world as-is. This is where your images, JavaScript files, stylesheets (CSS), and other static files go.|
|script/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.|
|test/|Unit tests, fixtures, and other test apparatus. These are covered in "Testing Rails Applications":testing.html|
|tmp/|Temporary files|
@@ -227,7 +227,7 @@ NOTE: In this guide we are using an SQLite3 database for data storage, because i
h5. Configuring a MySQL Database
-If you choose to use MySQL instead of the shipped Sqlite3 database, your +config/database.yml+ will look a little different. Here's the development section:
+If you choose to use MySQL instead of the shipped SQLite3 database, your +config/database.yml+ will look a little different. Here's the development section:
<yaml>
development:
@@ -258,6 +258,8 @@ development:
Change the username and password in the +development+ section as appropriate.
+TIP: You don't have to update the database configurations manually. If you had a look at the options of application generator, you have seen that one of them is named <tt>--database</tt>. It lets you choose an adapter for couple of most used relational databases. You can even run the generator repeatedly: <tt>cd .. && rails new blog --database=mysql</tt>. When you confirm the overwriting of the +config/database.yml+ file, your application will be configured for MySQL instead of SQLite.
+
h4. Creating the Database
Now that you have your database configured, it's time to have Rails create an empty database for you. You can do this by running a rake command:
@@ -298,7 +300,7 @@ To get Rails saying "Hello", you need to create at minimum a controller and a vi
$ rails generate controller home index
</shell>
-TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: +ruby \path\to\rails controller home index+.
+TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: <tt>ruby \path\to\your\application\script\rails generate controller home index</tt>.
Rails will create several files for you, including +app/views/home/index.html.erb+. This is the template that will be used to display the results of the +index+ action (method) in the +home+ controller. Open this file in your text editor and edit it to contain a single line of code:
@@ -347,7 +349,7 @@ In the case of the blog application, you can start by generating a scaffolded Po
$ rails generate scaffold Post name:string title:string content:text
</shell>
-NOTE. While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch.
+NOTE. While scaffolding will get you up and running quickly, the code it generates is unlikely to be a perfect fit for your application. You'll most probably want to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch. Rails, however, makes it really simple to customize templates for generated models, controllers, views and other source files. You'll find more information in the "Creating and Customizing Rails Generators & Templates":generators.html guide.
The scaffold generator will build 15 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates:
@@ -409,7 +411,7 @@ Rails will execute this migration command and tell you it created the Posts tabl
== CreatePosts: migrated (0.0020s) ===========================================
</shell>
-NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file.
+NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. If you would like to execute migrations in other environment, for instance in production, you must explicitely pass it when invoking the command: <tt>rake db:migrate RAILS_ENV=production</tt>.
h4. Adding a Link
diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile
index 8a39bdf3c1..e47ac7aed6 100644
--- a/railties/guides/source/i18n.textile
+++ b/railties/guides/source/i18n.textile
@@ -10,7 +10,7 @@ So, in the process of _internationalizing_ your Rails application you have to:
* Tell Rails where to find locale dictionaries
* Tell Rails how to set, preserve and switch locale
-In the process of _localizing_ your application you'll probably want to do following three things:
+In the process of _localizing_ your application you'll probably want to do the following three things:
* Replace or supplement Rails' default locale -- e.g. date and time formats, month names, Active Record model names, etc
* Abstract strings in your application into keyed dictionaries -- e.g. flash messages, static text in your views, etc.
@@ -305,12 +305,12 @@ end
# app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
- flash[:notice] = "Hello flash!"
+ flash[:notice] = "Hello Flash"
end
end
# app/views/home/index.html.erb
-<h1>Hello world!</h1>
+<h1>Hello World</h1>
<p><%= flash[:notice] %></p>
</ruby>
@@ -344,8 +344,8 @@ So let's add the missing translations into the dictionary files (i.e. do the "lo
<ruby>
# config/locales/en.yml
en:
- hello_world: Hello World
- hello_flash: Hello Flash
+ hello_world: Hello world!
+ hello_flash: Hello flash!
# config/locales/pirate.yml
pirate:
@@ -586,7 +586,7 @@ I18n.t :foo
I18n.l Time.now
</ruby>
-Explicitely passing a locale:
+Explicitly passing a locale:
<ruby>
I18n.t :foo, :locale => :de
@@ -623,7 +623,7 @@ pt:
bar: baz
</ruby>
-As you see, in both cases the toplevel key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz".
+As you see, in both cases the top level key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz".
Here is a "real" example from the Active Support +en.yml+ translations YAML file:
@@ -713,12 +713,12 @@ end
Then Active Record will look for messages in this order:
<ruby>
-activerecord.errors.models.admin.attributes.title.blank
+activerecord.errors.models.admin.attributes.name.blank
activerecord.errors.models.admin.blank
-activerecord.errors.models.user.attributes.title.blank
+activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
-errors.attributes.title.blank
+errors.attributes.name.blank
errors.messages.blank
</ruby>
@@ -852,7 +852,7 @@ h3. Conclusion
At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.
-If you find anything missing or wrong in this guide please file a ticket on "our issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions please sign up to our "mailinglist":http://groups.google.com/group/rails-i18n.
+If you find anything missing or wrong in this guide, please file a ticket on our "issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions, please sign up to our "mailing list":http://groups.google.com/group/rails-i18n.
h3. Contributing to Rails I18n
@@ -867,10 +867,10 @@ If you find your own locale (language) missing from our "example translations da
h3. Resources
* "rails-i18n.org":http://rails-i18n.org - Homepage of the rails-i18n project. You can find lots of useful resources on the "wiki":http://rails-i18n.org/wiki.
-* "rails-i18n Google group":http://groups.google.com/group/rails-i18n - The project's mailing list.
+* "Google group: rails-i18n":http://groups.google.com/group/rails-i18n - The project's mailing list.
* "Github: rails-i18n":http://github.com/svenfuchs/rails-i18n/tree/master - Code repository for the rails-i18n project. Most importantly you can find lots of "example translations":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for Rails that should work for your application in most cases.
-* "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project.
* "Github: i18n":http://github.com/svenfuchs/i18n/tree/master - Code repository for the i18n gem.
+* "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project.
* "Lighthouse: i18n":http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview - Issue tracker for the i18n gem.
@@ -879,7 +879,7 @@ h3. Authors
* "Sven Fuchs":http://www.workingwithrails.com/person/9963-sven-fuchs (initial author)
* "Karel Minařík":http://www.workingwithrails.com/person/7476-karel-mina-k
-If you found this guide useful please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com.
+If you found this guide useful, please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com.
h3. Footnotes
diff --git a/railties/guides/source/index.html.erb b/railties/guides/source/index.html.erb
index 84fbc53a69..933bf66b3f 100644
--- a/railties/guides/source/index.html.erb
+++ b/railties/guides/source/index.html.erb
@@ -151,17 +151,17 @@ Ruby on Rails Guides
<% end %>
</dl>
-<h3>Contributing to Rails</h3>
+<h3>Contributing to Ruby on Rails</h3>
<dl>
- <%= guide("Contributing to Rails", 'contributing_to_rails.html') do %>
+ <%= guide("Contributing to Ruby on Rails", 'contributing_to_ruby_on_rails.html') do %>
<p>Rails is not &quot;somebody else's framework.&quot; This guide covers a variety of ways that you can get involved in the ongoing development of Rails.</p>
<% end %>
<%= guide('API Documentation Guidelines', 'api_documentation_guidelines.html') do %>
<p>This guide documents the Ruby on Rails API documentation guidelines.</p>
<% end %>
-
+
<%= guide('Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html') do %>
<p>This guide documents the Ruby on Rails guides guidelines.</p>
<% end %>
diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile
index 72e10191f9..0cbbe1f389 100644
--- a/railties/guides/source/initialization.textile
+++ b/railties/guides/source/initialization.textile
@@ -31,7 +31,7 @@ The actual +rails+ command is kept in _bin/rails_ at the and goes like this:
end
</ruby>
-This file will attempt to load +rails/cli+ and if it cannot find it then add the +railties/lib+ path to the load path (+$:+) and will then try to require it again.
+This file will attempt to load +rails/cli+ and if it cannot find it then add the +railties/lib+ path to the load path (+$:+) and will then try to require it again.
h4. +railites/lib/rails/cli.rb+
@@ -120,7 +120,7 @@ This climbs the directory tree until it reaches a path which contains a +script/
This is effectively the same as doing +ruby script/rails [arguments]+. Where +[arguments]+ at this point in time is simply "server".
-h4. +script/rails+
+h4. +script/rails+
This file looks like this:
@@ -222,9 +222,27 @@ h4. +actionpack/lib/action_dispatch.rb+
Action Dispatch is the routing component of the Rails framework. It depends on Active Support, +actionpack/lib/action_pack.rb+ and +Rack+ being available. The first thing required here is +active_support+.
-h4. +active_support/lib/active_support.rb+
+h4. +activesupport/lib/active_support.rb+
-This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+.
+This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+. The required file also requires another file: +active_support/lazy_load_hooks+
+
+h4. +activesupport/lib/active_support/lazy_load_hooks.rb+
+
+This file defines the +ActiveSupport.on_load+ hook which is used to execute code when specific parts are loaded. We'll see this in use a little later on.
+
+This file begins with requiring +active_support/inflector/methods+.
+
+h4. +activesupport/lib/active_support/inflector/methods.rb+
+
+The +methods.rb+ file is responsible for defining methods such as +camelize+, +underscore+ and +dasherize+ as well as a slew of others. The "+ActiveSupport::Inflector+ documentation":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html covers them all pretty decently.
+
+In this file there are a lot of lines such as this inside the +ActiveSupport+ module:
+
+<ruby>
+ autoload :Inflector
+</ruby>
+
+Due to the overriding of the +autoload+ method, Ruby will know to look for this file at +activesupport/lib/active_support/inflector.rb+ when the +Inflector+ class is first referenced.
The +active_support/lib/active_support/version.rb+ that is also required here simply defines an +ActiveSupport::VERSION+ constant which defines a couple of constants inside this module, the main constant of this is +ActiveSupport::VERSION::STRING+ which returns the current version of ActiveSupport.
@@ -236,7 +254,7 @@ Now back to +action_pack/lib/action_dispatch.rb+. The next +require+ in this fil
After this line, there's a require to +active_model+ which simply defines autoloads for the +ActiveModel+ part of Rails and sets up the +ActiveModel+ module which is used later on.
-The last of the requires is to +rack+, which like the +active_model+ and +active_support+ requires before it, sets up the +Rack+ module as well as the autoloads for constants within it.
+The last of the requires is to +rack+, which like the +active_model+ and +active_support+ requires before it, sets up the +Rack+ module as well as the autoloads for constants within it.
Finally in +action_dispatch.rb+ the +ActionDispatch+ module and *its* autoloads are declared.
@@ -337,7 +355,7 @@ The class *is* defined in +Rack::Server+, but is overwritten in +Rails::Server+
...
</ruby>
-This method will set up keys for the +options+ which Rails will then be able to use to determine how its server should run. After +initialize+ has finished, then the +start+ method will launch the server.
+This method will set up keys for the +options+ which Rails will then be able to use to determine how its server should run. After +initialize+ has finished, then the +start+ method will launch the server.
h4. +Rails::Server#start+
@@ -448,9 +466,13 @@ This file begins with requiring +config/application.rb+.
h4. +config/application.rb+
-This file requires +config/boot.rb+, but only if it hasn't been required before, which would be the case in +rails server+ but *wouldn't* be the case with Passenger.
+This file requires +config/boot.rb+, but only if it hasn't been required before, which would be the case in +rails server+ but *wouldn't* be the case with Passenger.
-Then the fun begins! The next line is:
+Then the fun begins!
+
+h3. Loading Rails
+
+The next line in +config/application.rb+ is:
<ruby>
require 'rails/all'
@@ -486,514 +508,128 @@ This file is responsible for the initial definition of the +Rails+ module and, r
However, before all that takes place the +rails/ruby_version_check+ file is required first.
+h4. +railties/lib/rails/ruby_version_check.rb+
+This file simply checks if the Ruby version is less than 1.8.7 or is 1.9.1 and raises an error if that is the case. Rails 3 simply will not run on earlier versions of Ruby than 1.8.7 or 1.9.1.
+NOTE: You should always endeavour to run the latest version of Ruby with your Rails applications. The benefits are many, including security fixes and the like, and very often there is a speed increase associated with it. The caveat is that you could have code that potentially breaks on the latest version, which should be fixed to work on the latest version rather than kept around as an excuse not to upgrade.
-**** REVIEW IS HERE ****
-
-This defines two methods on the module itself by using the familiar +class << self+ syntax. This allows you to call them as if they were class methods: +ActiveSupport.on_load_all+ and +ActiveSupport.load_all!+ respectively. The first method simply adds loading hooks to save them up for loading later on when +load_all!+ is called. By +call+'ing the block, the classes will be loaded. (NOTE: kind of guessing, I feel 55% about this).
-
-The +on_load_all+ method is called later with the +Dependencies+, +Deprecation+, +Gzip+, +MessageVerifier+, +Multibyte+ and +SecureRandom+. What each of these modules do will be covered later.
-
-This file goes on to define some classes that will be automatically loaded using Ruby's +autoload+ method, but not before including Rails's own variant of the +autoload+ method from _active_support/dependencies/autoload.rb_:
-
-
-<ruby>
- require "active_support/inflector/methods"
- require "active_support/lazy_load_hooks"
-
- module ActiveSupport
- module Autoload
- def self.extended(base)
- base.extend(LazyLoadHooks)
- end
-
- @@autoloads = {}
- @@under_path = nil
- @@at_path = nil
- @@eager_autoload = false
-
- def autoload(const_name, path = @@at_path)
- full = [self.name, @@under_path, const_name.to_s, path].compact.join("::")
- location = path || Inflector.underscore(full)
-
- if @@eager_autoload
- @@autoloads[const_name] = location
- end
- super const_name, location
- end
-
- ...
- end
- end
-</ruby>
-
-h4. Lazy Hooks
-
-+ActiveSupport::LazyLoadHooks+ is responsible for defining methods used for running hooks that are defined during the initialization process, such as the one defined inside the +active_record.initialize_timezone+ initializer:
-
-<ruby>
- initializer "active_record.initialize_timezone" do
- ActiveSupport.on_load(:active_record) do
- self.time_zone_aware_attributes = true
- self.default_timezone = :utc
- end
- end
-</ruby>
-
-When the initializer runs it invokes method +on_load+ for +ActiveRecord+ and the block passed to it would be called only when +run_load_hooks+ is called.
-When the entirety of +activerecord/lib/active_record/base.rb+ has been evaluated then +run_load_hooks+ is invoked. The very last line of +activerecord/lib/active_record/base.rb+ is:
-
-<ruby>
-ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
-</ruby>
-
-h4. +require 'active_support'+ cont'd.
-
-This file also uses the method +eager_autoload+ also defined in _active_support/dependencies/autoload.rb_:
-
-<ruby>
- def eager_autoload
- old_eager, @@eager_autoload = @@eager_autoload, true
- yield
- ensure
- @@eager_autoload = old_eager
- end
-</ruby>
-
-As you can see for the duration of the +eager_autoload+ block the class variable +@@eager_autoload+ is set to +true+, which has the consequence of when +autoload+ is called that the location of the file for that specific +autoload+'d constant is added to the +@@autoloads+ hash initialized at the beginning of this module declaration. So now that you have part of the context, here's the other, the code from _activesupport/lib/active_support.rb_:
-
-<ruby>
- require "active_support/dependencies/autoload"
-
- module ActiveSupport
- extend ActiveSupport::Autoload
-
- autoload :DescendantsTracker
- autoload :FileUpdateChecker
- autoload :LogSubscriber
- autoload :Notifications
-
- # TODO: Narrow this list down
- eager_autoload do
- autoload :BacktraceCleaner
- autoload :Base64
- autoload :BasicObject
- autoload :Benchmarkable
- autoload :BufferedLogger
- autoload :Cache
- autoload :Callbacks
- autoload :Concern
- autoload :Configurable
- autoload :Deprecation
- autoload :Gzip
- autoload :Inflector
- autoload :JSON
- autoload :Memoizable
- autoload :MessageEncryptor
- autoload :MessageVerifier
- autoload :Multibyte
- autoload :OptionMerger
- autoload :OrderedHash
- autoload :OrderedOptions
- autoload :Rescuable
- autoload :SecureRandom
- autoload :StringInquirer
- autoload :XmlMini
- end
-
- autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
- autoload :TestCase
- end
-
- autoload :I18n, "active_support/i18n"
-</ruby>
-
-So we know the ones in +eager_autoload+ are eagerly loaded and it does this by storing them in an +@@autoloads+ hash object and then loading them via +eager_autoload!+ which is called via the +preload_frameworks+ initializer defined in _railties/lib/rails/application/bootstrap.rb_.
-
-The classes and modules that are not +eager_autoload+'d are automatically loaded as they are references
-
-Note: What does it means to be autoloaded? An example of this would be calling the +ActiveSupport::TestCase+ class which hasn't yet been initialized. Because it's been specified as an +autoload+ Ruby will require the file that it's told to. The file it requires is not defined in the +autoload+ call here but, as you may have seen, in the +ActiveSupport::Autoload.autoload+ definition. So once that file has been required Ruby will try again and then if it still can't find it it will throw the all-too-familiar +uninitialized constant+ error.
-
-h4. +require 'action_dispatch'+
-
-Back in _actionpack/lib/action_dispatch.rb_, the next require after _active_support_ is to _active_support/dependencies/autoload_ but this file has already been loaded by _activesupport/lib/active_support.rb_ and so will not be loaded again. The next require is to Rack itself:
-
-<ruby>
- require 'rack'
-</ruby>
-
-As mentioned previously, Bundler has added the gems' _lib_ directories to the load path so this _rack_ file that is referenced lives in the Rack gem: _lib/rack.rb_. This loads Rack so we can use it later on when we define +Rails::Server+ to descend from +Rack::Server+.
-
-This file then goes on to define the +ActionDispatch+ module and it's related autoloads:
-
-<ruby>
- module Rack
- autoload :Test, 'rack/test'
- end
-
- module ActionDispatch
- extend ActiveSupport::Autoload
-
- autoload_under 'http' do
- autoload :Request
- autoload :Response
- end
-
- autoload_under 'middleware' do
- autoload :Callbacks
- autoload :Cascade
- autoload :Cookies
- autoload :Flash
- autoload :Head
- autoload :ParamsParser
- autoload :RemoteIp
- autoload :Rescue
- autoload :ShowExceptions
- autoload :Static
- end
-
- autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
- autoload :Routing
-
- module Http
- extend ActiveSupport::Autoload
-
- autoload :Cache
- autoload :Headers
- autoload :MimeNegotiation
- autoload :Parameters
- autoload :FilterParameters
- autoload :Upload
- autoload :UploadedFile, 'action_dispatch/http/upload'
- autoload :URL
- end
-
- module Session
- autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
- autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
- autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
- end
-
- autoload_under 'testing' do
- autoload :Assertions
- autoload :Integration
- autoload :PerformanceTest
- autoload :TestProcess
- autoload :TestRequest
- autoload :TestResponse
- end
- end
-
- autoload :Mime, 'action_dispatch/http/mime_type'
-</ruby>
-
-h4. +require "rails/commands/server"+
-
-Now that Rails has required Action Dispatch and it has required Rack, Rails can now go about defining the +Rails::Server+ class:
-
-<ruby>
- module Rails
- class Server < ::Rack::Server
-
- ...
-
- def initialize(*)
- super
- set_environment
- end
-
- ...
-
- def set_environment
- ENV["RAILS_ENV"] ||= options[:environment]
- end
- ...
- end
- end
-</ruby>
-
-h4. +require "rails/commands"+
-
-Back in _rails/commands_ Rails calls +Rails::Server.new+ which calls the +initialize+ method on the +Rails::Server+ class, which calls +super+, meaning it's actually calling +Rack::Server#initialize+, with it being defined like this:
-
-<ruby>
- def initialize(options = nil)
- @options = options
- end
-</ruby>
-
-The +options+ method like this:
-
-<ruby>
- def options
- @options ||= parse_options(ARGV)
- end
-</ruby>
+h4. +active_support/core_ext/kernel/reporting.rb+
-The +parse_options+ method like this:
+This is the first of the many Active Support core extensions that come with Rails. This one in particular defines methods in the +Kernel+ module which is mixed in to the +Object+ class so the methods are available on +main+ and can therefore be called like this:
<ruby>
- def parse_options(args)
- options = default_options
-
- # Don't evaluate CGI ISINDEX parameters.
- # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
- args.clear if ENV.include?("REQUEST_METHOD")
-
- options.merge! opt_parser.parse! args
- options
+ silence_warnings do
+ # some code
end
</ruby>
-And +default_options+ like this:
+These methods can be used to silence STDERR responses and the +silence_stream+ allows you to also silence other streams. Additionally, this mixin allows you to suppress exceptions and capture streams. For more information see the "Silencing Warnings, Streams, and Exceptions":http://guides.rubyonrails.org/active_support_core_extensions.html#silencing-warnings-streams-and-exceptions section from the Active Support Core Extensions Guide.
-<ruby>
- def default_options
- {
- :environment => "development",
- :pid => nil,
- :Port => 9292,
- :Host => "0.0.0.0",
- :AccessLog => [],
- :config => "config.ru"
- }
- end
-</ruby>
+h4. +active_support/core_ext/logger.rb+
-Here it is important to note that the default environment is _development_. After +Rack::Server#initialize+ has done its thing it returns to +Rails::Server#initialize+ which calls +set_environment+:
+The next file that is required is another Active Support core extension, this time to the +Logger+ class. This begins by defining the +around_[level]+ helpers for the +Logger+ class as well as other methods such as a +datetime_format+ getter and setter for the +formatter+ object tied to a +Logger+ object.
-<ruby>
- def set_environment
- ENV["RAILS_ENV"] ||= options[:environment]
- end
-</ruby>
+For more information see the "Extensions to Logger":http://guides.rubyonrails.org/active_support_core_extensions.html#extensions-to-logger section from the Active Support Core Extensions Guide.
-From the information given we can determine that +ENV["RAILS_ENV"]+ will be set to _development_ if no other environment is specified.
+h4. +railties/lib/rails/application.rb+
-Finally, after +Rails::Server.new+ has executed, there is one more require:
+The next file required by +railties/lib/rails.rb+ is +application.rb+. This file defines the +Rails::Application+ constant which the application's class defined in +config/application.rb+ in a standard Rails application depends on. Before the +Rails::Application+ class is defined however, there's some other files that get required first.
-<ruby>
- require APP_PATH
-</ruby>
+The first of these is +active_support/core_ext/hash/reverse_merge+ which can be "read about in the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#merging under the "Merging" section.
-+APP_PATH+ was previously defined as _config/application.rb_ in the application's root, and so that is where Rails will go next.
+h4. +active_support/file_update_checker.rb+
-h4. +require APP_PATH+
+The +ActiveSupport::FileUpdateChecker+ class defined within this file is responsible for checking if a file has been updated since it was last checked. This is used for monitoring the routes file for changes during development environment runs.
-This file is _config/application.rb_ in your application and makes two requires to begin with:
+h4. +railties/lib/rails/plugin.rb+
-<ruby>
- require File.expand_path('../boot', __FILE__)
- require 'rails/all'
-</ruby>
+This file defines +Rails::Plugin+ which inherits from +Rails::Engine+. Unlike +Rails::Engine+ and +Rails::Railtie+ however, this class is not designed to be inherited from. Instead, this is used simply for loading plugins from within an application and an engine.
-The +../boot+ file it references is +config/boot.rb+, which was loaded earlier in the initialization process and so will not be loaded again.
+This file begins by requiring +rails/engine.rb+
-If you generate the application with the +-O+ option this will put a couple of pick-and-choose requirements at the top of your _config/application.rb_ instead:
+h4. +railties/lib/rails/engine.rb+
-<ruby>
- # Pick the frameworks you want:
- # require "active_record/railtie"
- require "action_controller/railtie"
- require "action_mailer/railtie"
- require "active_resource/railtie"
- require "rails/test_unit/railtie"
-</ruby>
+The +rails/engine.rb+ file defines the +Rails::Engine+ class which inherits from +Rails::Railtie+. The +Rails::Engine+ class defines much of the functionality found within a standard application class such as the +routes+ and +config+ methods.
-For the purposes of this guide, will will assume only:
+The "API documentation":http://api.rubyonrails.org/classes/Rails/Engine.html for +Rails::Engine+ explains the function of this class pretty well.
-<ruby>
- require 'rails/all'
-</ruby>
+This file's first line requires +rails/railtie.rb+.
-h4. +require "rails/all"+
+h4. +railties/lib/rails/railtie.rb+
-Now we'll dive into the internals of the pre-initialization stage of Rails. The file that is being required is _railties/lib/rails/all.rb_. The first line in this file is:
+The +rails/railtie.rb+ file is responsible for defining +Rails::Railtie+, the underlying class for all ties to Rails now. Gems that want to have their own initializers or rake tasks and hook into Rails should have a +GemName::Railtie+ class that inherits from +Rails::Railtie+.
-<ruby>
- require 'rails'
-</ruby>
+The "API documentation":http://api.rubyonrails.org/classes/Rails/Railtie.html for +Rails::Railtie+, much like +Rails::Engine+, explains this class exceptionally well.
-h4. +require 'rails'+
+The first require in this file is +rails/initializable.rb+.
-This file (_railties/lib/rails.rb_) requires the very, very basics that Rails needs to get going. I'm not going to delve into these areas yet, just cover them briefly for now. Later on we will go through the ones that are important to the boot procedure.
+h4. +railties/lib/rails/initializable.rb+
-<ruby>
- require 'pathname'
+Now we reach the end of this particular rabbit hole as +rails/initializable.rb+ doesn't require any more Rails files, only +tsort+ from the Ruby standard library.
- require 'active_support'
- require 'active_support/core_ext/kernel/reporting'
- require 'active_support/core_ext/logger'
+This file defines the +Rails::Initializable+ module which contains the +Initializer+ class, the basis for all initializers in Rails. This module also contains a +ClassMethods+ class which will be included into the +Rails::Railtie+ class when these requires have finished.
- require 'rails/application'
- require 'rails/version'
- require 'rails/deprecation'
- require 'rails/log_subscriber'
- require 'rails/ruby_version_check'
+Now that +rails/initializable.rb+ has finished being required from +rails/railtie.rb+, the next require is for +rails/configuration+.
- require 'active_support/railtie'
- require 'action_dispatch/railtie'
-</ruby>
+h4. +railties/lib/rails/configuration.rb+
-+require 'pathname'+ requires the Pathname class which is used for returning a Pathname object for +Rails.root+. Although is coming to use this path name to generate paths as below:
+This file defines the +Rails::Configuration+ module, containing the +MiddlewareStackProxy+ class as well as the +Generators+ class. The +MiddlewareStackProxy+ class is used for managing the middleware stack for an application, which we'll see later on. The +Generators+ class provides the functionality used for configuring what generators an application uses through the "+config.generators+ option":http://guides.rubyonrails.org/configuring.html#configuring-generators.
-<ruby>
- Rails.root.join("app/controllers")
-</ruby>
+The first file required in this file is +activesupport/deprecation+.
-Pathname can also be converted to string, so the following syntax is preferred:
+h4. +activesupport/lib/active_support/deprecation.rb+
-<ruby>
- "#{Rails.root}/app/controllers"
-</ruby>
-
-
-This works because Ruby automatically handles file path conversions. Although this is not new to Rails 3 (it was available in 2.3.5), it is something worthwhile pointing out.
+This file, and the files it requires, define the basic deprecation warning features found in Rails. This file is responsible for setting defaults in the +ActiveSupport::Deprecation+ module for the +deprecation_horizon+, +silenced+ and +debug+ values. The files that are required before this happens are:
-Inside this file there are other helpful helper methods defined, such as +Rails.root+, +Rails.env+, +Rails.logger+ and +Rails.application+.
+* +active_support/deprecation/behaviors+
+* +active_support/deprecation/reporting+
+* +active_support/deprecation/method_wrappers+
+* +active_support/deprecation/proxy_wrappers+
-The first require:
+h4. +activesupport/lib/active_support/deprecation/behaviors.rb+
-<ruby>
- require 'active_support'
-</ruby>
+This file defines the behavior of the +ActiveSupport::Deprecation+ module, setting up the +DEFAULT_BEHAVIORS+ hash constant which contains the three defaults to outputting deprecation warnings: +:stderr+, +:log+ and +:notify+. This file begins by requiring +activesupport/notifications+ and +activesupport/core_ext/array/wrap+.
-Is not ran as this was already required by _actionpack/lib/action_dispatch.rb_.
+h4 +activesupport/lib/active_support/notifications.rb+
+TODO: document +ActiveSupport::Notifications+.
-h4. +require 'active_support/core_ext/kernel/reporting'+
+h4. +activesupport/core_ext/array/wrap+
-This file extends the +Kernel+ module, providing the methods +silence_warnings+, +enable_warnings+, +with_warnings+, +silence_stderr+, +silence_stream+ and +suppress+. The API documentation on these overridden methods is fairly good and if you wish to know more "have a read.":http://api.rubyonrails.org/classes/Kernel.html
-
-For information on this file see the "Core Extensions" guide. TODO: link to guide.
-
-h4. +require 'active_support/core_ext/logger'+
-
-For information on this file see the "Core Extensions" guide. TODO: link to guide.
-
-h4. +require 'rails/application'+
-
-Here's where +Rails::Application+ is defined. This is the superclass of +YourApp::Application+ from _config/application.rb_ and the subclass of +Rails::Engine+ This is the main entry-point into the Rails initialization process as when your application is initialized, your class is the basis of its configuration.
-
-This file requires three important files before +Rails::Application+ is defined: _rails/railties_path.rb_, _rails/plugin.rb_ and _rails/engine.rb_.
-
-
-h4. +require 'rails/railties_path'+
-
-This file serves one purpose:
-
-<ruby>
- RAILTIES_PATH = File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
-</ruby>
+As this file comprises of a core extension, it is covered exclusively in "the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#wrapping
-Helpful, hey? One must wonder why they just didn't define it outright.
+h4. +activesupport/lib/active_support/deprecation/reporting.rb+
+This file is responsible for defining the +warn+ and +silence+ methods for +ActiveSupport::Deprecation+ as well as additional private methods for this module.
-h4. +require 'rails/plugin'+
+h4. +activesupport/lib/active_support/deprecation/method_wrappers.rb+
-Firstly this file requires _rails/engine.rb_, which defines our +Rails::Engine+ class, explained in the very next section.
+This file defines a +deprecate_methods+ which is primarily used by the +module/deprecation+ core extension required by the first line of this file. Other core extensions required by this file are the +module/aliasing+ and +array/extract_options+ files.
-This file defines a class called +Rails::Plugin+ which descends from +Rails::Engine+.
+h4. +activesupport/lib/active_support/deprecation/proxy_wrappers.rb+
-This defines the first few initializers for the Rails stack:
-
-* load_init_rb
-* sanity_check_railties_collisons
-
-These are explained in the Initialization section. TODO: First write initialization section then come back here and link.
-TODO: Expand.
-
-h4. +require 'rails/engine'+
-
-This file requires _rails/railtie.rb_ which defines +Rails::Railtie+.
-
-+Rails::Engine+ defines a couple of further initializers for your application:
-
-* set_load_path
-* set_autoload_paths
-* add_routing_paths
-* add_routing_namespaces
-* add_locales
-* add_view_paths
-* add_generator_templates
-* load_application_initializers
-* load_application_classes
-
-These are explained in the Initialization section. TODO: First write initialization section then come back here and link.
-
-Also in here we see that a couple of methods are +delegate+'d:
-
-<ruby>
- delegate :middleware, :paths, :root, :to => :config
-</ruby>
-
-This means when you call either the +middleware+, +paths+ or +root+ methods you are in reality calling +config.middleware+, +config.paths+ and +config.root+ respectively.
-
-+Rails::Engine+ descends from +Rails::Railtie+.
-
-h4. +require 'rails/railtie'+
-
-+Rails::Railtie+ (_pronounced Rail-tie, as in a bowtie_), provides a method of classes to hook into Rails, providing them with methods to add generators, rake tasks and subscribers. All of the facets of Rails are their own Railtie. and as you've probably already figured out, the engines that you use are railties too. Plugins also can be railties, but they do not have to be.
-
-Here there's requires to _rails/initializable.rb_ and and _rails/configurable.rb_.
-
-h4. +require 'rails/initializable'+
-
-The +Rails::Initializable+ module includes methods helpful for the initialization process in rails, such as the method to define initializers: +initializer+. This is included into +Rails::Railtie+ so it's available there as well as +Rails::Engine+, +Rails::Application+ and +YourApp::Application+. In here we also see the class definition for +Rails::Initializer+, the class for all initializer objects.
-
-h4. +require 'rails/configuration'+
-
-The +Rails::Configuration+ module sets up shared configuration for applications, engines and plugins alike.
-
-At the top of this file there are three +require+s:
-
-<ruby>
- require 'active_support/ordered_options'
- require 'rails/paths'
- require 'rails/rack'
-</ruby>
++proxy_wrappers.rb+ defines deprecation wrappers for methods, instance variables and constants. Previously, this was used for the +RAILS_ENV+ and +RAILS_ROOT+ constants for 3.0 but since then these constants have been removed. The deprecation message that would be raised from these would be something like:
-h4. +require 'active_support/ordered_options'+
+<plain>
+ BadConstant is deprecated! Use GoodConstant instead.
+</plain>
-+ActiveSupport::OrderedOptions+ is a special-purpose +OrderedHash+, used for keeping track of the options specified in the configuration of your application.
+h4. +active_support/ordered_options+
-TODO: expand.
+This file is the next file required from +rails/configuration.rb+ is the file that defines +ActiveSupport::OrderedOptions+ which is used for configuration options such as +config.active_support+ and the like.
-h4. +require 'rails/paths'+
+The next file required is +active_support/core_ext/hash/deep_dup+ which is covered in "Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#deep_dup
-This file is used to set up the +Rails::Paths+ module which is used to set up helpers for referencing paths to the folders of your Rails application, such as in _railties/lib/rails/engine/configuration.rb_ where it is used to firstly define them:
+The file that is required next from is +rails/paths+
-<ruby>
- def paths
- @paths ||= begin
- paths = Rails::Paths::Root.new(@root)
- paths.app "app", :eager_load => true, :glob => "*"
- paths.app.controllers "app/controllers", :eager_load => true
- paths.app.helpers "app/helpers", :eager_load => true
- paths.app.models "app/models", :eager_load => true
- paths.app.mailers "app/mailers", :eager_load => true
- paths.app.views "app/views", :eager_load => true
- paths.lib "lib", :load_path => true
- paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
- paths.lib.templates "lib/templates"
- paths.config "config"
- paths.config.initializers "config/initializers", :glob => "**/*.rb"
- paths.config.locales "config/locales", :glob => "*.{rb,yml}"
- paths.config.routes "config/routes.rb"
- paths.public "public"
- paths.public.javascripts "public/javascripts"
- paths.public.stylesheets "public/stylesheets"
- paths
- end
- end
-</ruby>
+h4. +railties/lib/rails/paths.rb+
-You can then get to these helper methods by calling +YourApp::Application.config.paths+.
+This file defines the +Rails::Paths+ module which allows paths to be configured for a Rails application or engine. Later on in this guide when we cover Rails configuration during the initialization process we'll see this used to set up some default paths for Rails and some of them will be configured to be eager loaded.
-h4. +require 'rails/rack'+
+h4. +railties/lib/rails/rack.rb+
-This file sets up some +autoload+'d constants for +Rails::Rack+:
+The final file to be loaded by +railties/lib/rails/configuration.rb+ is +rails/rack+ which defines some simple autoloads:
<ruby>
module Rails
@@ -1006,1456 +642,122 @@ This file sets up some +autoload+'d constants for +Rails::Rack+:
end
</ruby>
-h4. +require 'rails/version'+
-
-Now we're back to _rails.rb_. The line after +require 'rails/application'+ in _rails.rb_ is:
-
-<ruby>
- require 'rails/version'
-</ruby>
-
-The code in this file declares +Rails::VERSION+ so that the version number can easily be accessed. It stores it in constants, with the final version number being attainable by calling +Rails::VERSION::STRING+.
-
-h4. +require 'rails/deprecation'+
-
-This sets up a couple of familiar constants: +RAILS_ENV+, +RAILS_ROOT+ and +RAILS_DEFAULT_LOGGER+ to still be usable, but raise a deprecation warning when they are. Their alternatives are now +Rails.env+, +Rails.root+ and +Rails.logger+ respectively.
-
-If you wish to know more about how they're deprecated see the +require 'active_support/deprecation/proxy_wrappers'+ section. TODO: link to section.
-
-h4. +require 'rails/log_subscriber'+
-
-The +Rails::LogSubscriber+ provides a central location for logging in Rails 3 so as to not slow down the main thread. When you call one of the logging methods (+info+, +debug+, +warn+, +error+, +fatal+ or +unknown+) from the +Rails::LogSubscriber+ class or one of its subclasses this will notify the Rails logger to log this call in the fashion you specify, but will not write it to the file. The file writing is done at the end of the request, courtesy of the +Rails::Rack::Logger+ middleware.
-
-Each Railtie defines its own class that descends from +Rails::LogSubscriber+ with each defining its own methods for logging individual tasks.
-
-h4. +require 'rails/ruby_version_check'+
-
-This file ensures that you're running a minimum of 1.8.7. If you're running an older version, it will tell you:
-
-<pre>
- Rails requires Ruby version 1.8.7 or later.
- You're running [your Ruby version here]; please upgrade to continue.
-</pre>
-
-h4. +require 'activesupport/railtie'+
-
-This file declares two Railties, one for ActiveSupport and the other for I18n. In these Railties there's the following initializers defined:
-
-* active_support.initialize_whiny_nils
-* active_support.initialize_time_zone
-
-* i18n.initialize
-
-This Railtie also defines an an +after_initialize+ block, which will (as the name implies) be ran after the initialization process. More on this later. TODO: When you write the section you can link to it.
-
-h4. +require 'action_dispatch/railtie'+
-
-This file is explained in the ActionDispatch Railtie Section. TODO: link
-
-h4. Return to _rails/all.rb_
-
-Now that we've covered the extensive process of what the first line does in this file, lets cover the remainder:
-
-<ruby>
- %w(
- active_record
- action_controller
- action_mailer
- active_resource
- rails/test_unit
- ).each do |framework|
- begin
- require "#{framework}/railtie"
- rescue LoadError
- end
- end
-</ruby>
-
-As you may be able to tell from the code, this is going through and loading all the Railties for Active Record, Action Controller, Action Mailer, Active Resource. Two other Railties, one for Active Support and one for Action Dispatch were required earlier, but are still covered in this section for continuity reasons. TODO: link.
-
-h4. ActiveSupport Railtie
-
-From Active Support's README:
-
-Active Support is a collection of various utility classes and standard library extensions that were found useful for Rails.
-
-TODO: Quotify.
-
-h5. +require 'active_support/railtie'+
-
-
-h4. Active Record Railtie
-
-The Active Record Railtie takes care of hooking Active Record into Rails. This depends on Active Support, Active Model and Arel. From Active Record's readme:
-
-TODO: Quotify.
-
-<plain>
- Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It's an implementation of the object-relational mapping (ORM) pattern by the same name as described by Martin Fowler:
-
- "An object that wraps a row in a database table or view, encapsulates
- the database access, and adds domain logic on that data."
-
- Active Record's main contribution to the pattern is to relieve the original of two stunting problems:
- lack of associations and inheritance. By adding a simple domain language-like set of macros to describe
- the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the
- gap of functionality between the data mapper and active record approach.
-</plain>
-
-h5. +require "active_record/railtie"+
-
-The _activerecord/lib/active_record/railtie.rb_ file defines the Railtie for Active Record.
-
-This file first requires Active Record, the _railties/lib/rails.rb_ file which has already been required and so will be ignored, and the Active Model Railtie:
-
-<ruby>
- require "active_record"
- require "rails"
- require "active_model/railtie"
-</ruby>
-
-Active Model's Railtie is covered in the next section. TODO: Section.
-
-h5. +require "active_record"+
-
-TODO: Why are +activesupport_path+ and +activemodel_path+ defined here?
-
-The first three requires require ActiveSupport, Active Model and Arel in that order:
-
-<ruby>
- require 'active_support'
- require 'active_model'
- require 'arel'
-</ruby>
-
-
-h5. +require "active_support"+
-
-This was loaded earlier by _railties/lib/rails.rb_. This line is here as a safeguard for when Active Record is loaded outside the scope of Rails.
-
-h5. +require "active_model"+
-
-TODO: Again with the +activesupport_path+!
-
-Here we see another +require "active_support"+ this is again, a safeguard for when Active Model is loaded outside the scope of Rails.
-
-This file defines a few +autoload+'d modules for Active Model, requires +active_support/i18n+ and adds the default translation file for Active Model to +I18n.load_path+.
-
-The +require 'active_support/i18n'+ just loads I18n and adds Active Support's default translations file to +I18n.load_path+ too:
-
-<ruby>
- require 'i18n'
- I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml
-</ruby>
-
-
-h5. +require "arel"+
-
-This file in _arel/lib/arel.rb_ loads a couple of Active Support things first:
-
-<ruby>
- require 'active_support/inflector'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/class/attribute_accessors'
-</ruby>
-
-These files are explained in the "Common Includes" section.
-
-h5. +require 'arel'+
-
-Back in _arel/lib/arel.rb_, the next two lines require Active Record parts:
-
-<ruby>
- require 'active_record'
- require 'active_record/connection_adapters/abstract/quoting'
-</ruby>
-
-Because we're currently loading _active_record.rb_, it skips right over it.
-
-h5. +require 'active_record/connection_adapters/abstract/quoting'+
-
-_activerecord/lib/active_record/connection_adapters/abstract/quoting.rb_ defines methods used for quoting fields and table names in Active Record.
-
-TODO: Explain why this is loaded especially.
-
-h5. +require 'active_record'+
-
-Back the initial require from the _railtie.rb_.
-
-The _active_support_ and _active_model_ requires are again just an insurance for if we're loading Active Record outside of the scope of Rails. In _active_record.rb_ the ActiveRecord +Module+ is initialized and in it there is defined a couple of +autoloads+ and +eager_autoloads+.
-
-There's a new method here called +autoload_under+ which is defined in +ActiveSupport::Autoload+. This sets the autoload path to temporarily be the specified path, in this case +relation+ for the +autoload+'d classes inside the block.
-
-Inside this file the +AttributeMethods+, +Locking+ and +ConnectionAdapter+ modules are defined inside the +ActiveRecord+ module. The second to last line tells Arel what SQL engine we want to use. In this case it's +ActiveRecord::Base+. The final line adds in the translations for Active Record which are only for if a record is invalid or non-unique.
-
-h5. +require 'rails'+
-
-As mentioned previously this is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section.
-
-h5. +require 'active_model/railtie'+
-
-This is covered in the Active Model Railtie section. TODO: link there.
-
-h5. +require 'action_controller/railtie'+
-
-This is covered in the Action Controller Railtie section. TODO: link there.
-
-h5. The Active Record Railtie
-
-Inside the Active Record Railtie the +ActiveRecord::Railtie+ class is defined:
-
-<ruby>
- module ActiveRecord
- class Railtie < Rails::Railtie
-
- ...
- end
- end
-</ruby>
-
-TODO: Explain the logger.
-
-By doing this the +ActiveRecord::Railtie+ class gains access to the methods contained within +Rails::Railtie+ such as +rake_tasks+, +log_subscriber+ and +initiailizer+, all of which the Railtie is using in this case. The initializers defined here are:
-
-* active_record.initialize_timezone
-* active_record.logger
-* active_record.set_configs
-* active_record.initialize_database
-* active_record.log_runtime
-* active_record.initialize_database_middleware
-* active_record.load_observers
-* active_record.set_dispatch_hooks
-
-As with the engine initializers, these are explained later.
-
-
-h4. Active Model Railtie
-
-This Railtie is +require+'d by Active Record's Railtie.
-
-From the Active Model readme:
-
-<plain>
- Prior to Rails 3.0, if a plugin or gem developer wanted to be able to have an object interact with Action Pack helpers, it was required to either copy chunks of code from Rails, or monkey patch entire helpers to make them handle objects that did not look like Active Record. This generated code duplication and fragile applications that broke on upgrades.
-
- Active Model is a solution for this problem.
-
- Active Model provides a known set of interfaces that your objects can implement to then present a common interface to the Action Pack helpers.
-</plain>
-
-
-h5. +require "active_model/railtie"+
-
-This Railtie file, _activemodel/lib/active_model/railtie.rb_ is quite small and only requires in +active_model+. As mentioned previously, the require to _rails_ is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section.
-
-<ruby>
- require "active_model"
- require "rails"
-</ruby>
-
-h5. +require "active_model"+
-
-Active Model depends on Active Support and ensures it is required by making a +require 'active_support'+ call. It has already been loaded from _railties/lib/rails.rb_ so will not be reloaded for us here. The file goes on to define the +ActiveModel+ module and all of its autoloaded classes. This file also defines the english translations for some of the validation messages provided by Active Model, such as "is not included in the list" and "is reserved".
-
-h4. Action Controller Railtie
-
-The Action Controller Railtie takes care of all the behind-the-scenes code for your controllers; it puts the C into MVC; and does so by implementing the +ActionController::Base+ class which you may recall is where your +ApplicationController+ class descends from.
-
-h5. +require 'action_controller/railtie'+
-
-This first makes a couple of requires:
-
-<ruby>
- require "action_controller"
- require "rails"
- require "action_view/railtie"
-</ruby>
-
-The _action_controller_ file is explained in the very next section. The require to _rails_ is requiring the already-required _railties/lib/rails.rb_. If you wish to know about the require to _action_view/railtie_ this is explained in the Action View Railtie section.
-
-h5. +require 'action_controller+
-
-This file, _actionpack/lib/action_controller.rb_, defines the Action Controller module and its relative autoloads. Before it does any of that it makes two requires: one to _abstract_controller_, explored next, and the other to _action_dispatch_, explored directly after that.
-
-h5. +require 'abstract_controller'+
-
-+AbstractController+ provides the functionality of TODO.
-
-This file is in _actionpack/lib/abstract_controller.rb_ and begins by attempting to add the path to Active Support to the load path, which it would succeed in if it wasn't already set by anything loaded before it. In this case, it's not going to be set due to Arel already loading it in (TODO: right?).
-
-The next thing in this file four +require+ calls:
-
-<ruby>
- require 'active_support/ruby/shim'
- require 'active_support/dependencies/autoload'
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
-</ruby>
-
-After these require calls the +AbstractController+ module is defined with some standard +autoload+'d classes.
-
-
-h5. +require 'active_support/ruby/shim'+
-
-This file is explained in the "Common Includes" section beneath.
-
-h5. +require 'active_support/dependencies/autoload+
-
-This file was loaded upon the first require of +active_support+ and is not included. If you wish to be refreshed on what this file performs visit TODO: link to section.
-
-h5. +require 'active_support/core_ext/module/attr_internal'+
-
-This file is explained in the "Common Includes" section as it is required again later on. See the TODO: section. I also think this may be explained in the Active Support Core Extensions guide.
-
-h5. +require 'active_support/core_ext/module/delegation'+
-
-This file is explained in the "Common Includes" section as it has already been required by Arel at this point in the initialization process (see: section TODO: LINK!).
-
-h5. +require 'action_controller'+
-
-Back to _actionpack/lib/action_controller.rb_.
-
-After the initial call to +require 'abstract_controller'+, this calls +require 'action_dispatch'+ which was required earlier by _railties/lib/rails.rb_. The purpose of this file is explained in the ActionDispatch Railtie section.
-
-This file defines the +ActionController+ module and its autoloaded classes.
-
-Here we have a new method called +autoload_under+. This was covered in the Active Record Railtie but it is covered here also just in case you missed or skimmed over it. The +autoload_under+ method is defined in +ActiveSupport::Autoload+ and it sets the autoload path to temporarily be the specified path, in this case by specifying _metal_ it will load the specified +autoload+'d classes from _lib/action_controller/metal_ inside the block.
-
-Another new method we have here is called +autoload_at+:
-
-<ruby>
- autoload_at "action_controller/metal/exceptions" do
- autoload :ActionControllerError
- autoload :RenderError
- autoload :RoutingError
- autoload :MethodNotAllowed
- autoload :NotImplemented
- autoload :UnknownController
- autoload :MissingFile
- autoload :RenderError
- autoload :SessionOverflowError
- autoload :UnknownHttpMethod
- end
-</ruby>
-
-This defines the path of which to find these classes defined at and is most useful for if you have multiple classes defined in a single file, as is the case for this block; all of those classes are defined inside _action_controller/metal/exceptions.rb_ and when Active Support goes looking for them it will look in that file.
-
-At the end of this file there are a couple more requires:
-
-<ruby>
- # All of these simply register additional autoloads
- require 'action_view'
- require 'action_controller/vendor/html-scanner'
-
- # Common Active Support usage in ActionController
- require 'active_support/concern'
- require 'active_support/core_ext/class/attribute_accessors'
- require 'active_support/core_ext/load_error'
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/name_error'
- require 'active_support/inflector'
-</ruby>
-
-h5. +require 'action_view'+
-
-This is best covered in the Action View Railtie section, so skip there by TODO: Link / page?
-
-h5. +require 'action_controller/vendor/html-scanner'+
-
-TODO: What is the purpose of this? Find out.
-
-h5. +require 'active_support/concern'+
-
-TODO: I can kind of understand the purpose of this.. need to see where @_dependencies is used however.
-
-h5. +require 'active_support/core_ext/class/attribute_accessors'+
-
-This file defines, as the path implies, attribute accessors for class. These are +cattr_reader+, +cattr_writer+, +cattr_accessor+.
-
-h5. +require 'active_support/core_ext/load_error'+
-
-The Active Support Core Extensions (TODO: LINK!) guide has a great coverage of what this file precisely provides.
-
-h5. +require 'active_support/core_ext/module/attr_internal'+
-
-This file is explained in the "Core Extension" guide.
-
-This file was required through the earlier _abstract_controller.rb_ require.
-
-h5. +require 'active_support/core_ext/module/delegation'+
-
-This file is explained in the "Common Includes" section.
-
-This file was required earlier by Arel and so is not required again.
-
-h5. +require 'active_support/core_ext/name_error'+
-
-This file includes extensions to the +NameError+ class, providing the +missing_name+ and +missing_name?+ methods. For more information see the Active Support Core Extensions guide.
-
-h5. +require 'active_support/inflector'+
-
-This file is explained in the "Common Includes" section.
-
-This file was earlier required by Arel and so is not required again.
-
-h5. Action Controller Railtie
-
-So now we come back to the Action Controller Railtie with a couple more requires to go before +ActionController::Railtie+ is defined:
-
-<ruby>
- require "action_view/railtie"
- require "active_support/core_ext/class/subclasses"
- require "active_support/deprecation/proxy_wrappers"
- require "active_support/deprecation"
-</ruby>
-
-As explained previously the +action_view/railtie+ file will be explained in the Action View Railtie section. TODO: link to it.
-
-h5. +require 'active_support/core_ext/class/subclasses'+
-
-For an explanation of this file _activesupport/lib/active_support/core_ext/class/subclasses_, see the Active Support Core Extension guide.
-
-h5. +require 'active_support/deprecation/proxy_wrappers'+
-
-This file, _activesupport/lib/active_support/deprecation/proxy_wrappers.rb_, defines a couple of deprecation classes, which are +DeprecationProxy+, +DeprecationObjectProxy+, +DeprecationInstanceVariableProxy+, +DeprecationConstantProxy+ which are all namespaced into +ActiveSupport::Deprecation+. These last three are all subclasses of +DeprecationProxy+.
-
-Why do we mention them here? Beside the obvious-by-now fact that we're covering just about everything about the initialization process in this guide, if you're deprecating something in your library and you use Active Support, you too can use the +DeprecationProxy+ class (and it's subclasses) too.
-
-
-h6. +DeprecationProxy+
-
-This class is used only in _railties/lib/rails/deprecation.rb_, loaded further on in the initialization process. It's used in this way:
-
-<ruby>
- RAILS_ROOT = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do
- cattr_accessor :warned
- self.warned = false
-
- def target
- Rails.root
- end
-
- def replace(*args)
- warn(caller, :replace, *args)
- end
-
- def warn(callstack, called, args)
- unless warned
- ActiveSupport::Deprecation.warn("RAILS_ROOT is deprecated! Use Rails.root instead", callstack)
- self.warned = true
- end
- end
- end).new
-</ruby>
-
-There is similar definitions for the other constants of +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+. All three of these constants are in the midst of being deprecated (most likely in Rails 3.1) so Rails will tell you if you reference them that they're deprecated using the +DeprecationProxy+ class. Whenever you call +RAILS_ROOT+ this will raise a warning, telling you: "RAILS_ROOT is deprecated! Use Rails.root instead".... TODO: investigate if simply calling it does raise this warning. This same rule applies to +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+, their new alternatives are +Rails.env+ and +Rails.logger+ respectively.
-
-h6. +DeprecatedObjectProxy+
-
-This is used in one place _actionpack/lib/action_controller/railtie.rb_, which you may remember is how we got to the +DeprecationProxy+ section:
-
-<ruby>
- ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message)
-</ruby>
-
-This makes more sense in the wider scope of the initializer:
-
-<ruby>
- initializer "action_controller.url_helpers" do |app|
- ActionController.base_hook do
- extend ::ActionController::Railtie::UrlHelpers.with(app.routes)
- end
-
- message = "ActionController::Routing::Routes is deprecated. " \
- "Instead, use Rails.application.routes"
-
- proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message)
- ActionController::Routing::Routes = proxy
- end
-</ruby>
-
-+ActionController::Routing::Routes+ was the previous constant used in defining routes in Rails 2 applications, now it's simply a method on +Rails.application+ rather than it's own individual class: +Rails.application.routes+. Both of these still call the +draw+ method on the returned object to end up defining the routes.
-
-
-h6. +DeprecatedInstanceVariableProxy+
-
-This isn't actually used anywhere in Rails anymore. It was used previously for when +@request+ and +@params+ were deprecated in Rails 2. It has been kept around as it could be useful for the same purposes in libraries that use Active Support.
-
-h6. +DeprecatedConstantProxy+
-
-This method is used in a couple of places, _activesupport/lib/active_support/json/encoding.rb_ and _railties/lib/rails/rack.rb_.
-
-In _encoding.rb_ it's used to define a constant that's now been deprecated:
-
-<ruby>
- CircularReferenceError = Deprecation::DeprecatedConstantProxy.new('ActiveSupport::JSON::CircularReferenceError', Encoding::CircularReferenceError)
-</ruby>
-
-
-Now when you reference +ActiveSupport::JSON::CircularReferenceError+ you'll receive a warning:
-
-<plain>
- ActiveSupport::JSON::CircularReferenceError is deprecated! Use Encoding::CircularReferenceError instead.
-</plain>
-
-h5. +require "active_support/deprecation"+
-
-This re-opens the +ActiveSupport::Deprecation+ module which was already defined by our deprecation proxies. Before this happens however we have 4 requires:
-
-<ruby>
- require 'active_support/deprecation/behaviors'
- require 'active_support/deprecation/reporting'
- require 'active_support/deprecation/method_wrappers'
- require 'active_support/deprecation/proxy_wrappers'
-</ruby>
-
-The remainder of this file goes about setting up the +silenced+ and +debug+ accessors:
-
-<ruby>
- module ActiveSupport
- module Deprecation #:nodoc:
- class << self
- # The version the deprecated behavior will be removed, by default.
- attr_accessor :deprecation_horizon
- end
- self.deprecation_horizon = '3.0'
-
- # By default, warnings are not silenced and debugging is off.
- self.silenced = false
- self.debug = false
- end
- end
-</ruby>
-
-h5. +require "active_support/deprecation/behaviors"+
-
-This sets up some default behavior for the warnings raised by +ActiveSupport::Deprecation+, defining different ones for _development_ and _test_ and nothing for production, as we never want deprecation warnings in production:
-
-<ruby>
- # Default warning behaviors per Rails.env. Ignored in production.
- DEFAULT_BEHAVIORS = {
- 'test' => Proc.new { |message, callstack|
- $stderr.puts(message)
- $stderr.puts callstack.join("\n ") if debug
- },
- 'development' => Proc.new { |message, callstack|
- logger =
- if defined?(Rails) && Rails.logger
- Rails.logger
- else
- require 'logger'
- Logger.new($stderr)
- end
- logger.warn message
- logger.debug callstack.join("\n ") if debug
- }
- }
-</ruby>
-
-In the _test_ environment, we will see the deprecation errors displayed in +$stderr+ and in _development_ mode, these are sent to +Rails.logger+ if it exists, otherwise it is output to +$stderr+ in a very similar fashion to the _test_ environment. These are both defined as procs, so Active Support can pass arguments to the +call+ method we call on it when Active Support +warn+.
-
-h5. +require 'active_support/deprecation/reporting'+
-
-This file defines further extensions to the +ActiveSupport::Deprecation+ module, including the +warn+ method which is used from Active Support's +DeprecationProxy+ class and an +attr_accessor+ on the class called +silenced+. This checks that we have a behavior defined, which we do in the _test_ and _development_ environments, and that we're not +silenced+ before warning about deprecations by +call+'ing the +Proc+ time.
-
-This file also defines a +silence+ method on the module also which you can pass a block to temporarily silence errors:
-
-<ruby>
- ActiveSupport::Deprecation.silence do
- puts "YOU CAN FIND ME HERE: #{RAILS_ROOT}"
- end
-</ruby>
-
-TODO: may have to correct this example.
-
-h5. +require 'active_support/deprecation/method_wrappers'+
-
-This file defines a class method on +ActiveSupport::Deprecation+ called +deprecate_methods+. This method is used in _activesupport/lib/active_support/core_ext/module/deprecation.rb_ to allow you to declare deprecated methods on modules:
-
-<ruby>
- class Module
- # Declare that a method has been deprecated.
- # deprecate :foo
- # deprecate :bar => 'message'
- # deprecate :foo, :bar, :baz => 'warning!', :qux => 'gone!'
- def deprecate(*method_names)
- ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
- end
- end
-</ruby>
-
-h5. +require 'action_controller/railtie'+
-
-Inside +ActionController::Railtie+ there are another two requires:
-
-<ruby>
- require "action_controller/railties/log_subscriber"
- require "action_controller/railties/url_helpers"
-</ruby>
-
-
-h5. +require 'action_controller/railties/log_subscriber'+
-
-+ActionController::Railties::LogSubscriber+ inherits from +Rails::LogSubscriber+ and defines methods for logging such things as action processing and file sending.
-
-h5. +require 'action_controller/railties/url_helpers'+
-
-This file defines a +with+ method on +ActionController::Railtie::UrlHelpers+ which is later used in the +action_controller.url_helpers+ initializer. For more information see the +action_controller.url_helpers+ initializer section.
-
-h5. Action Controller Railtie
-
-After these requires it deprecates a couple of ex-Action Controller methods and points whomever references them to their ActionDispatch equivalents. These methods are +session+, +session=+, +session_store+ and +session_store=+.
-
-After the deprecations, Rails defines the +log_subscriber+ to be a new instance of +ActionController::Railties::LogSubscriber+ and then go about defining the following initializers, keeping in mind that these are added to the list of initializers defined before hand:
-
-* action_controller.logger
-* action_controller.set_configs
-* action_controller.initialize_framework_caches
-* action_controller.set_helpers_path
-* action_controller.url_helpers
-
-h4. Action View Railtie
-
-The Action View Railtie provides the backend code for your views and it puts the C into MVC. This implements the +ActionView::Base+ of which all views and partials are objects of.
-
-h5. +require 'action_view/railtie'+
-
-The Railtie is defined in a file called _actionpack/lib/action_view/railtie.rb_ and initially makes a call to +require 'action_view'+.
-
-h5. +require 'action_view'+
-
-Here again we have the addition of the path to Active Support to the load path attempted, but because it's already in the load path it will not be added. Similarly, we have two requires:
-
-<ruby>
- require 'active_support/ruby/shim'
- require 'active_support/core_ext/class/attribute_accessors'
-</ruby>
-
-And these have already been required. If you wish to know what these files do go to the explanation of each in the "Common Includes" section. TODO: link to them!
+Once this file is finished loading, then the +Rails::Configuration+ class is initialized. This completes the loading of +railties/lib/rails/configuration.rb+ and now we jump back to the loading of +railties/lib/rails/railtie.rb+, where the next file loaded is +active_support/inflector+.
-This file goes on to +require 'action_pack'+ which consists of all this code (comments stripped):
+h4. +activesupport/lib/active_support/inflector.rb+
-<ruby>
- require 'action_pack/version'
-</ruby>
-
-the _version_ file contains this code (comments stripped):
++active_support/inflector.rb+ requires a series of file which are responsible for setting up the basics for knowing how to pluralize and singularize words. These files are:
<ruby>
- module ActionPack #:nodoc:
- module VERSION #:nodoc:
- MAJOR = 3
- MINOR = 1
- TINY = 0
- BUILD = "beta"
-
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
- end
- end
-</ruby>
-
-TODO: Why?!
-
-This file goes on to define the +ActionView+ module and its +autoload+'d modules and then goes on to make two more requires:
-
-<ruby>
- require 'active_support/core_ext/string/output_safety'
- require 'action_view/base'
-</ruby>
-
-h5. +require 'active_support/core_ext/string/output_safety'+
-
-The _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ file is responsible for the code used in escaping HTML and JSON, namely the +html_escape+ and +json_escape+ methods. It does this by overriding these methods in +Erb::Util+ which is later included into +ActionView::Base+. This also defines +ActiveSupport::SafeBuffer+ which descends from +String+ and is used for concatenating safe output from your views to ERB templates.
-
-h5. +require 'action_view/base'+
-
-This file initially makes requires to the following files:
-
-<ruby>
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/class/attribute'
-</ruby>
-
-These are explained in their relevant areas inside the "Common Includes" section.
-
-The remainder of this file sets up the +ActionView+ module and the +ActionView::Base+ class which is the class of all view templates. Inside of +ActionView::Base+ it makes an include to several helper modules:
-
-<ruby>
- include Helpers, Rendering, Partials, Layouts, ::ERB::Util, Context
-</ruby>
-
-h5. +ActionView::Helpers+
-
-This module, from _actionpack/lib/action_view/helpers.rb_, initially sets up the +autoload+'s for the various +ActionView::Helpers+ modules (TODO: mysteriously not using +autoload_under+). This also sets up a +ClassMethods+ module which is included automatically into wherever +ActionView::Helpers+ is included by defining a +self.included+ method:
-
-<ruby>
- def self.included(base)
- base.extend(ClassMethods)
- end
-
- module ClassMethods
- include SanitizeHelper::ClassMethods
- end
-</ruby>
-
-Inside of +SanitizeHelper::ClassMethods+ it defines, of course, methods for assisting with sanitizing in Rails such as +link_sanitizer+ which is used by the +strip_links+ method.
-
-Afterwards this includes the +ActiveSupport::Benchmarkable+ which is used for benchmarking how long a specific thing takes in a view. The method is simply +benchmark+ and can be used like this:
-
-<ruby>
- benchmark("potentially long running thing") do
- Post.count
- end
-</ruby>
-
-The "documentation":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html is great about explaining what precisely this does.
-
-This module is also included into Active Record and +AbstractController+, meaning you can also use the +benchmark+ method in these methods.
-
-After including +ActiveSupport::Benchmarkable+, the helpers which we have declared to be +autoload+'d are included. I will not go through and cover what each of these helpers do, as their names should be fairly explicit about it, and it's not really within the scope of this guide.
-
-h5. +ActionView::Rendering+
-
-This module, from _actionpack/lib/action_view/render/rendering.rb_ defines a method you may be a little too familiar with: +render+. This is the +render+ use for rendering all kinds of things, such as partials, templates and text.
-
-h5. +ActionView::Partials+
-
-This module, from _actionpack/lib/action_view/render/partials.rb_, defines +ActionView::Partials::PartialRenderer+ which you can probably guess is used for rendering partials.
-
-h5. +ActionView::Layouts+
-
-This module, from _actionpack/lib/action_view/render/layouts.rb_, defines +ActionView::Layouts+ which defines methods such as +find_layout+ for locating layouts.
-
-h5. +ERB::Util+
-
-The +ERB::Util+ module from Ruby core, as the document describes it: "A utility module for conversion routines, often handy in HTML generation". It offers two methods +html_escape+ and +url_encode+, with a third called +json_escape+ being added in by the requirement of _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ earlier. As explained earlier, +html_escape+ is overridden to return a string marked as safe.
-
-h5. +ActionView::Context+
-
-TODO: Not entirely sure what this is all about. Something about the context of view rendering... can't work it out.
-
-h5. Action View Railtie
-
-Now that _actionpack/lib/action_view.rb_ has been required, the next step is to +require 'rails'+, but this will be skipped as the file was required by _railties/lib/rails/all.rb_ way back in the beginnings of the initialization process.
-
-Next, the Railtie itself is defined:
-
-
-<ruby>
- module ActionView
- class Railtie < Rails::Railtie
- railtie_name :action_view
-
- require "action_view/railties/log_subscriber"
- log_subscriber ActionView::Railties::LogSubscriber.new
-
- initializer "action_view.cache_asset_id" do |app|
- unless app.config.cache_classes
- ActiveSupport.on_load(:action_view) do
- ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false
- end
- end
- end
- end
- end
-</ruby>
-
-The +ActionView::LogSubscriber+ sets up a method called +render_template+ which is called when a template is rendered. TODO: Templates only or partials and layouts also? I would imagine these fall under the templates category, but there needs to research to ensure this is correct.
-
-The sole initializer defined here, _action_view.cache_asset_ids_ is responsible for caching the timestamps on the ends of your assets. If you've ever seen a link generated by +image_tag+ or +stylesheet_link_tag+ you would know that I mean that this timestamp is the number after the _?_ in this example: _/javascripts/prototype.js?1265442620_. This initializer will do nothing if +cache_classes+ is set to false in any of your application's configuration. TODO: Elaborate.
-
-h4. Action Mailer Railtie
-
-The Action Mailer Railtie is responsible for including all the emailing functionality into Rails by way of the Action Mailer gem itself. Action Mailer is:
-
-Action Mailer is a framework for designing email-service layers. These layers
-are used to consolidate code for sending out forgotten passwords, welcome
-wishes on signup, invoices for billing, and any other use case that requires
-a written notification to either a person or another system.
-
-Action Mailer is in essence a wrapper around Action Controller and the
-Mail gem. It provides a way to make emails using templates in the same
-way that Action Controller renders views using templates.
-
-TODO: Quotify.
-
-h5. +require 'action_mailer/railtie'+
-
-This file first makes two requires:
-
-<ruby>
- require "action_mailer"
- require "rails"
-</ruby>
-
-The requires in +action_mailer+ are already loaded or are core extensions:
+ require 'active_support/inflector/inflections'
+ require 'active_support/inflector/transliterate'
+ require 'active_support/inflector/methods'
-<ruby>
- require 'abstract_controller'
- require 'action_view'
-
- # Common Active Support usage in Action Mailer
- require 'active_support/core_ext/class'
- require 'active_support/core_ext/object/blank'
- require 'active_support/core_ext/array/uniq_by'
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
+ require 'active_support/inflections'
require 'active_support/core_ext/string/inflections'
- require 'active_support/lazy_load_hooks'
</ruby>
-_abstract_controller_ is covered in the "Action Controller Railtie" section. TODO: Cover AbstractController there and link to it.
-_action_view_ was required by the Action View Railtie and will not be required again.
-
-For the core extensions you may reference the "Core Extensions" guide. TODO: Link to guide.
+The +active_support/inflector/methods+ file has already been required by +active_support/autoload+ and so won't be loaded again here.
-_active_support/lazy_load_hooks_ was covered earlier in the guide and since it has already been required at this point in the initialization process, it will not be required again.
+h4. +activesupport/lib/active_support/inflector/inflections.rb+
-The +require "rails"+ is referencing the _railties/lib/rails.rb_ file which was included back in TODO: link to section.
-
-_actionmailer/lib/action_mailer.rb_ then goes on to define the +ActionMailer+ module:
-
-<ruby>
- module ActionMailer
- extend ::ActiveSupport::Autoload
-
- autoload :AdvAttrAccessor
- autoload :Collector
- autoload :Base
- autoload :DeliveryMethods
- autoload :DeprecatedApi
- autoload :MailHelper
- autoload :OldApi
- autoload :Quoting
- autoload :TestCase
- autoload :TestHelper
- end
-</ruby>
+This file references the +ActiveSupport::Inflector+ constant which isn't loaded by this point. But there were autoloads set up in +activesupport/lib/active_support.rb+ which will load the file which loads this constant and so then it will be defined. Then this file defines pluralization and singularization rules for words in Rails. This is how Rails knows how to pluralize "tomato" to "tomatoes".
-And a +Text+ module too:
+h4. +activesupport/lib/active_support/inflector/transliterate.rb+
-<ruby>
- module Text
- extend ActiveSupport::Autoload
+In this file is where the "+transliterate+":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate and +parameterize+:http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize methods are defined. The documentation for both of these methods is very much worth reading.
- autoload :Format, 'text/format'
- end
-</ruby>
+h4. Back to +railties/lib/rails/railtie.rb+
-which is used by the +ActionMailer::MailerHelper+ method +block_format+:
+Once the inflector files have been loaded, the +Rails::Railtie+ class is defined. This class includes a module called +Initializable+, which is actually +Rails::Initializable+. This module includes the +initializer+ method which is used later on for setting up initializers, amongst other methods.
-<ruby>
- def block_format(text)
- formatted = text.split(/\n\r\n/).collect { |paragraph|
- Text::Format.new(
- :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
- ).format
- }.join("\n")
-
- # Make list points stand on their own line
- formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
- formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
-
- formatted
- end
-</ruby>
+h4. +railties/lib/rails/initializable.rb+
-h5. Action Mailer Railtie
+When the module from this file (+Rails::Initializable+) is included, it extends the class it's included into with the +ClassMethods+ module inside of it. This module defines the +initializer+ method which is used to define initializers throughout all of the railties. This file completes the loading of +railties/lib/rails/railtie.rb+. Now we go back to +rails/engine.rb+.
-The Railtie defines the +log_subscriber+ as +ActionMailer::Railties::LogSubscriber.new+, with this class having two logging methods: one for delivery called +deliver+ and one for receipt called +receive+.
+h4. +railties/lib/rails/engine.rb+
-The initializers defined in this Railtie are:
+The next file required in +rails/engine.rb+ is +active_support/core_ext/module/delegation+ which is documented in the "Active Support Core Extensions Guide":http://guides.rubyonrails.org/active_support_core_extensions.html#method-delegation.
-* action_mailer.url_for
-* action_mailer.logger
-* action_mailer.set_configs
+The next two files after this are Ruby standard library files: +pathname+ and +rbconfig+. The file after these is +rails/engine/railties+.
-These are covered later on the Initialization section. TODO: first write then link to Initialization section.
+h4. +railties/lib/rails/engine/railties.rb+
-h4. Active Resource Railtie
+This file defines the +Rails::Engine::Railties+ class which provides the +engines+ and +railties+ methods which are used later on for defining rake tasks and other functionality for engines and railties.
-The Active Resource Railtie is responsible for creating an interface into remote sites that offer a REST API. The Active Resource Railtie depends on Active Support and Active Model.
+h4. Back to +railties/lib/rails/engine.rb+
-h5. +require 'active_resource/railtie'+
+Once +rails/engine/railties.rb+ has finished loading the +Rails::Engine+ class gets its basic functionality defined, such as the +inherited+ method which will be called when this class is inherited from.
-This file defines the Active Resource Railtie:
+Once this file has finished loading we jump back to +railties/lib/rails/plugin.rb+
-<ruby>
- require "active_resource"
- require "rails"
+h4. Back to +railties/lib/rails/plugin.rb+
- module ActiveResource
- class Railtie < Rails::Railtie
- railtie_name :active_resource
+The next file required in this is a core extension from Active Support called +array/conversions+ which is covered in "this section":http://guides.rubyonrails.org/active_support_core_extensions.html#array-conversions of the Active Support Core Extensions Guide.
- require "active_resource/railties/log_subscriber"
- log_subscriber ActiveResource::Railties::LogSubscriber.new
+Once that file has finished loading, the +Rails::Plugin+ class is defined.
- initializer "active_resource.set_configs" do |app|
- app.config.active_resource.each do |k,v|
- ActiveResource::Base.send "#{k}=", v
- end
- end
- end
- end
-</ruby>
+h4. Back to +railties/lib/rails/application.rb+
-The +require 'rails'+ has already been done back in TODO: link to section.
+Jumping back to +rails/application.rb+ now. This file defines the +Rails::Application+ class where the application's class inherits from. This class (and its superclasses) define the basic behaviour on the application's constant such as the +config+ method used for configuring the application.
-h5. +require 'active_resource'+
+Once this file's done then we go back to the +railties/lib/rails.rb+ file, which next requires +rails/version+.
-This file, _activeresource/lib/active_resource.rb_, defines the +ActiveResource+ module, first off this will add the path to Active Support and Active Model to the load path if it's not already there, then require both +active_support+ (_activesupport/lib/active_support.rb_) and +active_model+ (_activemodel/lib/active_model.rb_)
+h4. +railties/lib/rails/version.rb+
-<ruby>
- activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
- $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
+Much like +active_support/version+, this file defines the +VERSION+ constant which has a +STRING+ constant on it which returns the current version of Rails.
- activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
- $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
+Once this file has finished loading we go back to +railties/lib/rails.rb+ which then requires +active_support/railtie.rb+.
- require 'active_support'
- require 'active_model'
+h4. +activesupport/lib/active_support/railtie.rb+
- module ActiveResource
- extend ActiveSupport::Autoload
-
- autoload :Base
- autoload :Connection
- autoload :CustomMethods
- autoload :Formats
- autoload :HttpMock
- autoload :Observing
- autoload :Schema
- autoload :Validations
- end
-</ruby>
+This file requires +active_support+ and +rails+ which have already been required so these two lines are effectively ignored. The third require in this file is to +active_support/i18n_railtie.rb+.
-h5. Active Resource Railtie
+h4. +activesupport/lib/active_support/i18n_railtie.rb+
-The Railtie itself is fairly short as Active Resource is the smallest component of Rails.
+This file is the first file that sets up configuration with these lines inside the class:
<ruby>
- module ActiveResource
- class Railtie < Rails::Railtie
- railtie_name :active_resource
-
- require "active_resource/railties/log_subscriber"
- log_subscriber ActiveResource::Railties::LogSubscriber.new
-
- initializer "active_resource.set_configs" do |app|
- app.config.active_resource.each do |k,v|
- ActiveResource::Base.send "#{k}=", v
- end
- end
- end
- end
+ class Railtie < Rails::Railtie
+ config.i18n = ActiveSupport::OrderedOptions.new
+ config.i18n.railties_load_path = []
+ config.i18n.load_path = []
+ config.i18n.fallbacks = ActiveSupport::OrderedOptions.new
</ruby>
-The Railtie defines the +log_subscriber+ as +ActiveResource::Railties::LogSubscriber.new+ which has one method defined: +request+. +request+ is used whenever a request is made to an external service.
-
-There is only one initializer defined here: +set_configs+. This is covered later in the Initialization section.
-
-
-h4. ActionDispatch Railtie
-
-ActionDispatch handles all dispatch work for Rails. It interfaces with Action Controller to determine what action to undertake when a request comes in. TODO: I would quote the README but it is strangely absent. Flyin' blind here!
-
-The ActionDispatch Railtie was previously required when we called +require 'rails'+, but we will cover the Railtie here too.
-
-ActionDispatch depends on Active Support.
-
-h5. +require 'action_dispatch/railtie'+
-
-This file defines the ActionDispatch Railtie:
-
-<ruby>
- require "action_dispatch"
- require "rails"
-
- module ActionDispatch
- class Railtie < Rails::Railtie
- railtie_name :action_dispatch
-
- config.action_dispatch.x_sendfile_header = "X-Sendfile"
- config.action_dispatch.ip_spoofing_check = true
-
- # Prepare dispatcher callbacks and run 'prepare' callbacks
- initializer "action_dispatch.prepare_dispatcher" do |app|
- # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
- require 'rails/dispatcher'
- ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed }
- end
- end
- end
-</ruby>
-
-The +require 'rails'+ has already been done back in TODO: link to section.
-
-
-
-
-h5. +require 'action_dispatch'+
-
-This file was already loaded earlier in the initialization process. TODO: link to it.
-
-h5. ActionDispatch Railtie
-
-The ActionDispatch Railtie is almost as short as the Active Resource Railtie:
-
-<ruby>
- require "action_dispatch"
- require "rails"
-
- module ActionDispatch
- class Railtie < Rails::Railtie
- railtie_name :action_dispatch
-
- config.action_dispatch.x_sendfile_header = "X-Sendfile"
- config.action_dispatch.ip_spoofing_check = true
-
- # Prepare dispatcher callbacks and run 'prepare' callbacks
- initializer "action_dispatch.prepare_dispatcher" do |app|
- # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
- require 'rails/dispatcher'
- ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed }
- end
- end
- end
-</ruby>
-
-The +config+ method here is from +Rails::Railtie+ and pertains to your application's configuration. In this case, it is setting up some defaults which you can later override in _config/application.rb_.
-
-This Railtie does not define a +log_subscriber+ and only defines one initializer: +prepare_dispatcher+.
-
-h3. Return to _config/application.rb_
-
-Now that Rails has finished loading all the Railties by way of +require 'rails/all'+ Rails can now move on to the next line:
-
-<ruby>
- Bundler.require :default, Rails.env
-</ruby>
-
-NOTE: It is worth mentioning here that you are not tied to using Bundler with Rails 3, but it is (of course) advised that you do. To "turn off" Bundler, comment out or remove the corresponding lines in _config/application.rb_ and _config/boot.rb_.
-
-Bundler was +require+'d back in _config/boot.rb_, and so that is what makes it available here. This guide does not dive into the internals of Bundler; it's really it's own separate guide.
-
-The +Bundler.require+ method adds all the gems not specified inside a +group+ in the +Gemfile+ and the ones specified in groups for the +Rails.env+ (in this case, _development_), to the load path. This is how an application is able to find them.
-
-The rest of this file is spent defining your application's main class. This is it without the comments:
-
-<ruby>
- module YourApp
- class Application < Rails::Application
- config.encoding = "utf-8"
- config.filter_parameters += [:password]
- end
- end
-</ruby>
-
-h3. Return to Rails
-
-On the surface, this looks like a simple class inheritance. There's more underneath though. back in +Rails::Application+, the +inherited+ method is defined:
-
-<ruby>
- def inherited(base)
- raise "You cannot have more than one Rails::Application" if Rails.application
- super
- Rails.application = base.instance
- end
-</ruby>
-
-We do not already have a +Rails.application+, so instead this resorts to calling +super+. +Rails::Application+ descends from +Rails::Engine+ and so will call the +inherited+ method in +Rails::Engine+ (in _railties/lib/rails/engine.rb_), but before that it's important to note that +called_from+ is defined an +attr_accessor+ on +Rails::Engine+ and that +YourApp::Application+ is not an +abstract_railtie+:
+By inheriting from +Rails::Railtie+ the +Rails::Railtie#inherited+ method is called:
<ruby>
def inherited(base)
unless base.abstract_railtie?
- base.called_from = begin
- # Remove the line number from backtraces making sure we don't leave anything behind
- call_stack = caller.map { |p| p.split(':')[0..-2].join(':') }
- File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-\.]*/lib/rails|rack[\w\-\.]*/lib/rack] })
- end
- end
-
- super
- end
-</ruby>
-
-This +called_from+ setting looks a little overwhelming to begin with, but the short end of it is that it returns your application's root, something like: _/home/you/yourapp_. After +called_from+ has been set, +super+ is again called and this means the +Rails::Railtie#inherited+ method (in _railties/lib/rails/railtie.rb_):
-
-<ruby>
- def inherited(base)
- unless base.abstract_railtie?
- base.send(:include, self::Configurable)
+ base.send(:include, Railtie::Configurable)
subclasses << base
end
end
</ruby>
-Again, +YourApp::Application+ will return false for +abstract_railtie+ and so the code inside the +unless+ will be ran. The first line:
-
-<ruby>
- base.send(:include, self::Configurable)
-</ruby>
-
-includes the +self::Configurable+ module, with self being +Rails::Application+ in this context:
-
-<ruby>
- module Rails
- class Application
- module Configurable
- def self.included(base)
- base.extend ClassMethods
- end
-
- module ClassMethods
- def inherited(base)
- raise "You cannot inherit from a Rails::Application child"
- end
- end
-
- def config
- @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd))
- end
- end
- end
- end
-</ruby>
-
-The inclusion of the +Rails::Application::Configurable+ module triggers the +included+ method in here which extends +YourApp::Application+ with the +Rails::Application::Configurable::ClassMethods+.
-
-Now that the chain of +super+ calls is done, we'll go back to the original +inherited+ method in +Rails::Application+ and the final line in this method:
-
-<ruby>
- Rails.application = base.instance
-</ruby>
-
-+base+ in this case is +YourApp::Application+ and calling +instance+ on this will return an instance of +YourApp::Application+ through the +instance+ method defined here:
-
-<ruby>
- def instance
- if self == Rails::Application
- Rails.application
- else
- @@instance ||= new
- end
- end
-</ruby>
-
-+self+ in this case is +YourApp::Application+, so it won't match to +Rails::Application+ so instead the +new+ method is called which calls the +initialize+ method.
-
-
-
-
-h3. Firing it up!
-
-Now that we've covered the boot process of Rails the next line best to cover would be what happens after _script/rails_ has loaded _config/boot.rb_. That's quite simply that it then +require 'rails/commands'+ which is located at _railties/lib/rails/commands.rb_. Remember how +exec+ passed the arguments to +script/rails+? This is where they're used. _rails/commands.rb_ is quite a large file in Rails 3, as it contains all the Rails commands like console, about, generate and, of course, server. Because we've called +rails server+ the first argument in +ARGV+ is of course +"server"+. So assuming this we can determine that the +ARGV.shift+ in _commands.rb_ is going to return +"server"+, therefore it'll match this +when+:
-
-<ruby>
- when 's', 'server'
- require 'rails/commands/server'
- Dir.chdir(ROOT_PATH)
- Rails::Server.start
-</ruby>
-
-The keen-eyed observer will note that this +when+ also specifies the argument could also be simply +'s'+ thereby making the full command +rails s+. This is the same with the other commands with +generate+ becoming +g+, +console+ becoming +c+ and +dbconsole+ becoming +db+.
-
-This code here ensures we are at the +ROOT_PATH+ of our application (this constant was defined in _script/rails_) and then calls +Rails::Server.start+. +Rails::Server+ descends from +Rack::Server+ which is defined in the rack gem. The +Rails::Server.start+ method is defined like this:
-
-<ruby>
- def start
- ENV["RAILS_ENV"] = options[:environment]
-
- puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
- puts "=> Rails #{Rails.version} application starting in #{Rails.env} on http://#{options[:Host]}:#{options[:Port]}"
- puts "=> Call with -d to detach" unless options[:daemonize]
- trap(:INT) { exit }
- puts "=> Ctrl-C to shutdown server" unless options[:daemonize]
-
- super
- ensure
- puts 'Exiting' unless options[:daemonize]
- end
-</ruby>
-
-We can see here that there is usual output indicating that the server is booting up.
-
-How the +options+ variable gets set and how Rack starts the server up is covered in the next section.
-
-h3. Racking it up!
-
-
-This +Rack::Server.start+ method is defined like this:
+This first checks if the Railtie that's inheriting it is a component of Rails itself:
<ruby>
- def self.start
- new.start
- end
-</ruby>
-
-+new+ as you know calls +initialize+ in a class, and that is defined like this:
-
-<ruby>
- def initialize(options = nil)
- @options = options
- end
-</ruby>
-
-And then +options+, which are the options referenced by the +start+ method in +Rails::Server+.
-
-<ruby>
- def options
- @options ||= parse_options(ARGV)
- end
-</ruby>
-
-And +parse_options+:
-
-<ruby>
- def parse_options(args)
- options = default_options
+ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Plugin Rails::Engine Rails::Application)
- # Don't evaluate CGI ISINDEX parameters.
- # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
- args.clear if ENV.include?("REQUEST_METHOD")
+...
- options.merge! opt_parser.parse! args
- options
- end
-</ruby>
-
-And +default_options+:
-
-<ruby>
- def default_options
- {
- :environment => "development",
- :pid => nil,
- :Port => 9292,
- :Host => "0.0.0.0",
- :AccessLog => [],
- :config => "config.ru"
- }
- end
-</ruby>
-
-Finally! We've arrived at +default_options+ which leads into our next point quite nicely. After the object has been +initialize+'d, +start+ is called:
-
-<ruby>
- def start
- if options[:debug]
- $DEBUG = true
- require 'pp'
- p options[:server]
- pp wrapped_app
- pp app
- end
-
- if options[:warn]
- $-w = true
- end
-
- if includes = options[:include]
- $LOAD_PATH.unshift *includes
- end
-
- if library = options[:require]
- require library
- end
-
- daemonize_app if options[:daemonize]
- write_pid if options[:pid]
- server.run wrapped_app, options
- end
-</ruby>
-
-We're not debugging anything, so there goes the first 7 lines, we're not warning, nor are we including, requiring, daemonising or writing out a pid file. That's everything except the final line, which calls +run+ with the +wrapped_app+ which is then defined like this:
-
-<ruby>
- def wrapped_app
- @wrapped_app ||= build_app app
- end
-</ruby>
-
-and +build_app+'s first and only argument is +app+ which is defined like this:
-
-
-<ruby>
- def app
- @app ||= begin
- if !::File.exist? options[:config]
- abort "configuration #{options[:config]} not found"
- end
-
- app, options = Rack::Builder.parse_file(self.options[:config], opt_parser)
- self.options.merge! options
- app
- end
- end
-</ruby>
-
-+options+ is a method we talked about a short while ago, which is just the set of default options. +options[:config]+ in this context is therefore _config.ru_ which coincidentally we have in our application! To get an application instance from this method +Rack::Builder+ joins the fray with a call to +parse_file+ on our _config.ru_:
-
-<ruby>
- def self.parse_file(config, opts = Server::Options.new)
- options = {}
- if config =~ /\.ru$/
- cfgfile = ::File.read(config)
- if cfgfile[/^#\\(.*)/] && opts
- options = opts.parse! $1.split(/\s+/)
- end
- cfgfile.sub!(/^__END__\n.*/, '')
- app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app",
- TOPLEVEL_BINDING, config
- else
- require config
- app = Object.const_get(::File.basename(config, '.rb').capitalize)
- end
- return app, options
- end
-</ruby>
-
-First this reads your config file and checks it for +#\+ at the beginning. This is supported if you want to pass options into the +Rack::Server+ instance that you have and can be used like this:
-
-<ruby>
- #\\ -E production
- # This file is used by Rack-based servers to start the application.
-
- require ::File.expand_path('../config/environment', __FILE__)
- run YourApp::Application.instance
-
-</ruby>
-
-TODO: Is the above correct? I am simply guessing!
-
-After that it removes all the content after any +__END__+ in your _config.ru_ (TODO: because? Is this so it doesn't get eval'd?) and then evals the content of this file which, as you've seen is quite simple. The code that's first evaluated would be the require to the _config/environment.rb_ file, which leads into the next section.
-
-h3. _config/environment.rb_
-
-Now that we've seen that _rails/server_ gets to _config/environment.rb_ via Rack's requiring of it and Passenger requires it straight off the line. We've covered the boot process of Rails and covered the beginnings of a Rack server starting up. We have reached a common path for both _rails/server_ and Passenger now, so let's investigate what _config/environment.rb_ does.
-
-<ruby>
- # Load the rails application
- require File.expand_path('../application', __FILE__)
-
- # Initialize the rails application
- YourApp::Application.initialize!
-
-</ruby>
-
-As you can see, there's a require in here for _config/application.rb_, and this file looks like this:
-
-
-<ruby>
- module YourApp
- class Application < Rails::Application
- # Settings in config/environments/* take precedence over those specified here.
- # Application configuration should go into files in config/initializers
- # -- all .rb files in that directory are automatically loaded.
-
- # Add additional load paths for your own custom dirs
- # config.load_paths += %W( #{config.root}/extras )
-
- # Only load the plugins named here, in the order given (default is alphabetical).
- # :all can be used as a placeholder for all plugins not explicitly named
- # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
-
- # Activate observers that should always be running
- # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
-
- # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
- # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
- # config.time_zone = 'Central Time (US & Canada)'
-
- # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
- # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
- # config.i18n.default_locale = :de
-
- # Configure generators values. Many other options are available, be sure to check the documentation.
- # config.generators do |g|
- # g.orm :active_record
- # g.template_engine :erb
- # g.test_framework :test_unit, :fixture => true
- # end
- end
- end
-</ruby>
-
-These options (and their siblings) are explained in a later section. What's important to note for this file currently is that this is where the +YourApp::Application+ class is initialized and that it's a subclass of +Rails::Application+. This is the first point where your application begins to initialize Rails and as you can see all of this is configuration stuff which your initializers and really, the rest of your application will depend on. These options and what they do will be covered later.
-
-
-h3. Rails Initialization Process
-
-Now begins the actual initialization of Rails. Previously we have covered how _rails server_ and Passenger get to this stage and the parts of Rails that they have both loaded.
-
-h3. +Rails::Application+
-
-The first steps for the initialization process of Rails begins when +YourApp::Application+ descends from +Rails::Application+. The +Rails::Application+ class descends from +Rails::Engine+ class which itself descends from +Rails::Railtie+ defined in _railties/lib/rails/railtie.rb_. Along this fantastical chain of superclasses, there's defined a couple of inherited class methods. These methods just so happen to be called when a class inherits from (aka: is made a subclass of) this class. This first one is for +Rails::Application+:
-
-<ruby>
- def inherited(base)
- raise "You cannot have more than one Rails::Application" if Rails.application
- super
- Rails.application = base.instance
- end
-</ruby>
-
-This goes up the chain by using +super+ to calling +Rails::Engine.inherited+:
-
-<ruby>
- def inherited(base)
- unless abstract_railtie?(base)
- base.called_from = begin
- call_stack = caller.map { |p| p.split(':').first }
- File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] })
- end
- end
-
- super
- end
-</ruby>
-
-+called_from+ references where this code was called from. This is covered later on in the "Bootstrap Initializers" section.
-
-Which then calls +Rails::Railtie.inherited+:
-
-<ruby>
- def inherited(base)
- unless abstract_railtie?(base)
- base.send(:include, self::Configurable)
- subclasses << base
- end
- end
-</ruby>
-
-This +inherited+ first includes the +Rails::Configurable+ module on +base+, which is +YourApp::Application+. This module defines the +config+ method on +YourApp::Application+, and now it's starting to come together. You may notice that in your +config/application.rb+ file there's a +config+ method called there. This is the method from +Rails::Configurable+.
-
-Then this adds to +Rails::Railtie.subclasses+ your application's class because... TODO: explain.
-
-With +Rails::Railtie.inherited+ out of the way, and that being the last thing to do in +Rails::Engine.inherited+ we return to +Rails::Application.inherited+ which calls the following:
-
-<ruby>
- Rails.application = base.instance
+def abstract_railtie?
+ ABSTRACT_RAILTIES.include?(name)
+end
</ruby>
-As you already know, +base+ is +YourApp::Application+ and now it's calling the +instance+ method on it. This method is defined in +Rails::Application+ like this:
+Because +I18n::Railtie+ isn't in this list, +abstract_railtie?+ returns +false+. Therefore the +Railtie::Configurable+ module is included into this class and the +subclasses+ method is called and +I18n::Railtie+ is added to this new array.
<ruby>
- def instance
- if self == Rails::Application
- Rails.application
- else
- @@instance ||= new
- end
- end
+def subclasses
+ @subclasses ||= []
+end
</ruby>
-The +new+ method here simply creates a new +Rails::Application+ and sets it to the +@@instance+ class variable. No magic.
-
-h3. Your Application's Configuration
-Now that +inherited+ has finished doing its job, next up in _config/application.rb_ is the call to the +config+ object's methods. As explained before, this +config+ object is an instance of +Rails::Railtie::Configuration+, put into place by the call of +include Rails::Configurable+ back in +Rails::Railtie.inherited+. This defined it as such:
+The +config+ method used at the top of +I18n::Railtie+ is defined on +Rails::Railtie+ and is defined like this:
<ruby>
def config
@@ -2463,231 +765,45 @@ Now that +inherited+ has finished doing its job, next up in _config/application.
end
</ruby>
-All the methods for +Rails::Railtie::Configuration+ are defined like this in _railties/lib/rails/railtie/configuration.rb_:
+At this point, that +Railtie::Configuration+ constant is automatically loaded which causes the +rails/railties/configuration+ file to be loaded. The line for this is this particular line in +railties/lib/rails/railtie.rb+:
<ruby>
- require 'rails/configuration'
-
- module Rails
- class Railtie
- class Configuration
- include Rails::Configuration::Shared
- end
- end
- end
+ autoload :Configuration, "rails/railtie/configuration"
</ruby>
-As you can probably guess here, the +Rails::Configuration+ module is defined by _rails/configuration_ (_railties/lib/rails/configuration.rb_).
-
-h3. +Rails::Configuration::Shared+
-
-In a standard application, the +application.rb+ looks like this with all the comments stripped out:
+h4. +railties/lib/rails/railtie/configuration.rb+
-<ruby>
- require File.expand_path('../boot', __FILE__)
-
- module YourApp
- class Application < Rails::Application
- config.filter_parameters << :password
- end
- end
-</ruby>
+This file begins with a require out to +rails/configuration+ which has already been required earlier in the process and so isn't required again.
-The +config+ method being the one defined on +Rails::Application::Configurable+:
-
-<ruby>
- def config
- @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd))
- end
-</ruby>
-
-The method +find_with_root_flag+ is defined on +Rails::Engine+ (the superclass of +Rails::Application+) and it will find the directory containing a certain flag. In this case it's the +config.ru+ file:
-
-<ruby>
- def find_root_with_flag(flag, default=nil)
- root_path = self.called_from
-
- while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
- parent = File.dirname(root_path)
- root_path = parent != root_path && parent
- end
-
- root = File.exist?("#{root_path}/#{flag}") ? root_path : default
- raise "Could not find root path for #{self}" unless root
-
- RUBY_PLATFORM =~ /(:?mswin|mingw)/ ?
- Pathname.new(root).expand_path : Pathname.new(root).realpath
- end
-</ruby>
-
-+called_from+ goes through the +caller+ which is the stacktrace of the current thread, in the case of your application it would go a little like this:
-
-<pre>
- /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/application.rb:30:in `inherited'
- /home/you/yourapp/config/application.rb:4:in `<module:TestApp>'
- /home/you/yourapp/config/application.rb:3:in `<top (required)>'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `block in require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:537:in `new_constants_in'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands.rb:33:in `<top (required)>'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `block in require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:537:in `new_constants_in'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /var/www/rboard/script/rails:10:in `<main>'
-</pre>
-
-+called_from+ is defined in the +inherited+ method for +Rails::Engine+ which looks like this:
-
-<ruby>
- base.called_from = begin
- call_stack = caller.map { |p| p.split(':').first }
- File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] })
- end
-</ruby>
-
-The +call_stack+ here is the +caller+ output shown previously, minus everything after the first +:+ on all the lines. The first path that matches this is _/usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails_. Yours may vary slightly, but should always end in _railties-x.x.x/lib/rails_.
-
-The code in +find_root_with_flag+ will go up this directory structure until it reaches the top, which in this case is +/+.
-
-<ruby>
- while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
- parent = File.dirname(root_path)
- root_path = parent != root_path && parent
- end
-
- root = File.exist?("#{root_path}/#{flag}") ? root_path : default
- raise "Could not find root path for #{self}" unless root
-</ruby>
-
-TODO: What is all this for?
-
-At the root of the system it looks for +config.ru+. TODO: Why? Obviously it's not going to find it, so it uses the +default+ option we've specified which is +Dir.pwd+ which will default to the root folder of your Rails application. This path is then passed to +Rails::Application::Configuration.new+. +Rails::Application::Configuration+ descends from +Rails::Engine::Configuration+ and the +initialize+ method goes like this:
-
-<ruby>
- def initialize(*)
- super
- @allow_concurrency = false
- @colorize_logging = true
- @filter_parameters = []
- @dependency_loading = true
- @serve_static_assets = true
- @time_zone = "UTC"
- @consider_all_requests_local = true
- end
-</ruby>
-
-The +super+ method here is the +initialize+ method in +Rails::Engine::Configuration+:
-
-<ruby>
- def initialize(root=nil)
- @root = root
- end
-</ruby>
-
-Here, the +@root+ variable is assigned the path of your application and then the remainder of +Rails::Application::Configuration.initialize+ is ran, setting up a few instance variables for basic configuration, including one for +@filter_parameters+.
-
-Now with the +config+ option set up, we can go onwards and call +filter_parameters+ on it. This +filter_parameters+ method is not defined on +Rails::Configuration::Shared+ and actually falls to the +method_missing+ defined there instead:
+This file defines the +Rails::Railtie::Configuration+ class which is responsible for providing a way to easily configure railties and it's the +initialize+ method here which is called by the +config+ method back in the +i18n_railtie.rb+ file. The methods on this object don't exist, and so are rescued by the +method_missing+ defined further down in +configuration.rb+:
<ruby>
def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? options[$1] = args.first : options[$1]
- end
- super
- end
-</ruby>
-
-We're not calling +filter_parameters=+, we're calling +filter_parameters+, therefore it'll be the second part of this ternary argument: +options[$1]+. The options method is defined like this:
-
-<ruby>
- def options
- @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- end
-</ruby>
-
-OrderedOptions exists... TODO: explain.
-
-
-So from this we can determine that our +options+ hash now has a key for +filter_parameters+ which's value is an array consisting of a single symbol: +:password+. How this option manages to get into the +@filter_parameters+ variable defined on the +Rails::Application::Configuration.initialize+ method is explained later.
-
-h3. Application Configured!
-
-Now your application has finished being configured (at least in the sense of _config/application.rb_, there's more to come!) in _config/environment.rb_ the final line calls +YourApp::Application.initalize!+.
-
-h3. Initialization begins
-
-This is one of those magical uses of +method_missing+ which, for the purposes of debugging, is something that you don't expect to come across as often as you do and as a consequence you'll spend a good portion of an hour looking for method definitions that don't exist because +method_missing+ is taking care of it. There's some pretty crafty use of +method_missing+ all over Rails and it's encouraged to take note of its power.
-
-+Rails::Application+ has a +method_missing+ definition which does this:
-
-<ruby>
- def method_missing(*args, &block)
- instance.send(*args, &block)
- end
-</ruby>
-
-With our +instance+ being our already initialized by the +inherited+ method, this will just return the value of the +@@instance+ variable, a +Rails::Application+ object. Calling +initialize!+ on this method does this:
-
-<ruby>
- def initialize!
- run_initializers(self)
- self
+ if name.to_s =~ /=$/
+ @@options[$`.to_sym] = args.first
+ elsif @@options.key?(name)
+ @@options[name]
+ else
+ super
+ end
end
</ruby>
-The initializers it is talking about running here are the initializers for our application. The object passed in to +run_initializers+ is +YourApp::Application+.
-
+So therefore when an option is referred to it simply stores the value as the key if it's used in a setter context, or retrieves it if used in a getter context. Nothing fancy going on there.
-h3. +run_initializers+
+h4. Back to +activesupport/lib/active_support/i18n_railtie.rb+
-This method begins the running of all the defined initializers. In the section "The Boot Process" we covered the loading sequence of Rails before any initialization happens and during this time we saw that the +Rails::Railtie+ class includes the +Initializable+ module. As we've also seen +YourApp::Application+ is a descendant of this class, so it too has these methods.
-
-+run_initializers+ looks like this:
+After the configuration method the +reloader+ method is defined, and then the first of of Railties' initializers is defined: +i18n.callbacks+.
<ruby>
- def run_initializers(*args)
- return if instance_variable_defined?(:@ran)
- initializers.each do |initializer|
- initializer.run(*args)
+ initializer "i18n.callbacks" do
+ ActionDispatch::Reloader.to_prepare do
+ I18n::Railtie.reloader.execute_if_updated
end
- @ran = true
- end
-</ruby>
-
-Here the +initializers+ method is defined in _railties/lib/rails/application.rb_:
-
-<ruby>
- def initializers
- initializers = Bootstrap.initializers_for(self)
- railties.all { |r| initializers += r.initializers }
- initializers += super
- initializers += Finisher.initializers_for(self)
- initializers
end
</ruby>
-h3. +Bootstrap+ initializers
-
-The first line here references a +Bootstrap+ class we haven't seen before. Or have we? The keen-eyed observer would have spotted an +autoload+ for it at the top of +Rails::Application+:
-
-<ruby>
- autoload :Bootstrap, 'rails/application/bootstrap'
-</ruby>
-
-Now that we've referenced that class, it will be required for us. You'll notice inside this class that there's an +include Initializable+, providing the afore-mentioned methods from this module. Inside this class a number of initializers are defined.
-
-* load_environment_config
-* load_all_active_support
-* preload_frameworks
-* initialize_logger
-* initialize_cache
-* initialize_subscriber
-* set_clear_dependencies_hook
-* initialize_dependency_mechanism
-
-These are all defined using the +initializer+ method:
+The +initializer+ method (from the +Rails::Initializable+ module) here doesn't run the block, but rather stores it to be run later on:
<ruby>
def initializer(name, opts = {}, &blk)
@@ -2697,50 +813,25 @@ These are all defined using the +initializer+ method:
end
</ruby>
-The +initializers+ method defined here just references an +@initializers+ variable:
+An initializer can be configured to run before or after another initializer, which we'll see a couple of times throughout this initialization process. Anything that inherits from +Rails::Railtie+ may also make use of the +initializer+ method, something which is covered in the "Configuration guide":[http://ryanbigg.com/guides/configuring.html#rails-railtie-initializer].
-<ruby>
- def initializers
- @initializers ||= []
- end
-</ruby>
-
-As you can see from this method it will set +opts[:after]+ if there are previously defined initializers. So we can determine from this that the order our initializers are defined in is the same order that they run in, but only by default. It is possible to change this by specifying an +:after+ or +:before+ option as we will see later on. Each initializer is its own instance of the +Initializer+ class:
+The +Initializer+ class here is defined within the +Rails::Initializable+ module and its +initialize+ method is defined to just set up a couple of variables:
<ruby>
- class Initializer
- attr_reader :name, :block
-
- def initialize(name, context, options, &block)
- @name, @context, @options, @block = name, context, options, block
- end
-
- def before
- @options[:before]
- end
-
- def after
- @options[:after]
- end
-
- def run(*args)
- @context.instance_exec(*args, &block)
- end
-
- def bind(context)
- return self if @context
- Initializer.new(@name, context, @options, &block)
- end
+ def initialize(name, context, options, &block)
+ @name, @context, @options, @block = name, context, options, block
end
</ruby>
-Now that +Rails::Application::Bootstrap+ has finished loading, we can continue on with our initialization. We saw that it called this:
+Once this +initialize+ method is finished, the object is added to the object the +initializers+ method returns:
<ruby>
- initializers = Bootstrap.initializers_for(self)
+ def initializers
+ @initializers ||= self.class.initializers_for(self)
+ end
</ruby>
-Calling +initializers_for+, defined like this:
+If +@initializers+ isn't set (which it won't be at this point), the +intializers_for+ method will be called for this class.
<ruby>
def initializers_for(binding)
@@ -2748,12 +839,14 @@ Calling +initializers_for+, defined like this:
end
</ruby>
-The +binding+ argument here is +YourApp::Application+ and this will return a new +Initializer+ object for all the initializers in +initializers_chain+ for this particular context. +initializers_chain+ goes like this:
+The +Collection+ class in +railties/lib/rails/initializable.rb+ inherits from +Array+ and includes the +TSort+ module which is used to sort out the order of the initializers based on the order they are placed in.
-<ruby>
+The +initializers_chain+ method referenced in the +initializers_for+ method is defined like this:
+
+<rub>
def initializers_chain
initializers = Collection.new
- ancestors.reverse_each do |klass|
+ ancestors.reverse_each do | klass |
next unless klass.respond_to?(:initializers)
initializers = initializers + klass.initializers
end
@@ -2761,1278 +854,259 @@ The +binding+ argument here is +YourApp::Application+ and this will return a new
end
</ruby>
-The ancestors list is relatively short for +Rails::Application::Bootstrap+, consisting of itself and +Rails::Initializable+. Rails will go through these ancestors in reverse and check them all if they +respond_to?(:initializers)+. +Rails::Initializable+ does not and so it's skipped. +Rails::Application::Bootstrap+ of course does, and this is the list of initializers we covered earlier.
-
-After +initializers_chain+ is finished, then they are +map+'d like this, with the +binding+ of course being +YourApp::Application+ as explained previously.
+This method collects the initializers from the ancestors of this class and adds them to a new +Collection+ object using the <tt>+</tt> method which is defined like this for the <tt>Collection</tt> class:
<ruby>
- def initializers_for(binding)
- Collection.new(initializers_chain.map { |i| i.bind(binding) })
+ def +(other)
+ Collection.new(to_a + other.to_a)
end
</ruby>
-Wow. All that to cover just the first line in the +initializers+ method for +Rails::Application+.
-
-h3. Railties Initializers
+So this <tt>+</tt> method is overriden to return a new collection comprising of the existing collection as an array and then using the <tt>Array#+</tt> method combines these two collections, returning a "super" +Collection+ object. In this case, the only initializer that's going to be in this new +Collection+ object is the +i18n.callbacks+ initializer.
-This section covers the loading of the initializers and we will go into depth for each initializer in the next section, as they make more sense explained in their chain.
-
-The second line in +Rails::Application#initializers+:
+The next method to be called after this +initializer+ method is the +after_initialize+ method on the +config+ object, which is defined like this:
<ruby>
- def initializers
- railties.all { |r| initializers += r.initializers }
+ def after_initialize(&block)
+ ActiveSupport.on_load(:after_initialize, :yield => true, &block)
end
</ruby>
-calls +railties+, which is defined like this:
+The +on_load+ method here is provided by the +active_support/lazy_load_hooks+ file which was required earlier and is defined like this:
<ruby>
- def railties
- @railties ||= Railties.new(config)
- end
-</ruby>
-
-This sets up a new +Rails::Application::Railties+ object like this:
-
-<ruby>
- def initialize(config)
- @config = config
- end
-</ruby>
-
-And calls +all+ on it:
-
-<ruby>
- def all(&block)
- @all ||= railties + engines + plugins
- @all.each(&block) if block
- @all
- end
-</ruby>
-
-This +all+ method executes code on all the +Rails::Railtie+ and +Rails::Engine+ subclasses, retreived by the +railties+ and +engines+ methods defined right after +all+:
-
-<ruby>
- def railties
- @railties ||= ::Rails::Railtie.subclasses.map(&:new)
- end
-
- def engines
- @engines ||= ::Rails::Engine.subclasses.map(&:new)
- end
-</ruby>
-
-By default, the railties are:
-
-* +ActiveSupport::Railtie+
-* +I18n::Railtie+
-* +ActionDispatch::Railtie+
-* +ActionController::Railtie+
-* +ActiveRecord::Railtie+
-* +ActionView::Railtie+
-* +ActionMailer::Railtie+
-* +ActiveResource::Railtie+
-* +Rails::TestUnitRailtie+
-
-And these all descend from +Rails::Railtie+.
-
-The default +engines+ are +[]+.
-
-The +plugins+ method it calls is a little more complex:
-
-<ruby>
- def plugins
- @plugins ||= begin
- plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym }
- Plugin.all(plugin_names, @config.paths.vendor.plugins)
- end
- end
-</ruby>
-
-+@config.paths+ is defined in the +Rails::Application::Configuration+ like this:
-
-<ruby>
- def paths
- @paths ||= begin
- paths = super
- paths.app.controllers << builtin_controller if builtin_controller
- paths.config.database "config/database.yml"
- paths.config.environment "config/environments", :glob => "#{Rails.env}.rb"
- paths.log "log/#{Rails.env}.log"
- paths.tmp "tmp"
- paths.tmp.cache "tmp/cache"
- paths.vendor "vendor", :load_path => true
- paths.vendor.plugins "vendor/plugins"
-
- if File.exists?("#{root}/test/mocks/#{Rails.env}")
- ActiveSupport::Deprecation.warn "\"RAILS_ROOT/test/mocks/#{Rails.env}\" won't be added " <<
- "automatically to load paths anymore in future releases"
- paths.mocks_path "test/mocks", :load_path => true, :glob => Rails.env
- end
-
- paths
- end
- end
-</ruby>
-
-When we call +@config.paths.vendor.plugins+ it will return +"vendor/plugins"+.
-
-
-If you've defined specific plugin requirements for your application in _config/application.rb_ by using this code:
-
-<ruby>
- config.plugins = [:will_paginate, :by_star]
-</ruby>
-
-or specific plugin loading using a similar statement such as this next one:
-
-<ruby>
- config.plugins = [:will_paginate, :by_star, :all]
-</ruby>
-
-
-Then this is where the +@config.plugins+ comes from. If you wish to load only certain plugins for your application, use the first example. If you wish to load certain plugins before the rest then the second example is what you would use.
-
-If +config.plugins+ is not defined then +:all+ is specified in its place. Whatever the +plugin_names+ is specified as, is passed to +Plugin.all+ along with the path to the plugins, +@config.path.vendor.plugins+ (which defaults to _vendor/plugins_):
-
-<ruby>
- def self.all(list, paths)
- plugins = []
- paths.each do |path|
- Dir["#{path}/*"].each do |plugin_path|
- plugin = new(plugin_path)
- next unless list.include?(plugin.name) || list.include?(:all)
- plugins << plugin
- end
- end
-
- plugins.sort_by do |p|
- [list.index(p.name) || list.index(:all), p.name.to_s]
- end
- end
-</ruby>
-
-As we can see here it will go through the paths and for every folder in _vendor/plugins_ and +initialize+ a new +Rails::Plugin+ object for each:
-
-<ruby>
- def initialize(root)
- @name = File.basename(root).to_sym
- config.root = root
- end
-</ruby>
-
-This sets the plugin name to be the same name as the folder so the plugin located at _vendor/plugins/by\_star_'s name is +by_star+. After that, the +config+ object is initialized:
-
-<ruby>
- def config
- @config ||= Engine::Configuration.new
- end
-</ruby>
-
-and the root of the plugin defined as that folder. The reasoning for defining a +root+ is so that the initializer called +load_init_rb+ has some place to look for this file:
-
-<ruby>
- initializer :load_init_rb, :before => :load_application_initializers do |app|
- file = Dir["#{root}/{rails/init,init}.rb"].first
- config = app.config
- eval(File.read(file), binding, file) if file && File.file?(file)
- end
-</ruby>
-
-A little more on that later, however.
-
-If the plugin is not included in the list then it moves on to the next one. For all plugins included in the list (or if +:all+ is specified in the list) they are put into a +plugins+ local variable which is then sorted:
-
-<ruby>
- plugins.sort_by do |p|
- [list.index(p.name) || list.index(:all), p.name.to_s]
- end
-</ruby>
-
-The sort order is the same order as which they appear in the +config.plugins+ setting, or in alphabetical order if there is no setting specified.
-
-Now that we have our railties, engines, and plugins in a line we can finally get back to the +all+ code:
-
-<ruby>
- def initializers
- railties.all { |r| initializers += r.initializers }
- end
-</ruby>
-
-This block will gather add the railties' initializers to it.
-
-h3. Engine Initializers
-
-The third line in this +initializers+ method:
-
-<ruby>
- initializers += super
-</ruby>
-
-The +super+ method it's referring to is of course +Rails::Engine.initializers+, which isn't defined on the class but, as we have seen before, is defined on the +Rails::Railtie+ class it inherits from through the +Rails::Initializable+ module. Therefore we can determine the initializers to be added are now the ones defined in +Rails::Engine+.
-
-h3. Finisher Initializers
-
-The final set of initializers in this chain are those in +Rails::Finisher+. This involves running any after initialize code, building the middleware stack and adding the route for _rails/info/properties_.
-
-h3. Running the Initializers
-
-Now that we have all the initializers we can go back to the +run_initializers+ in +Rails::Initializable+:
-
-<ruby>
- def run_initializers(*args)
- return if instance_variable_defined?(:@ran)
- initializers.each do |initializer|
- initializer.run(*args)
- end
- @ran = true
- end
-</ruby>
-
-Now we finally have all the +initializers+ we can go through them and call +run+:
-
-<ruby>
- def run(*args)
- @context.instance_exec(*args, &block)
- end
-</ruby>
-
-You may remember that the +@context+ in this code is +YourApp::Application+ and calling +instance_exec+ on this class will make a new instance of it and execute the code within the +&block+ passed to it. This code within the block is the code from all the initializers.
-
-h3. Bootstrap Initializers
-
-These initializers are the very first initializers that will be used to get your application going.
-
-h4. +load_environment_config+
-
-<ruby>
- initializer :load_environment_config do
- require_environment!
- end
-</ruby>
-
-This quite simply makes a call to +require_environment!+ which is defined like this in +Rails::Application+:
-
-<ruby>
- def require_environment!
- environment = config.paths.config.environment.to_a.first
- require environment if environment
- end
-</ruby>
-
-We've seen +config.paths+ before when loading the plugins and they're explained in more detail in the Bonus section at the end of this guide. +config.enviroment+ for +paths+ is defined like this:
-
-<ruby>
- paths.config.environment "config/environments", :glob => "#{Rails.env}.rb"
-</ruby>
-
-+Rails.env+ was defined way back in the boot process when +railties/lib/rails.rb+ was required:
-
-<ruby>
-module Rails
- class << self
-
- ...
-
- def env
- @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
- end
-
- ...
-
- end
-end
-</ruby>
-
-With +ENV["RAILS_ENV"]+ and +ENV["RACK_ENV"]+ not set to anything for our server booting process, this will default to +"development"+.
-
-Therefore the path to this config file line would look like this with a substitution made:
-
-<ruby>
- paths.config.environment "config/environments", :glob => "development.rb"
-</ruby>
-
-This method returns a +Path+ object (which acts as an +Enumerable+).
-
-Back to +require_environment+ now:
-
-<ruby>
- def require_environment!
- environment = config.paths.config.environment.to_a.first
- require environment if environment
- end
-</ruby>
-
-And we've determined that +config.paths.config.environment+ is +Path+ object, and calling +to_a+ on that object calls +paths+ because it's +alias+'d at the bottom of the +Path+ class definition:
-
-<ruby>
- alias to_a paths
-</ruby>
-
-<ruby>
- def paths
- raise "You need to set a path root" unless @root.path
- result = @paths.map do |p|
- path = File.expand_path(p, @root.path)
- @glob ? Dir[File.join(path, @glob)] : path
- end
- result.flatten!
- result.uniq!
- result
- end
-</ruby>
-
-This returns an array of files according to our +path+ and +@glob+ which are +config/environments+ and +development.rb+ respectively, therefore we can determine that:
-
-<ruby>
- Dir[File.join(path, @glob)]
-</ruby>
-
-will return an +Array+ containing one element, +"config/enviroments/development.rb"+. Of course when we call +first+ on this Array we'll get the first element and because that exists, we now +require "config/environments/development.rb"+.
-
-This file contains the following by default:
-
-<ruby>
- YourApp::Application.configure do
- # Settings specified here will take precedence over those in config/environment.rb
-
- # In the development environment your application's code is reloaded on
- # every request. This slows down response time but is perfect for development
- # since you don't have to restart the webserver when you make code changes.
- config.cache_classes = false
-
- # Log error messages when you accidentally call methods on nil.
- config.whiny_nils = true
-
- # Show full error reports and disable caching
- config.consider_all_requests_local = true
- config.action_view.debug_rjs = true
- config.action_controller.perform_caching = false
-
- # Don't care if the mailer can't send
- config.action_mailer.raise_delivery_errors = false
- end
-</ruby>
-
-This +configure+ method is an +alias+ of +class_eval+ on +Rails::Application+:
-
-<ruby>
- alias :configure :class_eval
-</ruby>
-
-therefore, the code inside of the +configure+ is evaluated within the context of +YourApp::Application+.
-
-The +config+ object here is the same one that was set up when _config/application.rb_ was loaded, therefore the methods called in this object will fall to the +method_missing+ defined in +Rails::Configuration::Shared+:
-
-<ruby>
- def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? options[$1] = args.first : options[$1]
- end
- super
- end
-</ruby>
-
-This time we are using methods ending in +\=+, so it will set the key in the +options+ to be the value specified. The first couple of options, +cache_classes+, +whiny_nils+, +consider_all_requests_local+ are just simple keys on the +options+. If you recall how options were setup then you may be able to work out how the remaining +action_view+, +action_controller+ and +action_mailer+ methods work.
-
-Firstly, we'll cover how +config_key_regexp+ is defined:
-
-<ruby>
- def config_key_regexp
- bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|')
- /^(#{bits})(?:=)?$/
- end
-</ruby>
-
-And also +config_keys+:
-
-<ruby>
- def config_keys
- (Railtie.railtie_names + Engine.engine_names).map { |n| n.to_s }.uniq
- end
-</ruby>
-
-+config_keys+ in here returns:
-
-<ruby>
- [:active_support, :i18n, :action_dispatch, :action_view, :action_controller, :active_record, :action_mailer, :active_resource, :test_unit]
-</ruby>
-
-With all of those keys coming from +Railtie::railtie_names+. If you've elected to not load some of the frameworks here they won't be available as configuration keys, so you'll need to remove them too.
-
-Now a reminder of how the +options+ key is defined:
-
-<ruby>
- def options
- @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- end
-</ruby>
-
-The values for these framework keys are +ActiveSupport::OrderedOptions+ objects, with the class defined like this:
-
-<ruby>
- module ActiveSupport #:nodoc:
- class OrderedOptions < OrderedHash
- def []=(key, value)
- super(key.to_sym, value)
- end
-
- def [](key)
- super(key.to_sym)
- end
-
- def method_missing(name, *args)
- if name.to_s =~ /(.*)=$/
- self[$1.to_sym] = args.first
- else
- self[name]
- end
- end
- end
- end
-</ruby>
-
-We can determine when we call +config.action_view.debug_rjs+ it's falling back to the +method_missing+ defined on +ActiveSupport::OrderedOptions+, which ends up either setting or retrieving a key. In this case because we're using a setter, it will set the key for this hash. This completes the loading of _config/environments/development.rb_.
-
-h4. +load_all_active_support+
-
-This initializer does exactly what it says:
-
-<ruby>
- initializer :load_all_active_support do
- require "active_support/all" unless config.active_support.bare
- end
-</ruby>
-
-If you don't want this to happen you can specify the +config.active_support.bare+ option to +true+ in either _config/application.rb_ or any of your environment files.
-
-h4. +preload_frameworks+
-
-Remember earlier how we had all that stuff +eager_autoload+'d for Active Support?
-
-<ruby>
- initializer :preload_frameworks do
- require 'active_support/dependencies'
- ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks
- end
-</ruby>
-
-This is where it gets loaded. The +eager_autoload!+ method is defined like this:
-
-<ruby>
- def self.eager_autoload!
- @@autoloads.values.each { |file| require file }
- end
-</ruby>
-
-With +@@autoloads+ being
-
-
-* load_all_active_support
-* preload_frameworks
-* initialize_logger
-* initialize_cache
-* initialize_subscriber
-* set_clear_dependencies_hook
-* initialize_dependency_mechanism
-
-h4. Active Support Initializers
-
-Active Support
-
-**Active Support Initializers**
-
-* active_support.initialize_whiny_nils
-* active_support.initialize_time_zone
-
-**I18n Initializers**
-
-* i18n.initialize
-
-The +I18n::Railtie+ also defines an +after_initialize+ which we will return to later when discussing the initializers in detail.
-
-**Action Dispatch Initializers**
-
-* action_dispatch.prepare_dispatcher
-
-**Action Controller Initializers**
-
-* action_controller.logger
-* action_controller.set_configs
-* action_controller.initialize_framework_caches
-* action_controller.set_helpers_path
-
-**Active Record Initializers**
-
-* active_record.initialize_time_zone
-* active_record.logger
-* active_record.set_configs
-* active_record.log_runtime
-* active_record.initialize_database_middleware
-* active_record.load_observers
-* active_record.set_dispatch_hooks
-
-**Action View Initializers **
-
-* action_view.cache_asset_ids
-
-**Action Mailer Initializers **
-
-* action_mailer.logger
-* action_mailer.set_configs
-* action_mailer.url_for
-
-**Active Resource Initializers**
-
-* active_resource.set_configs
-
-**Rails::Engine Initializers**
-
-* set_load_path
-* set_autoload_paths
-* add_routing_paths
-
-
-h4. +Rails::Engine.new+
-
-The +new+ method doesn't exist, but in Ruby classes calling +new+ on the class instantiates a new instance of that class and calls the instance method +initialize+ on it. This method for +Rails::Application+ goes like this:
-
-<ruby>
- def initialize
- require_environment
- Rails.application ||= self
- @route_configuration_files = []
- end
-</ruby>
-
-h4. +Rails::Application#require_environment+
-
-This is not a crafty method like the previous ones, it just does as it says on the box:
-
-<ruby>
- def require_environment
- require config.environment_path
- rescue LoadError
- end
-</ruby>
-
-The +config+ object here is actually another +delegate+'d method (along with +routes+), this time to +self.class+:
-
-<ruby>
- delegate :config, :routes, :to => :'self.class'
-</ruby>
-
-So the method call is actually +self.class.config+.
-
-
-h4. +Rails::Application.config+
-
-Defined back inside the +class << self+ for +Rails::Application+, +config+ makes a new +Rails::Application::Configuration+ object and caches it in a variable called +@config+:
-
-<ruby>
- def config
- @config ||= Configuration.new(Plugin::Configuration.default)
- end
-</ruby>
-
-h4. +Rails::Plugin::Configuration.default+
-
-The +Rails::Plugin::Configuration+ class may be a bit difficult to find at first, but if you look for _plugin.rb_ in Rails, you'll find it in _railties/lib/rails/plugin.rb_. In this file, we see the following:
-
-<ruby>
- module Rails
- class Plugin < Engine
- ...
- end
- end
-</ruby>
-
-So we note here that +Rails::Plugin+ descends from +Rails::Railtie+ and secondly we note that the class +Configuration+ is not actually included in the +Plugin+ class, but it **is** in the +Railtie+ class!
-
-h4. +Rails::Railtie::Configuration+
-
-We've now tracked down the +Plugin::Configuration.default+ method to being +Railtie::Configuration.default+, which is defined like this in _railties/lib/rails/configuration.rb_:
-
-<ruby>
- class Railtie::Configuration
- def self.default
- @default ||= new
- end
- ...
- end
-</ruby>
-
-In this case we have effectively seen that it's doing Configuration.new(Configuration.new). I'll explain why.
-
-h4. +Rails::Application::Configuration.new+
-
-TODO: CLEAN THIS UP! This subclassing is only temporary and will probably not be separate in Rails 3. This is based solely off what the comment at the top of the Railtie::Configuration class says!
-
-The first thing to note here is that this class is subclassed from +Railtie::Configuration+ and therefore the method here is actually +Railtie::Configuration.new+. As mentioned previously, calling +new+ will make a new object of this class and then call +initialize+ on it, which is defined like this:
-
-<ruby>
- def initialize(base = nil)
- if base
- @options = base.options.dup
- @middleware = base.middleware.dup
+ def self.on_load(name, options = {}, &block)
+ if base = @loaded[name]
+ execute_hook(base, options, block)
else
- @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- @middleware = self.class.default_middleware_stack
+ @load_hooks[name] << [block, options]
end
end
</ruby>
-This method is not called with a +base+ argument for +Plugin::Configuration.default+ but it is for the +Configuration.new+ wrapped around it. We'll go for the internal one first, since that's the order Rails loads them in.
-
-h4. +default_middleware_stack+
-
-This method is defined like this:
-
-<ruby>
- def self.default_middleware_stack
- ActionDispatch::MiddlewareStack.new.tap do |middleware|
- middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
- middleware.use('::Rack::Lock', :if => lambda { !ActionController::Base.allow_concurrency })
- middleware.use('::Rack::Runtime')
- middleware.use('ActionDispatch::ShowExceptions', lambda { ActionController::Base.consider_all_requests_local })
- middleware.use('ActionDispatch::Notifications')
- middleware.use('ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes })
- middleware.use('ActionDispatch::Cookies')
- middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options })
- middleware.use('ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store })
- middleware.use('ActionDispatch::ParamsParser')
- middleware.use('::Rack::MethodOverride')
- middleware.use('::ActionDispatch::Head')
- end
- end
-</ruby>
-
-To really understand this method we need to dig a little deeper, down into where +ActionDispatch::MiddlewareStack.new+ is defined and what in particular it does for us.
-
-h4. +ActionDispatch::MiddlewareStack.new+
-
-+ActionDispatch+ is our first foray outside of the +railties+ gem, as this is actually defined in the +actionpack+ part of Rails. The class definition is as important as the method:
-
-<ruby>
- module ActionDispatch
- class MiddlewareStack < Array
-
- ...
-
- def initialize(*args, &block)
- super(*args)
- block.call(self) if block_given?
- end
- end
- end
-</ruby>
-
-When it's calling +super+ here it's actually calling +initialize+ on the Array class and from this we can determine that an +ActionDispatch::MiddlewareStack+ object is just an +Array+ object with special powers. One of those special powers is the ability to take a block, and +call+ it with +self+, meaning the block's parameter is the object itself!
-
-h4. +ActionDispatch::MiddlewareStack.use+
-
-Previously we saw a chunk of code that I'll re-show you stripped down:
+The +@loaded+ variable here is a hash containing elements representing the different components of Rails that have been loaded at this stage. Currently, this hash is empty. So the +else+ is executed here, using the +@load_hooks+ variable defined in +active_support/lazy_load_hooks+:
<ruby>
- def self.default_middleware_stack
- ActionDispatch::MiddlewareStack.new.tap do |middleware|
- middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
- ...
- end
- end
+ @load_hooks = Hash.new {|h,k| h[k] = [] }
</ruby>
-As explained in the previous section, we know that the +new+ on +ActionDispatch::MiddlewareStack+ takes a block and that block has one parameter which is the object itself. On this object we call the +use+ method to include middleware into our application. The use method simply does this:
+This defines a new hash which has keys that default to empty arrays. This saves Rails from having to do something like this instead:
<ruby>
- def use(*args, &block)
- middleware = Middleware.new(*args, &block)
- push(middleware)
- end
+ @load_hooks[name] = []
+ @load_hooks[name] << [block, options]
</ruby>
-We'll come back to this method later on.
+The value added to this array here consists of the block and options passed to +after_initialize+.
-h4. +ActionController::Middleware.new+
+We'll see these +@load_hooks+ used later on in the initialization process.
-This +initialize+ method also is in a class who's ancestry is important so once again I'll show the ancestry and we'll go up that particular chain:
+This rest of +i18n_railtie.rb+ defines the protected class methods +include_fallback_modules+, +init_fallbacks+ and +validate_fallbacks+.
-<ruby>
- module ActionController
- class Middleware < Metal
+h4. Back to +activesupport/lib/active_support/railtie.rb+
- ...
+This file defines the +ActiveSupport::Railtie+ constant which like the +I18n::Railtie+ constant just defined, inherits from +Rails::Railtie+ meaning the +inherited+ method would be called again here, including +Rails::Configurable+ into this class. This class makes use of +Rails::Railtie+'s +config+ method again, setting up the configuration options for Active Support.
- def initialize(app)
- super()
- @_app = app
- end
- end
- end
-</ruby>
+Then this Railtie sets up three more initializers:
-Here our method calls +super+ but with a difference: it's passing in no arguments intentionally by putting the two brackets at the end. The method called here is therefore +ActionController::Metal.initialize+.
+* +active_support.initialize_whiny_nils+
+* +active_support.deprecation_behavior+
+* +active_support.initialize_time_zone+
-h4. +ActionController::Metal.initialize+
+We will cover what each of these initializers do when they run.
-This is another subclassed class, this time from +ActionController::AbstractController+ and I'm sure you can guess what that means:
+Once the +active_support/railtie+ file has finished loading the next file required from +railties/lib/rails.rb+ is the +action_dispatch/railtie+.
-<ruby>
- class Metal < AbstractController::Base
+h4. +activesupport/lib/action_dispatch/railtie.rb+
- ...
+This file defines the +ActionDispatch::Railtie+ class, but not before requiring +action_dispatch+.
- def initialize(*)
- @_headers = {}
- super
- end
- end
-</ruby>
+h4. +activesupport/lib/action_dispatch.rb+
-The single +*+ in the argument listing means we can accept any number of arguments, we just don't care what they are.
-
-h4. +AbstractController::Base.initialize+
-
-This may be anti-climatic, but the initialize method here just returns an +AbstractController::Base+ object:
+This file attempts to locate the +active_support+ and +active_model+ libraries by looking a couple of directories back from the current file and then adds the +active_support+ and +active_model+ +lib+ directories to the load path, but only if they aren't already, which they are.
<ruby>
- # Initialize controller with nil formats.
- def initialize #:nodoc:
- @_formats = nil
- end
-</ruby>
-
-h4. +ActionDispatch::MiddlewareStack.use+
-
-Now we're back to this method, from our foray into the depths of how +Middleware.new+ works, we've showed that it is an instance of +AbstractController::Base+. Therefore it does
-
-TODO: ELABORATE ON THIS SECTION, including explaining what all the pieces of middleware do. Then explain how the default_middleware_stack does what it does, whatever that is.
-
-h4. Back to +Rails::Application::Configuration.new+
-
-Now that the first call to this method is complete (+Plugin::Configuration.default+), we can move onto the second call. Here's a refresher of what this method does:
+ activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
+ $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-<ruby>
- def initialize(base = nil)
- if base
- @options = base.options.dup
- @middleware = base.middleware.dup
- else
- @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- @middleware = self.class.default_middleware_stack
- end
- end
+ activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
+ $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
</ruby>
-You'll note now that this method is being called now is +Configuration.new(Plugin::Configuration.default)+ and with the argument, it's going to perform differently than before, this time duplicating the +options+ and +middleware+ of the object it was passed.
-
-TODO: Find out what purpose the +@options+ and +@middleware+ variables serve.
+In effect, these lines only define the +activesupport_path+ and +activemodel_path+ variables and nothing more.
-Finally, a +Rails::Application::Configuration+ object will be returned. On this class there are a couple of +attr_accessor+s and +attr_writer+s defined:
+The next two requires in this file are already done, so they are not run:
<ruby>
- attr_accessor :after_initialize_blocks, :cache_classes, :colorize_logging,
- :consider_all_requests_local, :dependency_loading,
- :load_once_paths, :logger, :plugins,
- :preload_frameworks, :reload_plugins, :serve_static_assets,
- :time_zone, :whiny_nils
-
- attr_writer :cache_store, :controller_paths,
- :database_configuration_file, :eager_load_paths,
- :i18n, :load_paths, :log_level, :log_path, :paths,
- :routes_configuration_file, :view_path
-</ruby>
-
-Along with these are a lot of helper methods, and one of them is +environment_path+:
-
-<ruby>
- def environment_path
- "#{root}/config/environments/#{Rails.env}.rb"
- end
+ require 'active_support'
+ require 'active_support/dependencies/autoload'
</ruby>
-h4. Back to +Rails::Application#require_environment+
-
-Now that we have a +Rails::Application::Configuration+ object for the +config+ method, we call the +environment_path+ which, as we've seen above, just requires the current environment file which in this case is _config/environments/development.rb_. If this file cannot be found, the +LoadError+ +require+ throws will be +rescue+'d and Rails will continue on its merry way.
-
-h4. _config/environments/development.rb_
-
-In a standard Rails application we have this in our _config/environments/development.rb_ file:
+The following require is to +action_pack+ (+activesupport/lib/action_pack.rb+) which has a 22-line copyright notice at the top of it and ends in a simple require to +action_pack/version+. This file, like other +version.rb+ files before it, defines the +ActionPack::VERSION+ constant:
<ruby>
- YourApp::Application.configure do
- # Settings specified here will take precedence over those in config/environment.rb
-
- # In the development environment your application's code is reloaded on
- # every request. This slows down response time but is perfect for development
- # since you don't have to restart the webserver when you make code changes.
- config.cache_classes = false
-
- # Log error messages when you accidentally call methods on nil.
- config.whiny_nils = true
-
- # Show full error reports and disable caching
- config.action_controller.consider_all_requests_local = true
- config.action_view.debug_rjs = true
- config.action_controller.perform_caching = false
+ module ActionPack
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
- # Don't care if the mailer can't send
- config.action_mailer.raise_delivery_errors = false
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
+ end
end
</ruby>
-It's a little bit sneaky here, but +configure+ is +alias+'d to +class_eval+ on subclasses of +Rails::Application+ which of course includes +YourApp::Application+. This means that the code inside the +configure do+ block will be evaled within the context of +YourApp::Application+. The +config+ method here is the one mentioned before: the +Rails::Application::Configuration+ object. The methods on it should look familiar too: they're the ones that had +attr_accessor+ and +attr_writer+ definitions.
+Once +action_pack+ is finished, then +active_model+ is required.
-The ones down the bottom, +config.action_controller+, +config.action_view+ and +config.action_mailer+ aren't defined by +attr_accessor+ or +attr_writer+, rather they're undefined methods and therefore will trigger the +method_missing+ on the +Rails::Application::Configuration+ option.
+h4. +activemodel/lib/active_model.rb+
-h5. config.cache_classes=
-
-The first method call in this file, this tells Rails to not cache the classes for every request. This means for every single request Rails will reload the classes of your application. If you have a lot of classes, this will slow down the request cycle of your application. This is set to +false+ in the _development_ environment, and +true+ in the _test_ & _production_ environments.
-
-h5. config.whiny_nils=
-
-If this is set to +true+, like it is here in the _development_ environment, _activesupport/whiny_nil_ will be +require+'d. Have you ever seen this error:
-
-<ruby>
- Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
-</ruby>
-
-Or perhaps this one?
+This file makes a require to +active_model/version+ which defines the version for Active Model:
<ruby>
- You have a nil object when you didn't expect it!
- You might have expected an instance of Array.
- The error occurred while evaluating nil.flatten!
-</ruby>
-
-If you have, then this is _activesupport/whiny_nil_ at work.
-
-
-h5. The frameworks
-
-As mentioned before, the methods +action_controller+, +action_view+ and +action_mailer+ aren't defined on the +Rails::Application::Configuration+ object, rather they are caught by +method_missing+ which does this:
+ module ActiveModel
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
-<ruby>
- def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? @options[$1] = args.first : @options[$1]
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
-
- super
end
</ruby>
-Whilst this code is not obvious at first, a little bit of further explanation will help you understand. +config_key_regexp+ is another method (a private one, like +method_missing+) defined here:
+Once the +version.rb+ file is loaded, the +ActiveModel+ module has its autoloaded constants defined as well as a sub-module called +ActiveModel::Serializers+ which has autoloads of its own. When the +ActiveModel+ module is closed the +active_support/i18n+ file is required.
-<ruby>
- def config_key_regexp
- bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|')
- /^(#{bits})(?:=)?$/
- end
-</ruby>
+h4. +activesupport/lib/active_support/i18n.rb+
-As is +config_keys+:
+This is where the +i18n+ gem is required and first configured:
<ruby>
- def config_keys
- ([ :active_support, :action_view ] +
- Railtie.plugin_names).map { |n| n.to_s }.uniq
+ begin
+ require 'i18n'
+ require 'active_support/lazy_load_hooks'
+ rescue LoadError => e
+ $stderr.puts "You don't have i18n installed in your application. Please add it to your Gemfile and run bundle install"
+ raise e
end
-</ruby>
-Aha! There we've got mention of +action_view+, but what is in +Railtie.plugin_names+? Most likely in this case the other frameworks.
-
-h5. +Railtie.plugin_names+
-
-I'm going to show you two methods since the third one, +self.plugin_name+, calls the second one, +self.plugins+ and they're right after each other:
-
-<ruby>
- module Rails
- class Railtie
- def self.inherited(klass)
- @plugins ||= []
- @plugins << klass unless klass == Plugin
- end
-
- def self.plugins
- @plugins
- end
-
- def self.plugin_names
- plugins.map { |p| p.plugin_name }
- end
- end
- end
+ I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
</ruby>
-In here we see that we get the +plugin_names+ from a variable called +@plugins+... which we haven't seen yet. Through the power of the wonderful +inherited+ the +@plugins+ variable is populated. +inherited+ is called when a class inherits, or subclasses, from this class. Therefore we can determine that the other classes are probably inheriting or subclassing from +Rails::Railtie+.
+In effect, the +I18n+ module first defined by +i18n_railtie+ is extended by the +i18n+ gem, rather than the other way around. This has no ill effect. They both work on the same way.
-h3. Serving a Request
+This is another spot where +active_support/lazy_load_hooks+ is required, but it has already been required so it's not loaded again.
-Now that your application is fully initialized, it's now ready to start serving requests.
+If +i18n+ cannot be loaded, the user is presented with an error which says that it cannot be loaded and recommends that it's added to the +Gemfile+. However, in a normal Rails application this gem would be loaded.
-h4. _rails server_
+Once it has finished loading, the +I18n.load_path+ method is used to add the +activesupport/lib/active_support/locale/en.yml+ file to I18n's load path. When the translations are loaded in the initialization process, this is one of the files where they will be sourced from.
-For servers running through _rails server_ you may recall that this uses +Rails::Server+ which is a subclass of +Rack::Server+. Previously we covered the initialization process of Rack but not completely up to the point where the server was running. Now that's what we'll do. Back when the +Rack::Server+ class was first covered there was a mention of the +start+ method which we only touched on. It goes a little like this:
+The loading of this file finishes the loading of +active_model+ and so we go back to +action_dispatch+.
-<ruby>
- def start
- if options[:debug]
- $DEBUG = true
- require 'pp'
- p options[:server]
- pp wrapped_app
- pp app
- end
+h4. Back to +activesupport/lib/action_dispatch.rb+
- if options[:warn]
- $-w = true
- end
-
- if includes = options[:include]
- $LOAD_PATH.unshift *includes
- end
-
- if library = options[:require]
- require library
- end
-
- daemonize_app if options[:daemonize]
- write_pid if options[:pid]
- server.run wrapped_app, options
- end
-</ruby>
-
-We were at the point of explaining what +wrapped_app+ was before we dived into the Rails initialization process.Now that we have a +wrapped_app+ we pass it as the first argument to +server.run+. +server+ in this instance is defined like this:
+The remainder of this file requires the +rack+ file from the Rack gem which defines the +Rack+ module. After +rack+, there's autoloads defined for the +Rack+, +ActionDispatch+, +ActionDispatch::Http+, +ActionDispatch::Session+. A new method called +autoload_under+ is used here, and this simply prefixes the files where the modules are autoloaded from with the path specified. For example here:
<ruby>
- def server
- @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default
- end
-</ruby>
-
-Our +options+ Hash is still the default, and there is no +server+ key set in +default_options+, so it will default to +Rack::Handler.default+. This code works like this:
-
-<ruby>
- def self.default(options = {})
- # Guess.
- if ENV.include?("PHP_FCGI_CHILDREN")
- # We already speak FastCGI
- options.delete :File
- options.delete :Port
-
- Rack::Handler::FastCGI
- elsif ENV.include?("REQUEST_METHOD")
- Rack::Handler::CGI
- else
- begin
- Rack::Handler::Mongrel
- rescue LoadError => e
- Rack::Handler::WEBrick
- end
- end
- end
+ autoload_under 'testing' do
+ autoload :Assertions
+ ...
</ruby>
+The +Assertions+ module is in the +action_dispatch/testing+ folder rather than simply +action_dispatch+.
-We don't have +PHP_FCGI_CHILDREN+ in our +ENV+, so it's not going to be +FastCGI+. We also don't have +REQUEST_METHOD+ in there, so it's not going to be +CGI+. If we have Mongrel installed it'll default to that and then finally it'll use WEBrick. For this, we'll assume a bare-bones installation and assume WEBrick. So from this we can determine our default handler is +Rack::Handler::WEBrick+.
+Finally, this file defines a top-level autoload, the +Mime+ constant.
-(side-note: Mongrel doesn't install on 1.9. TODO: How do we format these anyway?)
+h4. Back to +activesupport/lib/action_dispatch/railtie.rb+
-h5. +Rack::Handler::WEBrick+
+After +action_dispatch+ is required in this file, the +ActionDispatch::Railtie+ class is defined and is yet another class that inherits from +Rails::Railtie+. This class defines some initial configuration option defaults for +config.action_dispatch+ before setting up a single initializer called +action_dispatch.configure+.
-This class is subclassed from +WEBrick::HTTPServlet::AbstractServlet+ which is a class that comes with the Ruby standard library. This is the magical class that serves the requests and deals with the comings (requests) and goings (responses) for your server.
+With +action_dispatch/railtie+ now complete, we go back to +railties/lib/rails.rb+.
+h4. Back to +railties/lib/rails.rb+
-+Rack::Server+ has handlers for the request and by default the handler for a _rails server_ server is
+With the Active Support and Action Dispatch railties now both loaded, the rest of this file deals with setting up UTF-8 to be the default encoding for Rails and then finally setting up the +Rails+ module. This module defines useful methods such as +Rails.logger+, +Rails.application+, +Rails.env+, and +Rails.root+.
-h3. Cruft!
+h4. Back to +railties/lib/rails/all.rb+
-The final line of _config/environment.rb_:
+Now that +rails.rb+ is required, the remaining railties are loaded next, beginning with +active_record/railtie+.
-<ruby>
- YourApp::Application.initialize!
-</ruby>
+h4. +activerecord/lib/active_record/railtie.rb+
-gets down to actually initializing the application!
+Before this file gets into the swing of defining the +ActiveRecord::Railtie+ class, there are a couple of files that are required first. The first one of these is +active_record+.
-TODO: Cover the other +config.*+ methods in perhaps a "Bonus" section near the end. If they aren't referenced in a config file they aren't that important, right?
+h4. +activerecord/lib/active_record.rb+
+This file begins by detecting if the +lib+ directories of +active_support+ and +active_model+ are not in the load path and if they aren't then adds them. As we saw back in +action_dispatch.rb+, these directories are already there.
-TODO: This belongs in the guide, I just don't know where yet. Maybe towards the end, since this is really the "final" thing to be done before being able to serve requests.
+The first three requires have already been done by other files and so aren't loaded here, but the 4th require, the one to +arel+ will require the file provided by the Arel gem, which defines the +Arel+ module.
<ruby>
- def build_app(app)
- middleware[options[:environment]].reverse_each do |middleware|
- middleware = middleware.call(self) if middleware.respond_to?(:call)
- next unless middleware
- klass = middleware.shift
- app = klass.new(app, *middleware)
- end
- app
- end
-</ruby>
-
-Because we don't have any middleware for our application, this returns the application itself( Guessing here!! TODO: Investigate if this is really the case.)
-
-Now that we have an app instance, the last line in +start+ calls +server.run wrapped_app, options+. We know what our app is, and that our options are just the default options, so what is +server+? +server+ is this:
-
-<ruby>
- def server
- @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default
- end
+ require 'active_support'
+ require 'active_support/i18n'
+ require 'active_model'
+ require 'arel'
</ruby>
-Since we have default options, the server is obviously going to be +Rack::Handler.default+. The +default+ method goes like this:
+The 5th require in this file is one to +active_record/version+ which defines the +ActiveRecord::VERSION+ constant:
<ruby>
- def self.default(options = {})
- # Guess.
- if ENV.include?("PHP_FCGI_CHILDREN")
- # We already speak FastCGI
- options.delete :File
- options.delete :Port
-
- Rack::Handler::FastCGI
- elsif ENV.include?("REQUEST_METHOD")
- Rack::Handler::CGI
- else
- begin
- Rack::Handler::Mongrel
- rescue LoadError => e
- Rack::Handler::WEBrick
- end
- end
- end
-</ruby>
-
-h3. +Rails::Paths+
-
-
-The +super+ method it references comes from +Rails::Engine::Configuration+ which defines these paths:
+ module ActiveRecord
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
-<ruby>
- def paths
- @paths ||= begin
- paths = Rails::Paths::Root.new(@root)
- paths.app "app", :eager_load => true, :glob => "*"
- paths.app.controllers "app/controllers", :eager_load => true
- paths.app.helpers "app/helpers", :eager_load => true
- paths.app.models "app/models", :eager_load => true
- paths.app.views "app/views"
- paths.lib "lib", :load_path => true
- paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
- paths.lib.templates "lib/templates"
- paths.config "config"
- paths.config.initializers "config/initializers", :glob => "**/*.rb"
- paths.config.locales "config/locales", :glob => "*.{rb,yml}"
- paths.config.routes "config/routes.rb"
- paths
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
</ruby>
-h3. Appendix A
-
-This file is _activesupport/lib/active_support/inflector/inflections.rb_ and defines the +ActiveSupport::Inflector::Inflections+ class which defines the +singularize+, +pluralize+, +humanize+, +tableize+, +titleize+ and +classify+ methods as well as the code to defining how to work out the irregular, singular, plural and human versions of words. These methods are called +irregular+, +singular+, +plural+ and +human+ respectively, as is the Rails way.
+Once these requires are finished, the base for the +ActiveRecord+ module is defined along with its autoloads.
-This file is _activesupport/lib/active_support/inflector/transliterate.rb_ and defines two methods, +transliterate+ and +parameterize+.
-
-This file first requires _activesupport/lib/active_support/core_ext/string/multibyte.rb_, which requires _activesupport/lib/active_support/multibyte.rb_, which subsequently requires _activesupport/core_ext/module/attribute_accessors.rb_. The _attribute_accessors.rb_ file is needed to gain access to the +mattr_accessor+ (module attribute accessor) method, which is called in _active_suport/multibyte.rb_. The file _active_support/multibyte.rb_ also autoloads three other classes:
+Near the end of the file, we see this line:
<ruby>
-module ActiveSupport #:nodoc:
- module Multibyte
- autoload :EncodingError, 'active_support/multibyte/exceptions'
- autoload :Chars, 'active_support/multibyte/chars'
- autoload :Unicode, 'active_support/multibyte/unicode'
- ...
+ ActiveSupport.on_load(:active_record) do
+ Arel::Table.engine = self
end
-end
</ruby>
-There are also these method definitions:
+This will set the engine for +Arel::Table+ to be +ActiveRecord::Base+.
-<ruby>
- # The proxy class returned when calling mb_chars. You can use this accessor to configure your own proxy
- # class so you can support other encodings. See the ActiveSupport::Multibyte::Chars implementation for
- # an example how to do this.
- #
- # Example:
- # ActiveSupport::Multibyte.proxy_class = CharsForUTF32
- def self.proxy_class=(klass)
- @proxy_class = klass
- end
-
- # Returns the currect proxy class
- def self.proxy_class
- @proxy_class ||= ActiveSupport::Multibyte::Chars
- end
-</ruby>
-
-These methods are used in _activesupport/lib/active_support/core_ext/string/multibyte.rb_.
-
-The file _activesupport/lib/active_support/core_ext/string/chars.rb_ defines the default proxy class that will be returned by +mb_chars+.
-
-Because Ruby 1.9's +String+ class has support for multibyte encodings, some methods are defined only for Ruby 1.8:
-
-* +self.wants?+
-* +++
-* +=~+
-* +=~+
-* +center+
-* +include?+
-* +index+
-* +insert+
-* +ljust+
-* +lstrip+, +lstrip!+
-* +ord+
-* +rindex+
-* +rjust+
-* +rstrip+, +rstrip!+
-* +size+
-* +strip+, +strip!+
-
-However, Ruby 1.9 lacks support for some needed operations, so the following methods are defined for both Ruby 1.8 and Ruby 1.9:
-
-* +<=>+
-* +[]=+
-* +capitalize+, +capitalize!+
-* +compose+
-* +decompose+
-* +downcase+, +downcase!+
-* +g_length+
-* +limit+
-* +normalize+
-* +reverse+, +reverse+!
-* +slice+, +slice!+
-* +split+
-* +tidy_bytes+, +tidy_bytes!+
-* +titleize+
-* +upcase+, +upcase!+
+The file then finishes with this line:
<ruby>
- class String
- if RUBY_VERSION >= "1.9"
- def mb_chars
- if ActiveSupport::Multibyte.proxy_class.consumes?(self)
- ActiveSupport::Multibyte.proxy_class.new(self)
- else
- self
- end
- end
-
- def is_utf8? #:nodoc
- case encoding
- when Encoding::UTF_8
- valid_encoding?
- when Encoding::ASCII_8BIT, Encoding::US_ASCII
- dup.force_encoding(Encoding::UTF_8).valid_encoding?
- else
- false
- end
- end
- else
- def mb_chars
- if ActiveSupport::Multibyte.proxy_class.wants?(self)
- ActiveSupport::Multibyte.proxy_class.new(self)
- else
- self
- end
- end
-
- # Returns true if the string has UTF-8 semantics (a String used for purely byte resources is unlikely to have
- # them), returns false otherwise.
- def is_utf8?
- ActiveSupport::Multibyte::Chars.consumes?(self)
- end
- end
+ I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
</ruby>
-As you can see, +mb_chars+ is where the +proxy_class+ property comes in handy. This method will create a new instance of the configured proxy class using the instance of +String+ as a constructor argument. By default, the new +String+-like object will be an instance of the proxy class +ActiveSupport::Multibyte::Chars+. You can use +ActiveSupport::Multibyte.proxy_class=+ to set a different proxy class if you wish.
-
-Here, +mb_chars+ invokes +is_utf8?+ to checks if the string can be treated as UTF-8. On 1.9, the string's +encoding+ property is checked. On 1.8, +wants?+ checks to see if +$KCODE+ is "UTF-8" and, and +consumes?+ checks whether the string can be unpacked as UTF-8 without raising an error.
-
-The keen eye will have seen +ActiveSupport::Multibyte::Chars+ was specified as an +autoload+ earlier: _activesupport/lib/active_support/multibyte/chars.rb_ will be loaded without an explicit +require+ when we call +is_utf8+ on 1.8, or +mb_chars+ on any Ruby version. This file includes _activesupport/lib/active_support/string/access.rb_ which defines methods such as +at+, +from+, +to+, +first+ and +last+. These methods will return parts of the string depending on what is passed to them.
+This will add the translations from +activerecord/lib/active_record/locale/en.yml+ to the load path for +I18n+, with this file being parsed when all the translations are loaded.
-The second file included is _activesupport/lib/active_support/string/behavior.rb_ which only defines +acts_like_string?+ on +String+, a method which always returns +true+. This method is used by +Object#acts_like?+, which accepts a single argument representing the downcased and symbolised version of a class, and returns true if the object's behavior is like that class. In this case the code would be +acts_like?(:string)+.
+h4. Back to +activerecord/lib/active_record/railtie.rb+
-The +Chars+ class also defines other important methods such as the "spaceship" method +<=>+, which is needed by the +Comparable+ module, in order to allow UTF-8-aware sorting.
-
-h3. Common Includes
-
-TODO: I feel this section would be better at the end of the guide as it breaks the flow.
-
-This section is for all the common includes in the Railties.
-
-h4. +require 'active_support/inflector'+
-
-This file is _activesupport/lib/active_support/inflector.rb_ and makes a couple of requires out different files tasked with putting inflections in place:
+The next two <tt>require</tt>s in this file aren't run because their files are already required, with +rails+ being required by +rails/all+ and +active_model/railtie+ being required from +action_dispatch+.
<ruby>
- require 'active_support/inflector/inflections'
- require 'active_support/inflector/transliterate'
- require 'active_support/inflector/methods'
-
- require 'active_support/inflections'
- require 'active_support/core_ext/string/inflections'
+ require "rails"
+ require "active_model/railtie"
</ruby>
-The files included here define methods for modifying strings, such as +transliterate+ which will convert a Unicode string to its ASCII version, +parameterize+ for making strings into url-safe versions, +camelize+ for camel-casing a string such as +string_other+ into +StringOther+ and +ordinalize+ converting a string such as +101+ into +101st+. More information about these methods can be found in the Active Support Core Extensions Guide. TODO: Link to AS Guide.
-
-h4. +require 'active_support/core_ext/module/delegation'+
-
-_activesupport/lib/active_support/core_ext/module/delegation.rb_ defines the +delegate+ method which can be used to delegate methods to other methods in your code. Take the following code example:
+The next +require+ in this file is to +action_controller/railtie+.
-<ruby>
- class Client < ActiveRecord::Base
- has_one :address
-
- delegate :address_line_1, :to => :address
- end
-</ruby>
+h4. +actionpack/lib/action_controller/railtie.rb+
-This defines an +address_line_1+ method which is defined as:
+This file begins with a couple more requires to files that have already been loaded:
<ruby>
- def address_line_1(*args, &block)
- address.__send__(:address_line_1, *args, &block)
- rescue NoMethodError
- if address.nil?
- raise "address_line_1 is delegated to address.address_line_1, but address is nil: #{client.inspect}"
- end
- end
+ require "rails"
+ require "action_controller"
+ require "action_dispatch/railtie"
</ruby>
-h4. +require 'active_support/core_ext/class/attribute_accessors'+
-
-The file, _activesupport/lib/active_support/core_ext/class/attribute_accessors.rb_, defines the class accessor methods +cattr_writer+, +cattr_reader+ and +cattr_accessor+. +cattr_accessor+ defines a +cattr_reader+ and +cattr_writer+ for the symbol passed in. These methods work by defining class variables when you call their dynamic methods.
-
-Throughout the Railties there a couple of common includes. They are listed here for your convenience.
-
-h4. +require 'active_support/core_ext/module/attr_internal+
-
-This file defines three methods +attr_internal_reader+, +attr_internal_writer+ and +attr_internal_accessor+. These work very similar to the +attr_reader+, +attr_writer+ and +attr_accessor+ methods, except the variables they define begin with +@_+. This was done to ensure that they do not clash with variables used people using Rails, as people are less-likely to define say, +@_request+ than they are to define +@request+. An example of where this method is used is for +params+ in the +ActionController::Metal+ class.
-
-h4. +require 'active_support/ruby/shim'+
-
-The _activesupport/lib/active_support/ruby/shim.rb_ file requires methods that have been implemented in Ruby versions greater than 1.9. This is done so you can use Rails 3 on versions earlier than 1.9, such as 1.8.7. These methods are:
-
-* +Date#next_month+
-* +Date#next_year+
-* +DateTime#to_date+
-* +DateTime#to_datetime+
-* +DateTime#xmlschema+
-* +Enumerable#group_by+
-* +Enumerable#each_with_object+
-* +Enumerable#none?+
-* +Process#daemon+
-* +String#ord+
-* +Time#to_date+
-* +Time.to_time+
-* +Time.to_datetime+
+However the require after these is to a file that hasn't yet been loaded, +action_view/railtie+, which begins by requiring +action_view+.
-For more information see the Active Support Core Extensions guide TODO: link to relevant sections for each method.
+h4. +actionpack/lib/action_view.rb+
-And "the REXML security fix detailed here":[http://weblog.rubyonrails.org/2008/8/23/dos-vulnerabilities-in-rexml]
++action_view.rb+
diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb
index bb62506f04..91dab18b21 100644
--- a/railties/guides/source/layout.html.erb
+++ b/railties/guides/source/layout.html.erb
@@ -75,8 +75,8 @@
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
- <dt>Contributing to Rails</dt>
- <dd><a href="contributing_to_rails.html">Contributing to Rails</a></dd>
+ <dt>Contributing to Ruby on Rails</dt>
+ <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
@@ -106,14 +106,14 @@
<div class="wrapper">
<div id="mainCol">
<%= yield.html_safe %>
-
+
<h3>Feedback</h3>
<p>
You're encouraged to help in keeping the quality of this guide.
</p>
<p>
If you see any typos or factual errors you are confident to
- patch please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %>
+ patch, please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %>
and push the change yourself. That branch of Rails has public write access.
Commits are still reviewed, but that happens after you've submitted your
contribution. <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> is
@@ -123,10 +123,10 @@
You may also find incomplete content, or stuff that is not up to date.
Please do add any missing documentation for master. Check the
<%= link_to 'Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html' %>
- guide for style and conventions.
+ for style and conventions.
</p>
<p>
- Issues may also be reported <%= link_to 'in Github', 'https://github.com/lifo/docrails/issues' %>.
+ Issues may also be reported in <%= link_to 'Github', 'https://github.com/lifo/docrails/issues' %>.
</p>
<p>And last but not least, any kind of discussion regarding Ruby on Rails
documentation is very welcome in the <%= link_to 'rubyonrails-docs mailing list', 'http://groups.google.com/group/rubyonrails-docs' %>.
diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile
index 4cdd4f2709..fe400d3358 100644
--- a/railties/guides/source/layouts_and_rendering.textile
+++ b/railties/guides/source/layouts_and_rendering.textile
@@ -211,7 +211,7 @@ h5. Wrapping it up
The above three ways of rendering (rendering another template within the controller, rendering a template within another controller and rendering an arbitrary file on the file system) are actually variants of the same action.
-In fact, in the BooksController class, inside of the edit action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory:
+In fact, in the BooksController class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory:
<ruby>
render :edit
@@ -681,7 +681,7 @@ There are three tag options available for +auto_discovery_link_tag+:
* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically.
* +:title+ specifies the title of the link
-h5. Linking to Javascript Files with +javascript_include_tag+
+h5. Linking to JavaScript Files with +javascript_include_tag+
The +javascript_include_tag+ helper returns an HTML +script+ tag for each source provided. Rails looks in +public/javascripts+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/javascripts/main.js+:
diff --git a/railties/guides/source/nested_model_forms.textile b/railties/guides/source/nested_model_forms.textile
index 1d44da4df1..55694c0eb4 100644
--- a/railties/guides/source/nested_model_forms.textile
+++ b/railties/guides/source/nested_model_forms.textile
@@ -1,6 +1,6 @@
h2. Rails nested model forms
-Creating a form for a model _and_ its associations can become quite tedious. Therefor Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations.
+Creating a form for a model _and_ its associations can become quite tedious. Therefore Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations.
In this guide you will:
@@ -219,4 +219,4 @@ You can basically see the +projects_attributes+ hash as an array of attribute ha
NOTE: The reason that +fields_for+ constructed a form which would result in a hash instead of an array is that it won't work for any forms nested deeper than one level deep.
-TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example. \ No newline at end of file
+TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example.
diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile
index b9401f3559..341525a75c 100644
--- a/railties/guides/source/performance_testing.textile
+++ b/railties/guides/source/performance_testing.textile
@@ -60,8 +60,8 @@ Let's assume your application has the following controller and model:
<ruby>
# routes.rb
-map.root :controller => 'home'
-map.resources :posts
+root :to => 'home#index'
+resources :posts
# home_controller.rb
class HomeController < ApplicationController
@@ -436,7 +436,7 @@ h4. Model
Project.benchmark("Creating project") do
project = Project.create("name" => "stuff")
project.create_manager("name" => "David")
- project.milestones << Milestone.find(:all)
+ project.milestones << Milestone.all
end
</ruby>
diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile
index cb43282ace..f7c4a6f85c 100644
--- a/railties/guides/source/plugins.textile
+++ b/railties/guides/source/plugins.textile
@@ -25,7 +25,7 @@ This guide describes how to build a test-driven plugin that will:
* Add a custom generator command
* A custom route method that can be used in routes.rb
-For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.
+For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.
endprologue.
@@ -33,7 +33,7 @@ h3. Setup
h4. Create the Basic Application
-The examples in this guide require that you have a working rails application. To create a simple one execute:
+The examples in this guide require that you have a working rails application. To create a simple one execute:
<shell>
gem install rails
@@ -45,9 +45,9 @@ rake db:migrate
rails server
</shell>
-Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails application before continuing.
+Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails application before continuing.
-NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails application for other databases see the API docs.
+NOTE: The aforementioned instructions will work for SQLite3. For more detailed instructions on how to create a Rails application for other databases see the API docs.
h4. Generate the Plugin Skeleton
@@ -116,7 +116,7 @@ Now you can add any +require+ statements to +lib/yaffle.rb+ and keep +init.rb+ c
h3. Tests
-In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files:
+In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files:
* A +database.yml+ file with all of your connection strings
* A +schema.rb+ file with your table definitions
@@ -143,7 +143,7 @@ postgresql:
min_messages: ERROR
mysql:
- adapter: mysql
+ adapter: mysql2
host: localhost
username: root
password: password
@@ -268,7 +268,7 @@ Finished in 0.002236 seconds.
1 test, 2 assertion, 0 failures, 0 errors, 0 skips
</shell>
-By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in +database.yml+, pass the DB environment variable to rake:
+By default the setup above runs your tests with SQLite or SQLite3. To run tests with one of the other connection strings specified in +database.yml+, pass the DB environment variable to rake:
<shell>
rake DB=sqlite
@@ -281,9 +281,9 @@ Now you are ready to test-drive your plugin!
h3. Extending Core Classes
-This section will explain how to add a method to String that will be available anywhere in your rails application.
+This section will explain how to add a method to String that will be available anywhere in your Rails application.
-In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions:
+In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions:
<ruby>
# vendor/plugins/yaffle/test/core_ext_test.rb
@@ -345,7 +345,7 @@ $ rails console
h4. Working with +init.rb+
-When Rails loads plugins it looks for a file named +init.rb+. However, when the plugin is initialized, +init.rb+ is invoked via +eval+ (not +require+) so it has slightly different behavior.
+When Rails loads plugins it looks for a file named +init.rb+. However, when the plugin is initialized, +init.rb+ is invoked via +eval+ (not +require+) so it has slightly different behavior.
NOTE: The plugins loader also looks for +rails/init.rb+, but that one is deprecated in favor of the top-level +init.rb+ aforementioned.
@@ -377,7 +377,7 @@ end
h3. Add an "acts_as" Method to Active Record
-A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models.
+A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models.
To begin, set up your files so that you have:
@@ -433,7 +433,7 @@ With structure you can easily separate the methods that will be used for the cla
h4. Add a Class Method
-This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
+This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
To start out, write a failing test that shows the behavior you'd like:
@@ -486,7 +486,7 @@ ActiveRecord::Base.send :include, Yaffle
h4. Add an Instance Method
-This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database.
+This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database.
To start out, write a failing test that shows the behavior you'd like:
@@ -556,11 +556,11 @@ end
ActiveRecord::Base.send :include, Yaffle
</ruby>
-NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+.
+NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+.
h3. Models
-This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:
+This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:
<shell>
vendor/plugins/yaffle/
@@ -594,7 +594,7 @@ class WoodpeckerTest < Test::Unit::TestCase
end
</ruby>
-This is just a simple test to make sure the class is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
+This is just a simple test to make sure the class is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
* *vendor/plugins/yaffle/lib/yaffle.rb:*
@@ -607,7 +607,7 @@ This is just a simple test to make sure the class is being loaded correctly. Af
end
</ruby>
-Adding directories to the load path makes them appear just like files in the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.
+Adding directories to the load path makes them appear just like files in the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.
* *vendor/plugins/yaffle/lib/app/models/woodpecker.rb:*
@@ -630,7 +630,7 @@ Now your test should be passing, and you should be able to use the Woodpecker mo
h3. Controllers
-This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
+This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
You can test your plugin's controller as you would test any other controller:
@@ -661,7 +661,7 @@ class WoodpeckersControllerTest < Test::Unit::TestCase
end
</ruby>
-This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
+This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
* *vendor/plugins/yaffle/lib/yaffle.rb:*
@@ -686,11 +686,11 @@ class WoodpeckersController < ActionController::Base
end
</ruby>
-Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.
+Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.
h3. Helpers
-This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.
+This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.
You can test your plugin's helper as you would test any other helper:
@@ -707,7 +707,7 @@ class WoodpeckersHelperTest < Test::Unit::TestCase
end
</ruby>
-This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
+This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
* *vendor/plugins/yaffle/lib/yaffle.rb:*
@@ -736,9 +736,9 @@ Now your test should be passing, and you should be able to use the Woodpeckers h
h3. Routes
-In a standard 'routes.rb' file you use routes like 'map.connect' or 'map.resources'. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with 'map.yaffles'.
+You can add your own custom routes from a plugin. This section will describe how to add a custom method that can be called with 'map.yaffles'.
-Testing routes from plugins is slightly different from testing routes in a standard rails application. To begin, add a test like this:
+Testing routes from plugins is slightly different from testing routes in a standard Rails application. To begin, add a test like this:
* *vendor/plugins/yaffle/test/routing_test.rb*
@@ -802,20 +802,20 @@ You can also see if your routes work by running +rake routes+ from your app dire
h3. Generators
-Many plugins ship with generators. When you created the plugin above, you specified the +--generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'.
+Many plugins ship with generators. When you created the plugin above, you specified the +--generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'.
Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file.
h4. Testing Generators
-Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
+Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
* Creates a new fake rails root directory that will serve as destination
* Runs the generator
* Asserts that the correct files were generated
* Removes the fake rails root
-This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this:
+This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this:
* *vendor/plugins/yaffle/test/definition_generator_test.rb*
@@ -854,7 +854,7 @@ class DefinitionGeneratorTest < Test::Unit::TestCase
end
</ruby>
-You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
+You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
To make it pass, create the generator:
@@ -872,9 +872,9 @@ end
h4. The +USAGE+ File
-If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file.
+If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file.
-Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:
+Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:
<shell>
rails generate
@@ -899,9 +899,9 @@ Description:
h3. Add a Custom Generator Command
-You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
+You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
-This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file.
+This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file.
To start, add the following test method:
@@ -985,7 +985,7 @@ end
h3. Generator Commands
-You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
+You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'.
@@ -1125,9 +1125,9 @@ NOTE: If you haven't set up the custom route from above, 'rails destroy' will fa
h3. Migrations
-If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins.
+If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins.
-If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration.
+If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration.
Let's say you have the following migration in your plugin:
@@ -1199,12 +1199,12 @@ NOTE: several plugin frameworks such as Desert and Engines provide more advanced
h4. Generate Migrations
-Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this:
+Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this:
* call your rails generate script and pass in whatever options they need
* examine the generated migration, adding/removing columns or other options as necessary
-This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first:
+This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first:
* *vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb*
@@ -1254,7 +1254,7 @@ class MigrationGeneratorTest < Test::Unit::TestCase
end
</ruby>
-NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app.
+NOTE: The migration generator checks to see if a migration already exists, and it's hard-coded to check the +db/migrate+ directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app.
After running the test with 'rake' you can make it pass with:
@@ -1288,9 +1288,9 @@ class YaffleMigrationGenerator < Rails::Generator::NamedBase
end
</ruby>
-The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built-in rails +migration_template+ method, and reuses the built-in rails migration template.
+The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built-in Rails +migration_template+ method, and reuses the built-in rails migration template.
-It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
+It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
To run the generator, type the following at the command line:
@@ -1314,9 +1314,9 @@ class AddYaffleFieldsToBirds < ActiveRecord::Migration
end
</ruby>
-h3. Rake tasks
+h3. Rake Tasks
-When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle_tasks.rake'. Any rake task you add here will be available to the app.
+When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle_tasks.rake'. Any rake task you add here will be available to the app.
Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
@@ -1343,11 +1343,11 @@ Note that tasks from +vendor/plugins/yaffle/Rakefile+ are not available to the m
h3. Plugins as Gems
-Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem.
+Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem.
Rails 3 ignores both <tt>init.rb</tt> and <tt>rails/init.rb</tt> file of a gem. Also, the name of the plugin now is relevant since +config.gem+ tries to load it. Either name the main file after your gem, or document that users should use the +:lib+ option.
-It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in +Rakefile+. A rake task that packages the gem might look like this:
+It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in +Rakefile+. A rake task that packages the gem might look like this:
* *vendor/plugins/yaffle/Rakefile:*
@@ -1395,14 +1395,14 @@ h3. RDoc Documentation
Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
-The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
+The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
* Your name
* How to install
* How to add the functionality to the app (several examples of common use cases)
* Warning, gotchas or tips that might help save users time
-Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api.
+Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api.
Once your comments are good to go, navigate to your plugin directory and run:
@@ -1416,12 +1416,12 @@ If you prefer to use RSpec instead of Test::Unit, you may be interested in the "
h4. References
-* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i
-* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii
-* http://github.com/technoweenie/attachment_fu/tree/master
-* http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
-* http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
-* http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
+* "Complete Guide to Rails Plugins - Part 1":http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i
+* "Complete Guide to Rails Plugins - Part 2":http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii
+* "Attachment_fu Plugin":http://github.com/technoweenie/attachment_fu/tree/master
+* "Keeping init.rb thin":http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
+* "GemPlugins":http://www.mbleigh.com/2008/06/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
+* "Extending Routes":http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2
h4. Contents of +lib/yaffle.rb+
diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile
index d4b887ad02..8f87b4cd58 100644
--- a/railties/guides/source/rails_application_templates.textile
+++ b/railties/guides/source/rails_application_templates.textile
@@ -20,7 +20,7 @@ $ rails new blog -m ~/template.rb
It's also possible to apply a template using a URL :
<shell>
-$ rails new blog -m http://gist.github.com/31208.txt
+$ rails new blog -m https://gist.github.com/755496.txt
</shell>
Alternatively, you can use the rake task +rails:template+ to apply a template to an existing Rails application :
@@ -37,7 +37,7 @@ Rails templates API is very self explanatory and easy to understand. Here's an e
# template.rb
run "rm public/index.html"
generate(:scaffold, "person name:string")
-route "map.root :controller => 'people'"
+route "root :to => 'people#index'"
rake("db:migrate")
git :init
@@ -49,7 +49,7 @@ The following sections outlines the primary methods provided by the API :
h4. gem(name, options = {})
-Adds a +config.gem+ entry for the supplied gem to the generated application’s +config/environment.rb+.
+Adds a +gem+ entry for the supplied gem to the generated application’s +Gemfile+.
For example, if your application depends on the gems +bj+ and +nokogiri+ :
@@ -66,6 +66,16 @@ rake "gems:install"
And let Rails take care of installing the required gems if they’re not already installed.
+h4. add_source(source, options = {})
+
+Adds the given source to the generated application's +Gemfile+.
+
+For example, if you need to source a gem from "http://code.whytheluckystiff.net":
+
+<ruby>
+add_source "http://code.whytheluckystiff.net"
+</ruby>
+
h4. plugin(name, options = {})
Installs a plugin to the generated application.
@@ -183,7 +193,7 @@ h4. route(routing_code)
This adds a routing entry to the +config/routes.rb+ file. In above steps, we generated a person scaffold and also removed +public/index.html+. Now to make +PeopleController#index+ as the default page for the application :
<ruby>
-route "map.root :controller => :person"
+route "root :to => 'person#index'"
</ruby>
h4. inside(dir)
diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile
index f17e9b4798..c1b91da7a8 100644
--- a/railties/guides/source/rails_on_rack.textile
+++ b/railties/guides/source/rails_on_rack.textile
@@ -17,12 +17,7 @@ bq. Rack provides a minimal, modular and adaptable interface for developing web
- "Rack API Documentation":http://rack.rubyforge.org/doc/
-Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the following links:
-
-* "Official Rack Website":http://rack.github.com
-* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html
-* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1
-* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder
+Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the "Resources":#resources section below.
h3. Rails on Rack
@@ -165,7 +160,7 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
|_.Middleware|_.Purpose|
|+Rack::Lock+|Sets +env["rack.multithread"]+ flag to +true+ and wraps the application within a Mutex.|
|+ActionController::Failsafe+|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.|
-|+ActiveRecord::QueryCache+|Enable the Active Record query cache.|
+|+ActiveRecord::QueryCache+|Enables the Active Record query cache.|
|+ActionController::Session::CookieStore+|Uses the cookie based session store.|
|+ActionController::Session::MemCacheStore+|Uses the memcached based session store.|
|+ActiveRecord::SessionStore+|Uses the database based session store.|
@@ -228,8 +223,8 @@ h4. Learning Rack
* "Official Rack Website":http://rack.github.com
* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html
-* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1
-* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder
+* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/ruby-on-rack-1-hello-rack
+* "Ruby on Rack #2 - The Builder":http://m.onkey.org/ruby-on-rack-2-the-builder
h4. Understanding Middlewares
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
index 32346e8f2b..d214031b31 100644
--- a/railties/guides/source/routing.textile
+++ b/railties/guides/source/routing.textile
@@ -85,6 +85,9 @@ creates seven different routes in your application, all mapping to the +Photos+
|PUT |/photos/:id |update |update a specific photo |
|DELETE |/photos/:id |destroy |delete a specific photo |
+
+NOTE: Rails routes are matched in the order they are specified, so if you have a +resources :photos+ above a +get 'photos/poll'+ the +show+ action's route for the +resources+ line will be matched before the +get+ line. To fix this, move the +get+ line *above* the +resources+ line so that it is matched first.
+
h4. Paths and URLs
Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of +resources :photos+:
@@ -388,6 +391,8 @@ NOTE: You can't use +namespace+ or +:module+ with a +:controller+ path segment.
match ':controller(/:action(/:id))', :controller => /admin\/[^\/]+/
</ruby>
+TIP: By default dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment add a constraint which overrides this - for example +:id => /[^\/]+/+ allows anything except a slash.
+
h4. Static Segments
You can specify static segments when creating a route:
@@ -495,7 +500,7 @@ You specify a request-based constraint the same way that you specify a segment c
match "photos", :constraints => {:subdomain => "admin"}
</ruby>
-You can also specify constrains in a block form:
+You can also specify constraints in a block form:
<ruby>
namespace :admin do
@@ -595,7 +600,7 @@ You can specify what Rails should route +"/"+ to with the +root+ method:
root :to => 'pages#main'
</ruby>
-You should put the +root+ route at the end of the file. You also need to delete the public/index.html.erb file for the root route to take effect.
+You should put the +root+ route at the end of the file. You also need to delete the +public/index.html+ file for the root route to take effect.
h3. Customizing Resourceful Routes
@@ -630,7 +635,7 @@ You can use the +:constraints+ option to specify a required format on the implic
resources :photos, :constraints => {:id => /[A-Z][A-Z][0-9]+/}
</ruby>
-This declaration constrains the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match.
+This declaration constraints the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match.
You can specify a single constraint to apply to a number of routes by using the block form:
@@ -643,6 +648,8 @@ end
NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context.
+TIP: By default the +:id+ parameter doesn't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within an +:id+ add a constraint which overrides this - for example +:id => /[^\/]+/+ allows anything except a slash.
+
h4. Overriding the Named Helpers
The +:as+ option lets you override the normal naming for the named route helpers. For example:
@@ -701,7 +708,7 @@ resources :photos
This will provide route helpers such as +admin_photos_path+, +new_admin_photo_path+ etc.
-To prefix a group of routes, use +:as+ with +scope+:
+To prefix a group of route helpers, use +:as+ with +scope+:
<ruby>
scope "admin", :as => "admin" do
@@ -711,8 +718,20 @@ end
resources :photos, :accounts
</ruby>
+This will generate routes such as +admin_photos_path+ and +admin_accounts_path+ which map to +/admin/photos+ and +/admin/accounts+ respectively.
+
NOTE: The +namespace+ scope will automatically add +:as+ as well as +:module+ and +:path+ prefixes.
+You can prefix routes with a named parameter also:
+
+<ruby>
+scope ":username" do
+ resources :posts
+end
+</ruby>
+
+This will provide you with URLs such as +/bob/posts/1+ and will allow you to reference the +username+ part of the path as +params[:username]+ in controllers, helpers and views.
+
h4. Restricting the Routes Created
By default, Rails creates routes for the seven default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option tells Rails to create only the specified routes:
@@ -837,12 +856,6 @@ You can supply a +:method+ argument to specify the HTTP verb:
assert_recognizes({ :controller => "photos", :action => "create" }, { :path => "photos", :method => :post })
</ruby>
-You can also use the resourceful helpers to test recognition of a RESTful route:
-
-<ruby>
-assert_recognizes new_photo_url, { :path => "photos", :method => :post }
-</ruby>
-
h5. The +assert_routing+ Assertion
The +assert_routing+ assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of +assert_generates+ and +assert_recognizes+.
diff --git a/railties/guides/source/ruby_on_rails_guides_guidelines.textile b/railties/guides/source/ruby_on_rails_guides_guidelines.textile
index 0bc409cbda..6576758856 100644
--- a/railties/guides/source/ruby_on_rails_guides_guidelines.textile
+++ b/railties/guides/source/ruby_on_rails_guides_guidelines.textile
@@ -16,7 +16,7 @@ h3. Titles
The title of every guide uses +h2+, guide sections use +h3+, subsections +h4+, etc.
-Capitalize all words except for internal articles, prepositions, conjuctions, and forms of the verb to be:
+Capitalize all words except for internal articles, prepositions, conjunctions, and forms of the verb to be:
<plain>
h5. Middleware Stack is an Array
@@ -45,24 +45,30 @@ h3. HTML Generation
To generate all the guides just cd into the +railties+ directory and execute
<plain>
-rake generate_guides
+bundle exec rake generate_guides
</plain>
-You'll need the gems erubis, i18n, and RedCloth.
+You'll need the gems erubis, i18n, and RedCloth.
To process +my_guide.textile+ and nothing else use the +ONLY+ environment variable:
<plain>
-rake generate_guides ONLY=my_guide
+bundle exec rake generate_guides ONLY=my_guide
</plain>
Although by default guides that have not been modified are not processed, so +ONLY+ is rarely needed in practice.
-To force process of al the guides pass +ALL=1+.
+To force process of all the guides, pass +ALL=1+.
It is also recommended that you work with +WARNINGS=1+, this detects duplicate IDs and warns about broken internal links.
-h3. HTML validation
+If you want to generate guides in languages other than English, you can keep them in a separate directory under +source+ (eg. <tt>source/es</tt>) and use the +LANGUAGE+ environment variable.
+
+<plain>
+rake generate_guides LANGUAGE=es
+</plain>
+
+h3. HTML Validation
Please do validate the generated HTML with
diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile
index fbafc40d93..7f303c3565 100644
--- a/railties/guides/source/security.textile
+++ b/railties/guides/source/security.textile
@@ -616,7 +616,7 @@ h5(#sql-injection-introduction). Introduction
SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query:
<ruby>
-Project.find(:all, :conditions => "name = '#{params[:name]}'")
+Project.all(:conditions => "name = '#{params[:name]}'")
</ruby>
This could be in a search action and the user may enter a project's name that he wants to find. If a malicious user enters ' OR 1 --, the resulting SQL query will be:
@@ -632,7 +632,7 @@ h5. Bypassing Authorization
Usually a web application includes access control. The user enters his login credentials, the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user.
<ruby>
-User.find(:first, "login = '#{params[:name]}' AND password = '#{params[:password]}'")
+User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'")
</ruby>
If an attacker enters ' OR '1'='1 as the name, and ' OR '2'>'1 as the password, the resulting SQL query will be:
@@ -648,7 +648,7 @@ h5. Unauthorized Reading
The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above:
<ruby>
-Project.find(:all, :conditions => "name = '#{params[:name]}'")
+Project.all(:conditions => "name = '#{params[:name]}'")
</ruby>
And now let's inject another query using the UNION statement:
@@ -675,13 +675,13 @@ Ruby on Rails has a built-in filter for special SQL characters, which will escap
Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this:
<ruby>
-Model.find(:first, :conditions => ["login = ? AND password = ?", entered_user_name, entered_password])
+Model.first(:conditions => ["login = ? AND password = ?", entered_user_name, entered_password])
</ruby>
As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result:
<ruby>
-Model.find(:first, :conditions => {:login => entered_user_name, :password => entered_password})
+Model.first(:conditions => {:login => entered_user_name, :password => entered_password})
</ruby>
The array or hash form is only available in model instances. You can try +sanitize_sql()+ elsewhere. _(highlight)Make it a habit to think about the security consequences when using an external string in SQL_.
diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile
index 733c8a755e..a6d70da76c 100644
--- a/railties/guides/source/testing.textile
+++ b/railties/guides/source/testing.textile
@@ -229,13 +229,13 @@ $ rake db:test:load
Above +rake db:migrate+ runs any pending migrations on the _development_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current +db/schema.rb+. On subsequent attempts, it is a good idea to first run +db:test:prepare+, as it first checks for pending migrations and warns you appropriately.
-NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exists.
+NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exist.
h5. Rake Tasks for Preparing your Application for Testing
|_.Tasks |_.Description|
|+rake db:test:clone+ |Recreate the test database from the current environment's database schema|
-|+rake db:test:clone_structure+ |Recreate the test databases from the development structure|
+|+rake db:test:clone_structure+ |Recreate the test database from the development structure|
|+rake db:test:load+ |Recreate the test database from the current +schema.rb+|
|+rake db:test:prepare+ |Check for pending migrations and load the test schema|
|+rake db:test:purge+ |Empty the test database.|
@@ -512,12 +512,12 @@ After a request has been made by using one of the 5 methods (+get+, +post+, etc.
As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for +assigns+. For example:
<ruby>
- flash["gordon"] flash[:gordon]
- session["shmession"] session[:shmession]
- cookies["are_good_for_u"] cookies[:are_good_for_u]
+flash["gordon"] flash[:gordon]
+session["shmession"] session[:shmession]
+cookies["are_good_for_u"] cookies[:are_good_for_u]
# Because you can't use assigns[:something] for historical reasons:
- assigns["something"] assigns(:something)
+assigns["something"] assigns(:something)
</ruby>
h4. Instance Variables Available
@@ -582,7 +582,7 @@ assert_select "ol" do
end
</ruby>
-The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionController/Assertions/SelectorAssertions.html.
+The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html.
h5. Additional View-Based Assertions
diff --git a/railties/guides/w3c_validator.rb b/railties/guides/w3c_validator.rb
index da5200c0b7..f1fe1e0f33 100644
--- a/railties/guides/w3c_validator.rb
+++ b/railties/guides/w3c_validator.rb
@@ -21,7 +21,7 @@
#
# Separate many using commas:
#
-# # validates only
+# # validates only association_basics.html and migrations.html
# ONLY=assoc,migrations rake validate_guides
#
# ---------------------------------------------------------------------------
@@ -88,4 +88,4 @@ module RailsGuides
end
end
-RailsGuides::Validator.new.validate \ No newline at end of file
+RailsGuides::Validator.new.validate
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index 149c63cd9e..9cb3a0f008 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -149,7 +149,10 @@ module Rails
require "action_dispatch/http/rack_cache" if rack_cache
middleware.use ::Rack::Cache, rack_cache if rack_cache
- middleware.use ::ActionDispatch::Static, config.static_asset_paths if config.serve_static_assets
+ if config.serve_static_assets
+ asset_paths = ActiveSupport::OrderedHash[config.static_asset_paths.to_a.reverse]
+ middleware.use ::ActionDispatch::Static, asset_paths
+ end
middleware.use ::Rack::Lock unless config.allow_concurrency
middleware.use ::Rack::Runtime
middleware.use ::Rails::Rack::Logger
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index 8cd496781b..c74bcbedf2 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -6,25 +6,28 @@ module Rails
class Configuration < ::Rails::Engine::Configuration
attr_accessor :allow_concurrency, :asset_host, :cache_classes, :cache_store,
:encoding, :consider_all_requests_local, :dependency_loading,
- :filter_parameters, :helpers_paths, :log_level, :logger,
+ :filter_parameters, :helpers_paths, :logger,
:preload_frameworks, :reload_plugins,
:secret_token, :serve_static_assets, :session_options,
:time_zone, :whiny_nils
+ attr_writer :log_level
+
def initialize(*)
super
self.encoding = "utf-8"
- @allow_concurrency = false
+ @allow_concurrency = false
@consider_all_requests_local = false
- @filter_parameters = []
- @helpers_paths = []
- @dependency_loading = true
- @serve_static_assets = true
- @session_store = :cookie_store
- @session_options = {}
- @time_zone = "UTC"
- @middleware = app_middleware
- @generators = app_generators
+ @filter_parameters = []
+ @helpers_paths = []
+ @dependency_loading = true
+ @serve_static_assets = true
+ @session_store = :cookie_store
+ @session_options = {}
+ @time_zone = "UTC"
+ @log_level = nil
+ @middleware = app_middleware
+ @generators = app_generators
end
def compiled_asset_path
diff --git a/railties/lib/rails/cli.rb b/railties/lib/rails/cli.rb
index 2b32f7edf1..443d6f47ad 100644
--- a/railties/lib/rails/cli.rb
+++ b/railties/lib/rails/cli.rb
@@ -6,7 +6,7 @@ require 'rails/script_rails_loader'
Rails::ScriptRailsLoader.exec_script_rails!
require 'rails/ruby_version_check'
-Signal.trap("INT") { puts; exit }
+Signal.trap("INT") { puts; exit(1) }
if ARGV.first == 'plugin'
ARGV.shift
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
index 46363d7921..02ccdf8060 100644
--- a/railties/lib/rails/commands.rb
+++ b/railties/lib/rails/commands.rb
@@ -62,6 +62,7 @@ when 'application', 'runner'
when 'new'
puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n"
puts "Type 'rails' for help."
+ exit(1)
when '--version', '-v'
ARGV.unshift '--version'
@@ -91,4 +92,5 @@ In addition to those, there are:
All commands can be run with -h for more information.
EOT
+ exit(1)
end
diff --git a/railties/lib/rails/commands/application.rb b/railties/lib/rails/commands/application.rb
index 47c6752ca3..3b57b925ba 100644
--- a/railties/lib/rails/commands/application.rb
+++ b/railties/lib/rails/commands/application.rb
@@ -15,4 +15,16 @@ require 'rubygems' if ARGV.include?("--dev")
require 'rails/generators'
require 'rails/generators/rails/app/app_generator'
+module Rails
+ module Generators
+ class AppGenerator
+ # We want to exit on failure to be kind to other libraries
+ # This is only when accessing via CLI
+ def self.exit_on_failure?
+ true
+ end
+ end
+ end
+end
+
Rails::Generators::AppGenerator.start
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index 14d245ab2e..f0d6ea1687 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -1,4 +1,10 @@
require 'erb'
+
+begin
+ require 'psych'
+rescue LoadError
+end
+
require 'yaml'
require 'optparse'
require 'rbconfig'
@@ -74,7 +80,7 @@ module Rails
exec(find_cmd('mysql', 'mysql5'), *args)
- when "postgresql"
+ when "postgresql", "postgres"
ENV['PGUSER'] = config["username"] if config["username"]
ENV['PGHOST'] = config["host"] if config["host"]
ENV['PGPORT'] = config["port"].to_s if config["port"]
@@ -113,5 +119,5 @@ end
# Has to set the RAILS_ENV before config/application is required
if ARGV.first && !ARGV.first.index("-") && env = ARGV.first
- ENV['RAILS_ENV'] = %w(production development test).find { |e| e.index(env) } || env
+ ENV['RAILS_ENV'] = %w(production development test).detect {|e| e =~ /^#{env}/} || env
end
diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb
index 8b2cd1bdba..048af7cbef 100644
--- a/railties/lib/rails/commands/plugin.rb
+++ b/railties/lib/rails/commands/plugin.rb
@@ -276,12 +276,11 @@ end
require 'optparse'
module Commands
class Plugin
- attr_reader :environment, :script_name, :sources
+ attr_reader :environment, :script_name
def initialize
@environment = RailsEnvironment.default
@rails_root = RailsEnvironment.default.root
@script_name = File.basename($0)
- @sources = []
end
def environment=(value)
@@ -301,8 +300,6 @@ module Commands
o.on("-r", "--root=DIR", String,
"Set an explicit rails app directory.",
"Default: #{@rails_root}") { |rails_root| @rails_root = rails_root; self.environment = RailsEnvironment.new(@rails_root) }
- o.on("-s", "--source=URL1,URL2", Array,
- "Use the specified plugin repositories instead of the defaults.") { |sources| @sources = sources}
o.on("-v", "--verbose", "Turn on verbose output.") { |verbose| $verbose = verbose }
o.on("-h", "--help", "Show this help message.") { puts o; exit }
@@ -315,8 +312,6 @@ module Commands
o.separator ""
o.separator "EXAMPLES"
- o.separator " Install a plugin:"
- o.separator " #{@script_name} plugin install continuous_builder\n"
o.separator " Install a plugin from a subversion URL:"
o.separator " #{@script_name} plugin install http://dev.rubyonrails.com/svn/rails/plugins/continuous_builder\n"
o.separator " Install a plugin from a git URL:"
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index 1d81e08cd3..6e5e842370 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -5,19 +5,20 @@ require 'rbconfig'
require 'rails/engine/railties'
module Rails
- # Rails::Engine allows you to wrap a specific Rails application and share it accross
- # different applications. Since Rails 3.0, every Rails::Application is nothing
- # more than an Engine, allowing you to share it very easily.
+ # Rails::Engine allows you to wrap a specific Rails application and share it across
+ # different applications. Since Rails 3.0, every <tt>Rails::Application</tt> is nothing
+ # more than an engine, allowing you to share it very easily.
#
- # Any Rails::Engine is also a Rails::Railtie, so the same methods (like rake_tasks and
- # generators) and configuration available in the latter can also be used in the former.
+ # Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same methods
+ # (like <tt>rake_tasks</tt> and +generators+) and configuration available in the
+ # latter can also be used in the former.
#
# == Creating an Engine
#
- # In Rails versions before to 3.0, your gems automatically behaved as Engine, however
+ # In Rails versions prior to 3.0, your gems automatically behaved as engines, however,
# this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically
- # behave as Engine, you have to specify an Engine for it somewhere inside your plugin
- # lib folder (similar to how we specify a Railtie):
+ # behave as an engine, you have to specify an +Engine+ for it somewhere inside
+ # your plugin's +lib+ folder (similar to how we specify a +Railtie+):
#
# # lib/my_engine.rb
# module MyEngine
@@ -25,16 +26,17 @@ module Rails
# end
# end
#
- # Then ensure that this file is loaded at the top of your config/application.rb (or in
- # your Gemfile) and it will automatically load models, controllers and helpers
- # inside app, load routes at "config/routes.rb", load locales at "config/locales/*",
- # load tasks at "lib/tasks/*".
+ # Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt>
+ # (or in your +Gemfile+) and it will automatically load models, controllers and helpers
+ # inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at
+ # <tt>config/locales/*</tt>, and load tasks at <tt>lib/tasks/*</tt>.
#
# == Configuration
#
- # Besides the Railtie configuration which is shared across the application, in a
- # Rails::Engine you can access autoload_paths, eager_load_paths and autoload_once_paths,
- # which differently from a Railtie, are scoped to the current Engine.
+ # Besides the +Railtie+ configuration which is shared across the application, in a
+ # <tt>Rails::Engine</tt> you can access <tt>autoload_paths</tt>, <tt>eager_load_paths</tt>
+ # and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to
+ # the current engine.
#
# Example:
#
@@ -49,7 +51,7 @@ module Rails
#
# == Generators
#
- # You can set up generators for engine with config.generators method:
+ # You can set up generators for engines with <tt>config.generators</tt> method:
#
# class MyEngine < Rails::Engine
# config.generators do |g|
@@ -59,7 +61,7 @@ module Rails
# end
# end
#
- # You can also set generators for application by using config.app_generators:
+ # You can also set generators for an application by using <tt>config.app_generators</tt>:
#
# class MyEngine < Rails::Engine
# # note that you can also pass block to app_generators in the same way you
@@ -69,25 +71,25 @@ module Rails
#
# == Paths
#
- # Since Rails 3.0, both your Application and Engines do not have hardcoded paths.
- # This means that you are not required to place your controllers at "app/controllers",
+ # Since Rails 3.0, both your application and engines do not have hardcoded paths.
+ # This means that you are not required to place your controllers at <tt>app/controllers</tt>,
# but in any place which you find convenient.
#
- # For example, let's suppose you want to lay your controllers at lib/controllers, all
- # you need to do is:
+ # For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>.
+ # All you would need to do is:
#
# class MyEngine < Rails::Engine
# paths["app/controllers"] = "lib/controllers"
# end
#
- # You can also have your controllers being loaded from both "app/controllers" and
- # "lib/controllers":
+ # You can also have your controllers loaded from both <tt>app/controllers</tt> and
+ # <tt>lib/controllers</tt>:
#
# class MyEngine < Rails::Engine
# paths["app/controllers"] << "lib/controllers"
# end
#
- # The available paths in an Engine are:
+ # The available paths in an engine are:
#
# class MyEngine < Rails::Engine
# paths["app"] #=> ["app"]
@@ -103,16 +105,17 @@ module Rails
# paths["config/routes"] #=> ["config/routes.rb"]
# end
#
- # Your Application class adds a couple more paths to this set. And as in your Application,
- # all folders under "app" are automatically added to the load path. So if you have
- # "app/observers", it's added by default.
+ # Your <tt>Application</tt> class adds a couple more paths to this set. And as in your
+ # <tt>Application</tt>,all folders under +app+ are automatically added to the load path.
+ # So if you have <tt>app/observers</tt>, it's added by default.
#
# == Endpoint
#
- # Engine can be also a rack application. It can be useful if you have a rack application that
- # you would like to wrap with Engine and provide some of the Engine's features.
+ # An engine can be also a rack application. It can be useful if you have a rack application that
+ # you would like to wrap with +Engine+ and provide some of the +Engine+'s features.
+ #
+ # To do that, use the +endpoint+ method:
#
- # To do that, use endpoint method:
# module MyEngine
# class Engine < Rails::Engine
# endpoint MyRackApplication
@@ -121,14 +124,14 @@ module Rails
#
# Now you can mount your engine in application's routes just like that:
#
- # MyRailsApp::Application.routes.draw do
- # mount MyEngine::Engine => "/engine"
- # end
+ # MyRailsApp::Application.routes.draw do
+ # mount MyEngine::Engine => "/engine"
+ # end
#
# == Middleware stack
#
- # As Engine can now be rack endpoint, it can also have a middleware stack. The usage is exactly
- # the same as in application:
+ # As an engine can now be rack endpoint, it can also have a middleware stack. The usage is exactly
+ # the same as in <tt>Application</tt>:
#
# module MyEngine
# class Engine < Rails::Engine
@@ -138,8 +141,8 @@ module Rails
#
# == Routes
#
- # If you don't specify endpoint, routes will be used as default endpoint. You can use them
- # just like you use application's routes:
+ # If you don't specify an endpoint, routes will be used as the default endpoint. You can use them
+ # just like you use an application's routes:
#
# # ENGINE/config/routes.rb
# MyEngine::Engine.routes.draw do
@@ -148,30 +151,31 @@ module Rails
#
# == Mount priority
#
- # Note that now there can be more than one router in you application and it's better to avoid
- # passing requests through many routers. Consider such situation:
+ # Note that now there can be more than one router in your application, and it's better to avoid
+ # passing requests through many routers. Consider this situation:
#
# MyRailsApp::Application.routes.draw do
# mount MyEngine::Engine => "/blog"
# match "/blog/omg" => "main#omg"
# end
#
- # MyEngine is mounted at "/blog" path and additionaly "/blog/omg" points application's controller.
- # In such situation request to "/blog/omg" will go through MyEngine and if there is no such route
- # in Engine's routes, it will be dispatched to "main#omg". It's much better to swap that:
+ # +MyEngine+ is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's
+ # controller. In such a situation, requests to <tt>/blog/omg</tt> will go through +MyEngine+,
+ # and if there is no such route in +Engine+'s routes, it will be dispatched to <tt>main#omg</tt>.
+ # It's much better to swap that:
#
# MyRailsApp::Application.routes.draw do
# match "/blog/omg" => "main#omg"
# mount MyEngine::Engine => "/blog"
# end
#
- # Now, Engine will get only requests that were not handled by application.
+ # Now, +Engine+ will get only requests that were not handled by +Application+.
#
# == Asset path
#
- # When you use engine with its own public directory, you will probably want to copy or symlink it
- # to application's public directory. To simplify generating paths for assets, you can set asset_path
- # for an Engine:
+ # When you use +Engine+ with its own public directory, you will probably want to copy or symlink it
+ # to application's public directory. To simplify generating paths for assets, you can set <tt>asset_path</tt>
+ # for an engine:
#
# module MyEngine
# class Engine < Rails::Engine
@@ -179,27 +183,30 @@ module Rails
# end
# end
#
- # With such config, asset paths will be automatically modified inside Engine:
- # image_path("foo.jpg") #=> "/my_engine/images/foo.jpg"
+ # With such a config, asset paths will be automatically modified inside +Engine+:
+ #
+ # image_path("foo.jpg") #=> "/my_engine/images/foo.jpg"
#
# == Serving static files
#
- # By default, rails use ActionDispatch::Static to serve static files in development mode. This is ok
- # while you develop your application, but when you want to deploy it, assets from engine will not be
+ # By default, Rails uses <tt>ActionDispatch::Static</tt> to serve static files in development mode. This is ok
+ # while you develop your application, but when you want to deploy it, assets from an engine will not be
# served by default. You should choose one of the two following strategies:
#
# * enable serving static files by setting config.serve_static_assets to true
- # * copy engine's public files to application's public folder with rake ENGINE_NAME:install:assets, for example
- # rake my_engine:install:assets
+ # * copy engine's public files to application's public folder with <tt>rake ENGINE_NAME:install:assets</tt>, for example
+ # <tt>rake my_engine:install:assets</tt>
#
# == Engine name
#
- # There are some places where engine's name is used:
- # * routes: when you mount engine with mount(MyEngine::Engine => '/my_engine'), it's used as default :as option
- # * some of the rake tasks are based on engine name, e.g. my_engine:install:migrations, my_engine:install:assets
+ # There are some places where an Engine's name is used:
+ # * routes: when you mount an Engine with <tt>mount(MyEngine::Engine => '/my_engine')</tt>,
+ # it's used as default :as option
+ # * some of the rake tasks are based on engine name, e.g. <tt>my_engine:install:migrations</tt>,
+ # <tt>my_engine:install:assets</tt>
#
- # Engine name is set by default based on class name. For MyEngine::Engine it will be my_engine_engine.
- # You can change it manually it manually using engine_name method:
+ # Engine name is set by default based on class name. For <tt>MyEngine::Engine</tt> it will be
+ # <tt>my_engine_engine</tt>. You can change it manually it manually using the <tt>engine_name</tt> method:
#
# module MyEngine
# class Engine < Rails::Engine
@@ -209,12 +216,12 @@ module Rails
#
# == Isolated Engine
#
- # Normally when you create controllers, helpers and models inside engine, they are treated
- # as they were created inside the application. This means all applications helpers and named routes
- # will be available to your engine controllers.
+ # Normally when you create controllers, helpers and models inside an engine, they are treated
+ # as they were created inside the application. This means all application helpers and named routes
+ # will be available to your engine's controllers.
#
- # However, sometimes you want to isolate your engine from the application, specially if your engine
- # have its own router. To do that, you simply need to call +isolate_namespace+. This method requires
+ # However, sometimes you want to isolate your engine from the application, especially if your engine
+ # has its own router. To do that, you simply need to call +isolate_namespace+. This method requires
# you to pass a module where all your controllers, helpers and models should be nested to:
#
# module MyEngine
@@ -223,7 +230,8 @@ module Rails
# end
# end
#
- # With such Engine, everything that is inside MyEngine module, will be isolated from application.
+ # With such an engine, everything that is inside the +MyEngine+ module will be isolated from
+ # the application.
#
# Consider such controller:
#
@@ -232,24 +240,24 @@ module Rails
# end
# end
#
- # If engine is marked as isolated, FooController has access only to helpers from engine and
- # url_helpers from MyEngine::Engine.routes.
+ # If an engine is marked as isolated, +FooController+ has access only to helpers from +Engine+ and
+ # <tt>url_helpers</tt> from <tt>MyEngine::Engine.routes</tt>.
#
- # The next thing that changes in isolated engine is routes behaviour. Normally, when you namespace
- # your controllers, you also need to do namespace all your routes. With isolated engine,
+ # The next thing that changes in isolated engines is the behaviour of routes. Normally, when you namespace
+ # your controllers, you also need to do namespace all your routes. With an isolated engine,
# the namespace is applied by default, so you can ignore it in routes:
#
# MyEngine::Engine.routes.draw do
# resources :articles
# end
- #
- # The routes above will automatically point to MyEngine::ApplicationContoller. Further more, you don't
- # need to use longer url helpers like "my_engine_articles_path". Instead, you shuold simply use
- # articles_path as you would do with your application.
- #
- # To make that behaviour consistent with other parts of framework, isolated engine has influence also on
- # ActiveModel::Naming. When you use namespaced model, like MyEngine::Article, it will normally
- # use the prefix "my_engine". In isolated engine, the prefix will be ommited in url helpers and
+ #
+ # The routes above will automatically point to <tt>MyEngine::ApplicationContoller</tt>. Furthermore, you don't
+ # need to use longer url helpers like <tt>my_engine_articles_path</tt>. Instead, you shuold simply use
+ # <tt>articles_path</tt> as you would do with your application.
+ #
+ # To make that behaviour consistent with other parts of the framework, an isolated engine also has influence on
+ # <tt>ActiveModel::Naming</tt>. When you use a namespaced model, like <tt>MyEngine::Article</tt>, it will normally
+ # use the prefix "my_engine". In an isolated engine, the prefix will be ommited in url helpers and
# form fields for convenience.
#
# polymorphic_url(MyEngine::Article.new) #=> "articles_path"
@@ -264,9 +272,9 @@ module Rails
#
# == Using Engine's routes outside Engine
#
- # Since now you can mount engine inside application's routes, you do not have direct access to engine's
- # url_helpers inside application. When you mount Engine in application's routes, a special helper is
- # created to allow you to do that. Consider such scenario:
+ # Since you can now mount an engine inside application's routes, you do not have direct access to +Engine+'s
+ # <tt>url_helpers</tt> inside +Application+. When you mount an engine in an application's routes, a special helper is
+ # created to allow you to do that. Consider such a scenario:
#
# # APP/config/routes.rb
# MyApplication::Application.routes.draw do
@@ -274,7 +282,7 @@ module Rails
# match "/foo" => "foo#index"
# end
#
- # Now, you can use my_engine helper inside your application:
+ # Now, you can use the <tt>my_engine</tt> helper inside your application:
#
# class FooController < ApplicationController
# def index
@@ -282,7 +290,7 @@ module Rails
# end
# end
#
- # There is also 'main_app' helper that gives you access to application's routes inside Engine:
+ # There is also a <tt>main_app</tt> helper that gives you access to application's routes inside Engine:
#
# module MyEngine
# class BarController
@@ -292,34 +300,34 @@ module Rails
# end
# end
#
- # Note that the :as option given to mount takes the engine_name as default, so most of the time
- # you can simply ommit it.
+ # Note that the <tt>:as</tt> option given to mount takes the <tt>engine_name</tT> as default, so most of the time
+ # you can simply omit it.
#
- # Finally, if you want to generate url to engine's route using polymorphic_url, you also need
+ # Finally, if you want to generate a url to an engine's route using <tt>polymorphic_url</tt>, you also need
# to pass the engine helper. Let's say that you want to create a form pointing to one of the
# engine's routes. All you need to do is pass the helper as the first element in array with
# attributes for url:
#
- # form_for([my_engine, @user])
+ # form_for([my_engine, @user])
#
- # This code will use my_engine.user_path(@user) to generate the proper route.
+ # This code will use <tt>my_engine.user_path(@user)</tt> to generate the proper route.
#
# == Migrations & seed data
#
- # Engines can have their own migrations. Default path for migrations is exactly the same
- # as in application: db/migrate
+ # Engines can have their own migrations. The default path for migrations is exactly the same
+ # as in application: <tt>db/migrate</tt>
#
# To use engine's migrations in application you can use rake task, which copies them to
# application's dir:
#
# rake ENGINE_NAME:install:migrations
#
- # Note that some of the migrations may be skipped if migration with the same name already exists
- # in application. In such situation you must decide whether to leave that migration or rename the
+ # Note that some of the migrations may be skipped if a migration with the same name already exists
+ # in application. In such a situation you must decide whether to leave that migration or rename the
# migration in application and rerun copying migrations.
#
# If your engine has migrations, you may also want to prepare data for the database in
- # seeds.rb file. You can load that data using load_seed method, e.g.
+ # the <tt>seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
#
# MyEngine::Engine.load_seed
#
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index 66c4088a68..29e693dfb0 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -155,7 +155,7 @@ module Rails
# commands.
def self.invoke(namespace, args=ARGV, config={})
names = namespace.to_s.split(':')
- if klass = find_by_namespace(names.pop, names.shift)
+ if klass = find_by_namespace(names.pop, names.any? && names.join(':'))
args << "--help" if args.empty? && klass.arguments.any? { |a| a.required? }
klass.start(args, config)
else
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index 7766050632..ab7ed4eb9e 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -112,12 +112,7 @@ module Rails
end
def database_gemfile_entry
- entry = ""
- unless options[:skip_active_record]
- entry = "gem '#{gem_for_database}'"
- entry << ", :require => '#{require_for_database}'" if require_for_database
- end
- entry
+ options[:skip_active_record] ? "" : "gem '#{gem_for_database}'"
end
def rails_gemfile_entry
@@ -150,19 +145,12 @@ gem 'rails', '#{Rails::VERSION::STRING}'
case options[:database]
when "oracle" then "ruby-oci8"
when "postgresql" then "pg"
- when "sqlite3" then "sqlite3-ruby"
when "frontbase" then "ruby-frontbase"
when "mysql" then "mysql2"
else options[:database]
end
end
- def require_for_database
- case options[:database]
- when "sqlite3" then "sqlite3"
- end
- end
-
def bundle_if_dev_or_edge
bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
run "#{bundle_command} install" if dev_or_edge?
diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb
index f97f3db588..131eb6ff6f 100644
--- a/railties/lib/rails/generators/base.rb
+++ b/railties/lib/rails/generators/base.rb
@@ -274,7 +274,7 @@ module Rails
# Use Rails default banner.
#
def self.banner
- "rails generate #{generator_name} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]"
+ "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]".gsub(/\s+/, ' ')
end
# Sets the base_name taking into account the current class namespace.
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 86b9e8f40c..c383d4842f 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -12,13 +12,13 @@ source 'http://rubygems.org'
# To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+)
# gem 'ruby-debug'
-# gem 'ruby-debug19'
+# gem 'ruby-debug19', :require => 'ruby-debug'
# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri'
-# gem 'sqlite3-ruby', :require => 'sqlite3'
-# gem 'aws-s3', :require => 'aws/s3'
+# gem 'sqlite3'
+# gem 'rack-bug', :require => 'rack/bug'
# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
@@ -26,3 +26,6 @@ source 'http://rubygems.org'
# group :development, :test do
# gem 'webrat'
# end
+
+# Needed for guides generation
+# gem "RedCloth", "~> 4.2"
diff --git a/railties/lib/rails/generators/rails/app/templates/README b/railties/lib/rails/generators/rails/app/templates/README
index fe7013d52d..9f0f1d0e38 100644
--- a/railties/lib/rails/generators/rails/app/templates/README
+++ b/railties/lib/rails/generators/rails/app/templates/README
@@ -91,7 +91,7 @@ mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
class WeblogController < ActionController::Base
def index
- @posts = Post.find(:all)
+ @posts = Post.all
debugger
end
end
@@ -139,7 +139,7 @@ To reload your controllers and models after launching the console run
<tt>reload!</tt>
More information about irb can be found at:
-link:http://www.rubycentral.com/pickaxe/irb.html
+link:http://www.rubycentral.org/pickaxe/irb.html
== dbconsole
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml
index 025d62a8d8..90d87cc295 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml
@@ -1,5 +1,5 @@
# SQLite version 3.x
-# gem install sqlite3-ruby (not necessary on OS X Leopard)
+# gem install sqlite3
development:
adapter: sqlite3
database: db/development.sqlite3
diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore
index af64fae5e7..f0fa30c536 100644
--- a/railties/lib/rails/generators/rails/app/templates/gitignore
+++ b/railties/lib/rails/generators/rails/app/templates/gitignore
@@ -1,4 +1,4 @@
.bundle
db/*.sqlite3
log/*.log
-tmp/**/*
+tmp/
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
index a4f114586c..5c99a8d4a8 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
@@ -1,17 +1,17 @@
/*!
- * jQuery JavaScript Library v1.4.4
+ * jQuery JavaScript Library v1.5
* http://jquery.com/
*
- * Copyright 2010, John Resig
+ * Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
- * Copyright 2010, The Dojo Foundation
+ * Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
- * Date: Thu Nov 11 19:04:53 2010 -0500
+ * Date: Mon Jan 31 08:31:29 2011 -0500
*/
(function( window, undefined ) {
@@ -22,7 +22,7 @@ var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
- return new jQuery.fn.init( selector, context );
+ return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
@@ -38,20 +38,13 @@ var jQuery = function( selector, context ) {
// (both of which we optimize for)
quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
- // Is it a simple selector
- isSimple = /^.[^:#\[\.,]*$/,
-
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
- rwhite = /\s/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
- // Check for non-word characters
- rnonword = /\W/,
-
// Check for digits
rdigit = /\d/,
@@ -75,12 +68,15 @@ var jQuery = function( selector, context ) {
// For matching the engine and version of the browser
browserMatch,
-
+
// Has the ready events already been bound?
readyBound = false,
-
- // The functions to execute on DOM ready
- readyList = [],
+
+ // The deferred used on DOM ready
+ readyList,
+
+ // Promise methods
+ promiseMethods = "then done fail isResolved isRejected promise".split( " " ),
// The ready event handler
DOMContentLoaded,
@@ -92,12 +88,13 @@ var jQuery = function( selector, context ) {
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
-
+
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
- init: function( selector, context ) {
+ constructor: jQuery,
+ init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
@@ -111,7 +108,7 @@ jQuery.fn = jQuery.prototype = {
this.length = 1;
return this;
}
-
+
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
@@ -131,6 +128,7 @@ jQuery.fn = jQuery.prototype = {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
+ context = context instanceof jQuery ? context[0] : context;
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
@@ -148,11 +146,11 @@ jQuery.fn = jQuery.prototype = {
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
- selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
+ selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
}
-
+
return jQuery.merge( this, selector );
-
+
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
@@ -176,13 +174,6 @@ jQuery.fn = jQuery.prototype = {
return this;
}
- // HANDLE: $("TAG")
- } else if ( !context && !rnonword.test( selector ) ) {
- this.selector = selector;
- this.context = document;
- selector = document.getElementsByTagName( selector );
- return jQuery.merge( this, selector );
-
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
@@ -190,7 +181,7 @@ jQuery.fn = jQuery.prototype = {
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
- return jQuery( context ).find( selector );
+ return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
@@ -211,7 +202,7 @@ jQuery.fn = jQuery.prototype = {
selector: "",
// The current version of jQuery being used
- jquery: "1.4.4",
+ jquery: "1.5",
// The default length of a jQuery object is 0
length: 0,
@@ -234,18 +225,18 @@ jQuery.fn = jQuery.prototype = {
this.toArray() :
// Return just the object
- ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
+ ( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
- var ret = jQuery();
+ var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
-
+
} else {
jQuery.merge( ret, elems );
}
@@ -271,25 +262,17 @@ jQuery.fn = jQuery.prototype = {
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
-
+
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
- // If the DOM is already ready
- if ( jQuery.isReady ) {
- // Execute the function immediately
- fn.call( document, jQuery );
-
- // Otherwise, remember the function for later
- } else if ( readyList ) {
- // Add the function to the wait list
- readyList.push( fn );
- }
+ // Add the callback
+ readyList.done( fn );
return this;
},
-
+
eq: function( i ) {
return i === -1 ?
this.slice( i ) :
@@ -314,9 +297,9 @@ jQuery.fn = jQuery.prototype = {
return callback.call( elem, i, elem );
}));
},
-
+
end: function() {
- return this.prevObject || jQuery(null);
+ return this.prevObject || this.constructor(null);
},
// For internal use only.
@@ -403,14 +386,14 @@ jQuery.extend({
return jQuery;
},
-
+
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
-
+
// Handle when the DOM is ready
ready: function( wait ) {
// A third-party is pushing the ready event forwards
@@ -434,27 +417,15 @@ jQuery.extend({
}
// If there are functions bound, to execute
- if ( readyList ) {
- // Execute all of them
- var fn,
- i = 0,
- ready = readyList;
-
- // Reset the list of functions
- readyList = null;
-
- while ( (fn = ready[ i++ ]) ) {
- fn.call( document, jQuery );
- }
+ readyList.resolveWith( document, [ jQuery ] );
- // Trigger any bound ready events
- if ( jQuery.fn.trigger ) {
- jQuery( document ).trigger( "ready" ).unbind( "ready" );
- }
+ // Trigger any bound ready events
+ if ( jQuery.fn.trigger ) {
+ jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
}
},
-
+
bindReady: function() {
if ( readyBound ) {
return;
@@ -473,7 +444,7 @@ jQuery.extend({
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
-
+
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
@@ -482,7 +453,7 @@ jQuery.extend({
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", DOMContentLoaded);
-
+
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
@@ -533,20 +504,20 @@ jQuery.extend({
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
-
+
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
-
+
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
-
+
var key;
for ( key in obj ) {}
-
+
return key === undefined || hasOwn.call( obj, key );
},
@@ -556,11 +527,11 @@ jQuery.extend({
}
return true;
},
-
+
error: function( msg ) {
throw msg;
},
-
+
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
@@ -568,7 +539,7 @@ jQuery.extend({
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
-
+
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test(data.replace(rvalidescape, "@")
@@ -585,6 +556,28 @@ jQuery.extend({
}
},
+ // Cross-browser xml parsing
+ // (xml & tmp used internally)
+ parseXML: function( data , xml , tmp ) {
+
+ if ( window.DOMParser ) { // Standard
+ tmp = new DOMParser();
+ xml = tmp.parseFromString( data , "text/xml" );
+ } else { // IE
+ xml = new ActiveXObject( "Microsoft.XMLDOM" );
+ xml.async = "false";
+ xml.loadXML( data );
+ }
+
+ tmp = xml.documentElement;
+
+ if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
+ jQuery.error( "Invalid XML: " + data );
+ }
+
+ return xml;
+ },
+
noop: function() {},
// Evalulates a script in a global context
@@ -597,7 +590,7 @@ jQuery.extend({
script.type = "text/javascript";
- if ( jQuery.support.scriptEval ) {
+ if ( jQuery.support.scriptEval() ) {
script.appendChild( document.createTextNode( data ) );
} else {
script.text = data;
@@ -710,7 +703,7 @@ jQuery.extend({
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
-
+
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
@@ -752,6 +745,7 @@ jQuery.extend({
}
}
+ // Flatten any nested arrays
return ret.concat.apply( [], ret );
},
@@ -790,7 +784,7 @@ jQuery.extend({
// The value/s can be optionally by executed if its a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
-
+
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
@@ -798,19 +792,19 @@ jQuery.extend({
}
return elems;
}
-
+
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
-
+
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
-
+
return elems;
}
-
+
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
@@ -819,6 +813,155 @@ jQuery.extend({
return (new Date()).getTime();
},
+ // Create a simple deferred (one callbacks list)
+ _Deferred: function() {
+ var // callbacks list
+ callbacks = [],
+ // stored [ context , args ]
+ fired,
+ // to avoid firing when already doing so
+ firing,
+ // flag to know if the deferred has been cancelled
+ cancelled,
+ // the deferred itself
+ deferred = {
+
+ // done( f1, f2, ...)
+ done: function() {
+ if ( !cancelled ) {
+ var args = arguments,
+ i,
+ length,
+ elem,
+ type,
+ _fired;
+ if ( fired ) {
+ _fired = fired;
+ fired = 0;
+ }
+ for ( i = 0, length = args.length; i < length; i++ ) {
+ elem = args[ i ];
+ type = jQuery.type( elem );
+ if ( type === "array" ) {
+ deferred.done.apply( deferred, elem );
+ } else if ( type === "function" ) {
+ callbacks.push( elem );
+ }
+ }
+ if ( _fired ) {
+ deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
+ }
+ }
+ return this;
+ },
+
+ // resolve with given context and args
+ resolveWith: function( context, args ) {
+ if ( !cancelled && !fired && !firing ) {
+ firing = 1;
+ try {
+ while( callbacks[ 0 ] ) {
+ callbacks.shift().apply( context, args );
+ }
+ }
+ finally {
+ fired = [ context, args ];
+ firing = 0;
+ }
+ }
+ return this;
+ },
+
+ // resolve with this as context and given arguments
+ resolve: function() {
+ deferred.resolveWith( jQuery.isFunction( this.promise ) ? this.promise() : this, arguments );
+ return this;
+ },
+
+ // Has this deferred been resolved?
+ isResolved: function() {
+ return !!( firing || fired );
+ },
+
+ // Cancel
+ cancel: function() {
+ cancelled = 1;
+ callbacks = [];
+ return this;
+ }
+ };
+
+ return deferred;
+ },
+
+ // Full fledged deferred (two callbacks list)
+ Deferred: function( func ) {
+ var deferred = jQuery._Deferred(),
+ failDeferred = jQuery._Deferred(),
+ promise;
+ // Add errorDeferred methods, then and promise
+ jQuery.extend( deferred, {
+ then: function( doneCallbacks, failCallbacks ) {
+ deferred.done( doneCallbacks ).fail( failCallbacks );
+ return this;
+ },
+ fail: failDeferred.done,
+ rejectWith: failDeferred.resolveWith,
+ reject: failDeferred.resolve,
+ isRejected: failDeferred.isResolved,
+ // Get a promise for this deferred
+ // If obj is provided, the promise aspect is added to the object
+ promise: function( obj , i /* internal */ ) {
+ if ( obj == null ) {
+ if ( promise ) {
+ return promise;
+ }
+ promise = obj = {};
+ }
+ i = promiseMethods.length;
+ while( i-- ) {
+ obj[ promiseMethods[ i ] ] = deferred[ promiseMethods[ i ] ];
+ }
+ return obj;
+ }
+ } );
+ // Make sure only one callback list will be used
+ deferred.then( failDeferred.cancel, deferred.cancel );
+ // Unexpose cancel
+ delete deferred.cancel;
+ // Call given func if any
+ if ( func ) {
+ func.call( deferred, deferred );
+ }
+ return deferred;
+ },
+
+ // Deferred helper
+ when: function( object ) {
+ var args = arguments,
+ length = args.length,
+ deferred = length <= 1 && object && jQuery.isFunction( object.promise ) ?
+ object :
+ jQuery.Deferred(),
+ promise = deferred.promise(),
+ resolveArray;
+
+ if ( length > 1 ) {
+ resolveArray = new Array( length );
+ jQuery.each( args, function( index, element ) {
+ jQuery.when( element ).then( function( value ) {
+ resolveArray[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value;
+ if( ! --length ) {
+ deferred.resolveWith( promise, resolveArray );
+ }
+ }, deferred.reject );
+ } );
+ } else if ( deferred !== object ) {
+ deferred.resolve( object );
+ }
+ return promise;
+ },
+
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
@@ -833,9 +976,33 @@ jQuery.extend({
return { browser: match[1] || "", version: match[2] || "0" };
},
+ sub: function() {
+ function jQuerySubclass( selector, context ) {
+ return new jQuerySubclass.fn.init( selector, context );
+ }
+ jQuery.extend( true, jQuerySubclass, this );
+ jQuerySubclass.superclass = this;
+ jQuerySubclass.fn = jQuerySubclass.prototype = this();
+ jQuerySubclass.fn.constructor = jQuerySubclass;
+ jQuerySubclass.subclass = this.subclass;
+ jQuerySubclass.fn.init = function init( selector, context ) {
+ if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) {
+ context = jQuerySubclass(context);
+ }
+
+ return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass );
+ };
+ jQuerySubclass.fn.init.prototype = jQuerySubclass.fn;
+ var rootjQuerySubclass = jQuerySubclass(document);
+ return jQuerySubclass;
+ },
+
browser: {}
});
+// Create readyList deferred
+readyList = jQuery._Deferred();
+
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
@@ -858,9 +1025,8 @@ if ( indexOf ) {
};
}
-// Verify that \s matches non-breaking spaces
-// (IE fails on this test)
-if ( !rwhite.test( "\xA0" ) ) {
+// IE doesn't match non-breaking spaces with \s
+if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
@@ -914,10 +1080,7 @@ return (window.jQuery = window.$ = jQuery);
jQuery.support = {};
- var root = document.documentElement,
- script = document.createElement("script"),
- div = document.createElement("div"),
- id = "script" + jQuery.now();
+ var div = document.createElement("div");
div.style.display = "none";
div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
@@ -974,7 +1137,7 @@ return (window.jQuery = window.$ = jQuery);
deleteExpando: true,
optDisabled: false,
checkClone: false,
- scriptEval: false,
+ _scriptEval: null,
noCloneEvent: true,
boxModel: null,
inlineBlockNeedsLayout: false,
@@ -987,32 +1150,46 @@ return (window.jQuery = window.$ = jQuery);
select.disabled = true;
jQuery.support.optDisabled = !opt.disabled;
- script.type = "text/javascript";
- try {
- script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
- } catch(e) {}
+ jQuery.support.scriptEval = function() {
+ if ( jQuery.support._scriptEval === null ) {
+ var root = document.documentElement,
+ script = document.createElement("script"),
+ id = "script" + jQuery.now();
- root.insertBefore( script, root.firstChild );
+ script.type = "text/javascript";
+ try {
+ script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
+ } catch(e) {}
- // Make sure that the execution of code works by injecting a script
- // tag with appendChild/createTextNode
- // (IE doesn't support this, fails, and uses .text instead)
- if ( window[ id ] ) {
- jQuery.support.scriptEval = true;
- delete window[ id ];
- }
+ root.insertBefore( script, root.firstChild );
+
+ // Make sure that the execution of code works by injecting a script
+ // tag with appendChild/createTextNode
+ // (IE doesn't support this, fails, and uses .text instead)
+ if ( window[ id ] ) {
+ jQuery.support._scriptEval = true;
+ delete window[ id ];
+ } else {
+ jQuery.support._scriptEval = false;
+ }
+
+ root.removeChild( script );
+ // release memory in IE
+ root = script = id = null;
+ }
+
+ return jQuery.support._scriptEval;
+ };
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
- delete script.test;
+ delete div.test;
} catch(e) {
jQuery.support.deleteExpando = false;
}
- root.removeChild( script );
-
if ( div.attachEvent && div.fireEvent ) {
div.attachEvent("onclick", function click() {
// Cloning a node shouldn't copy over any
@@ -1035,10 +1212,16 @@ return (window.jQuery = window.$ = jQuery);
// Figure out if the W3C box model works as expected
// document.body must exist before we can do this
jQuery(function() {
- var div = document.createElement("div");
- div.style.width = div.style.paddingLeft = "1px";
+ var div = document.createElement("div"),
+ body = document.getElementsByTagName("body")[0];
- document.body.appendChild( div );
+ // Frameset documents with no body should not run this code
+ if ( !body ) {
+ return;
+ }
+
+ div.style.width = div.style.paddingLeft = "1px";
+ body.appendChild( div );
jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
if ( "zoom" in div.style ) {
@@ -1057,7 +1240,7 @@ return (window.jQuery = window.$ = jQuery);
jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2;
}
- div.innerHTML = "<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";
+ div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
var tds = div.getElementsByTagName("td");
// Check if table cells still have offsetWidth/Height when they are set
@@ -1077,7 +1260,7 @@ return (window.jQuery = window.$ = jQuery);
jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0;
div.innerHTML = "";
- document.body.removeChild( div ).style.display = "none";
+ body.removeChild( div ).style.display = "none";
div = tds = null;
});
@@ -1087,6 +1270,14 @@ return (window.jQuery = window.$ = jQuery);
var el = document.createElement("div");
eventName = "on" + eventName;
+ // We only care about the case where non-standard event systems
+ // are used, namely in IE. Short-circuiting here helps us to
+ // avoid an eval call (in setAttribute) which can cause CSP
+ // to go haywire. See: https://developer.mozilla.org/en/Security/CSP
+ if ( !el.attachEvent ) {
+ return true;
+ }
+
var isSupported = (eventName in el);
if ( !isSupported ) {
el.setAttribute(eventName, "return;");
@@ -1101,13 +1292,12 @@ return (window.jQuery = window.$ = jQuery);
jQuery.support.changeBubbles = eventSupported("change");
// release memory in IE
- root = script = div = all = a = null;
+ div = all = a = null;
})();
-var windowData = {},
- rbrace = /^(?:\{.*\}|\[.*\])$/;
+var rbrace = /^(?:\{.*\}|\[.*\])$/;
jQuery.extend({
cache: {},
@@ -1115,8 +1305,9 @@ jQuery.extend({
// Please use with caution
uuid: 0,
- // Unique for each copy of jQuery on the page
- expando: "jQuery" + jQuery.now(),
+ // Unique for each copy of jQuery on the page
+ // Non-digits removed to match rinlinejQuery
+ expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
@@ -1127,103 +1318,171 @@ jQuery.extend({
"applet": true
},
- data: function( elem, name, data ) {
+ hasData: function( elem ) {
+ elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
+
+ return !!elem && !jQuery.isEmptyObject(elem);
+ },
+
+ data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
- elem = elem == window ?
- windowData :
- elem;
+ var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,
- var isNode = elem.nodeType,
- id = isNode ? elem[ jQuery.expando ] : null,
- cache = jQuery.cache, thisCache;
+ // We have to handle DOM nodes and JS objects differently because IE6-7
+ // can't GC object references properly across the DOM-JS boundary
+ isNode = elem.nodeType,
- if ( isNode && !id && typeof name === "string" && data === undefined ) {
+ // Only DOM nodes need the global jQuery cache; JS object data is
+ // attached directly to the object so GC can occur automatically
+ cache = isNode ? jQuery.cache : elem,
+
+ // Only defining an ID for JS objects if its cache already exists allows
+ // the code to shortcut on the same path as a DOM node with no cache
+ id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
+
+ // Avoid doing any more work than we need to when trying to get data on an
+ // object that has no data at all
+ if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) {
return;
}
- // Get the data from the object directly
- if ( !isNode ) {
- cache = elem;
+ if ( !id ) {
+ // Only DOM nodes need a new unique ID for each element since their data
+ // ends up in the global cache
+ if ( isNode ) {
+ elem[ jQuery.expando ] = id = ++jQuery.uuid;
+ } else {
+ id = jQuery.expando;
+ }
+ }
- // Compute a unique ID for the element
- } else if ( !id ) {
- elem[ jQuery.expando ] = id = ++jQuery.uuid;
+ if ( !cache[ id ] ) {
+ cache[ id ] = {};
}
- // Avoid generating a new cache unless none exists and we
- // want to manipulate it.
+ // An object can be passed to jQuery.data instead of a key/value pair; this gets
+ // shallow copied over onto the existing cache
if ( typeof name === "object" ) {
- if ( isNode ) {
+ if ( pvt ) {
+ cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
+ } else {
cache[ id ] = jQuery.extend(cache[ id ], name);
+ }
+ }
- } else {
- jQuery.extend( cache, name );
+ thisCache = cache[ id ];
+
+ // Internal jQuery data is stored in a separate object inside the object's data
+ // cache in order to avoid key collisions between internal data and user-defined
+ // data
+ if ( pvt ) {
+ if ( !thisCache[ internalKey ] ) {
+ thisCache[ internalKey ] = {};
}
- } else if ( isNode && !cache[ id ] ) {
- cache[ id ] = {};
+ thisCache = thisCache[ internalKey ];
}
- thisCache = isNode ? cache[ id ] : cache;
-
- // Prevent overriding the named cache with undefined values
if ( data !== undefined ) {
thisCache[ name ] = data;
}
- return typeof name === "string" ? thisCache[ name ] : thisCache;
+ // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
+ // not attempt to inspect the internal events object using jQuery.data, as this
+ // internal data object is undocumented and subject to change.
+ if ( name === "events" && !thisCache[name] ) {
+ return thisCache[ internalKey ] && thisCache[ internalKey ].events;
+ }
+
+ return getByName ? thisCache[ name ] : thisCache;
},
- removeData: function( elem, name ) {
+ removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
- elem = elem == window ?
- windowData :
- elem;
+ var internalKey = jQuery.expando, isNode = elem.nodeType,
- var isNode = elem.nodeType,
- id = isNode ? elem[ jQuery.expando ] : elem,
- cache = jQuery.cache,
- thisCache = isNode ? cache[ id ] : id;
+ // See jQuery.data for more information
+ cache = isNode ? jQuery.cache : elem,
+
+ // See jQuery.data for more information
+ id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
+
+ // If there is already no cache entry for this object, there is no
+ // purpose in continuing
+ if ( !cache[ id ] ) {
+ return;
+ }
- // If we want to remove a specific section of the element's data
if ( name ) {
+ var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
+
if ( thisCache ) {
- // Remove the section of cache data
delete thisCache[ name ];
- // If we've removed all the data, remove the element's cache
- if ( isNode && jQuery.isEmptyObject(thisCache) ) {
- jQuery.removeData( elem );
+ // If there is no data left in the cache, we want to continue
+ // and let the cache object itself get destroyed
+ if ( !jQuery.isEmptyObject(thisCache) ) {
+ return;
}
}
+ }
+
+ // See jQuery.data for more information
+ if ( pvt ) {
+ delete cache[ id ][ internalKey ];
+
+ // Don't destroy the parent cache unless the internal data object
+ // had been the only thing left in it
+ if ( !jQuery.isEmptyObject(cache[ id ]) ) {
+ return;
+ }
+ }
- // Otherwise, we want to remove all of the element's data
+ var internalCache = cache[ id ][ internalKey ];
+
+ // Browsers that fail expando deletion also refuse to delete expandos on
+ // the window, but it will allow it on all other JS objects; other browsers
+ // don't care
+ if ( jQuery.support.deleteExpando || cache != window ) {
+ delete cache[ id ];
} else {
- if ( isNode && jQuery.support.deleteExpando ) {
- delete elem[ jQuery.expando ];
+ cache[ id ] = null;
+ }
+ // We destroyed the entire user cache at once because it's faster than
+ // iterating through each key, but we need to continue to persist internal
+ // data if it existed
+ if ( internalCache ) {
+ cache[ id ] = {};
+ cache[ id ][ internalKey ] = internalCache;
+
+ // Otherwise, we need to eliminate the expando on the node to avoid
+ // false lookups in the cache for entries that no longer exist
+ } else if ( isNode ) {
+ // IE does not allow us to delete expando properties from nodes,
+ // nor does it have a removeAttribute function on Document nodes;
+ // we must handle all of these cases
+ if ( jQuery.support.deleteExpando ) {
+ delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
-
- // Completely remove the data cache
- } else if ( isNode ) {
- delete cache[ id ];
-
- // Remove all fields from the object
} else {
- for ( var n in elem ) {
- delete elem[ n ];
- }
+ elem[ jQuery.expando ] = null;
}
}
},
+ // For internal use only.
+ _data: function( elem, name, data ) {
+ return jQuery.data( elem, name, data, true );
+ },
+
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
@@ -1244,15 +1503,17 @@ jQuery.fn.extend({
if ( typeof key === "undefined" ) {
if ( this.length ) {
- var attr = this[0].attributes, name;
data = jQuery.data( this[0] );
- for ( var i = 0, l = attr.length; i < l; i++ ) {
- name = attr[i].name;
+ if ( this[0].nodeType === 1 ) {
+ var attr = this[0].attributes, name;
+ for ( var i = 0, l = attr.length; i < l; i++ ) {
+ name = attr[i].name;
- if ( name.indexOf( "data-" ) === 0 ) {
- name = name.substr( 5 );
- dataAttr( this[0], name, data[ name ] );
+ if ( name.indexOf( "data-" ) === 0 ) {
+ name = name.substr( 5 );
+ dataAttr( this[0], name, data[ name ] );
+ }
}
}
}
@@ -1337,7 +1598,7 @@ jQuery.extend({
}
type = (type || "fx") + "queue";
- var q = jQuery.data( elem, type );
+ var q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( !data ) {
@@ -1345,7 +1606,7 @@ jQuery.extend({
}
if ( !q || jQuery.isArray(data) ) {
- q = jQuery.data( elem, type, jQuery.makeArray(data) );
+ q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
@@ -1376,6 +1637,10 @@ jQuery.extend({
jQuery.dequeue(elem, type);
});
}
+
+ if ( !queue.length ) {
+ jQuery.removeData( elem, type + "queue", true );
+ }
}
});
@@ -1425,7 +1690,7 @@ jQuery.fn.extend({
-var rclass = /[\n\t]/g,
+var rclass = /[\n\t\r]/g,
rspaces = /\s+/,
rreturn = /\r/g,
rspecialurl = /^(?:href|src|style)$/,
@@ -1558,11 +1823,11 @@ jQuery.fn.extend({
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
- jQuery.data( this, "__className__", this.className );
+ jQuery._data( this, "__className__", this.className );
}
// toggle whole className
- this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || "";
+ this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
@@ -1607,7 +1872,7 @@ jQuery.fn.extend({
var option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
- if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
+ if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
@@ -1630,7 +1895,6 @@ jQuery.fn.extend({
if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) {
return elem.getAttribute("value") === null ? "on" : elem.value;
}
-
// Everything else, we just grab the value
return (elem.value || "").replace(rreturn, "");
@@ -1696,10 +1960,10 @@ jQuery.extend({
height: true,
offset: true
},
-
+
attr: function( elem, name, value, pass ) {
- // don't set attributes on text and comment nodes
- if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
+ // don't get/set attributes on text, comment and attribute nodes
+ if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || elem.nodeType === 2 ) {
return undefined;
}
@@ -1714,88 +1978,96 @@ jQuery.extend({
// Try to normalize/fix the name
name = notxml && jQuery.props[ name ] || name;
- // These attributes require special treatment
- var special = rspecialurl.test( name );
+ // Only do all the following if this is a node (faster for style)
+ if ( elem.nodeType === 1 ) {
+ // These attributes require special treatment
+ var special = rspecialurl.test( name );
+
+ // Safari mis-reports the default selected property of an option
+ // Accessing the parent's selectedIndex property fixes it
+ if ( name === "selected" && !jQuery.support.optSelected ) {
+ var parent = elem.parentNode;
+ if ( parent ) {
+ parent.selectedIndex;
+
+ // Make sure that it also works with optgroups, see #5701
+ if ( parent.parentNode ) {
+ parent.parentNode.selectedIndex;
+ }
+ }
+ }
- // Safari mis-reports the default selected property of an option
- // Accessing the parent's selectedIndex property fixes it
- if ( name === "selected" && !jQuery.support.optSelected ) {
- var parent = elem.parentNode;
- if ( parent ) {
- parent.selectedIndex;
+ // If applicable, access the attribute via the DOM 0 way
+ // 'in' checks fail in Blackberry 4.7 #6931
+ if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
+ if ( set ) {
+ // We can't allow the type property to be changed (since it causes problems in IE)
+ if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
+ jQuery.error( "type property can't be changed" );
+ }
- // Make sure that it also works with optgroups, see #5701
- if ( parent.parentNode ) {
- parent.parentNode.selectedIndex;
+ if ( value === null ) {
+ if ( elem.nodeType === 1 ) {
+ elem.removeAttribute( name );
+ }
+
+ } else {
+ elem[ name ] = value;
+ }
}
- }
- }
- // If applicable, access the attribute via the DOM 0 way
- // 'in' checks fail in Blackberry 4.7 #6931
- if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
- if ( set ) {
- // We can't allow the type property to be changed (since it causes problems in IE)
- if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
- jQuery.error( "type property can't be changed" );
+ // browsers index elements by id/name on forms, give priority to attributes.
+ if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
+ return elem.getAttributeNode( name ).nodeValue;
}
- if ( value === null ) {
- if ( elem.nodeType === 1 ) {
- elem.removeAttribute( name );
- }
+ // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
+ // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+ if ( name === "tabIndex" ) {
+ var attributeNode = elem.getAttributeNode( "tabIndex" );
- } else {
- elem[ name ] = value;
+ return attributeNode && attributeNode.specified ?
+ attributeNode.value :
+ rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
+ 0 :
+ undefined;
}
- }
- // browsers index elements by id/name on forms, give priority to attributes.
- if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
- return elem.getAttributeNode( name ).nodeValue;
+ return elem[ name ];
}
- // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
- // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
- if ( name === "tabIndex" ) {
- var attributeNode = elem.getAttributeNode( "tabIndex" );
+ if ( !jQuery.support.style && notxml && name === "style" ) {
+ if ( set ) {
+ elem.style.cssText = "" + value;
+ }
- return attributeNode && attributeNode.specified ?
- attributeNode.value :
- rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
- 0 :
- undefined;
+ return elem.style.cssText;
}
- return elem[ name ];
- }
-
- if ( !jQuery.support.style && notxml && name === "style" ) {
if ( set ) {
- elem.style.cssText = "" + value;
+ // convert the value to a string (all browsers do this but IE) see #1070
+ elem.setAttribute( name, "" + value );
}
- return elem.style.cssText;
- }
+ // Ensure that missing attributes return undefined
+ // Blackberry 4.7 returns "" from getAttribute #6938
+ if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
+ return undefined;
+ }
- if ( set ) {
- // convert the value to a string (all browsers do this but IE) see #1070
- elem.setAttribute( name, "" + value );
- }
+ var attr = !jQuery.support.hrefNormalized && notxml && special ?
+ // Some attributes require a special call on IE
+ elem.getAttribute( name, 2 ) :
+ elem.getAttribute( name );
- // Ensure that missing attributes return undefined
- // Blackberry 4.7 returns "" from getAttribute #6938
- if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
- return undefined;
+ // Non-existent attributes return null, we normalize to undefined
+ return attr === null ? undefined : attr;
}
-
- var attr = !jQuery.support.hrefNormalized && notxml && special ?
- // Some attributes require a special call on IE
- elem.getAttribute( name, 2 ) :
- elem.getAttribute( name );
-
- // Non-existent attributes return null, we normalize to undefined
- return attr === null ? undefined : attr;
+ // Handle everything which isn't a DOM element node
+ if ( set ) {
+ elem[ name ] = value;
+ }
+ return elem[ name ];
}
});
@@ -1810,7 +2082,7 @@ var rnamespaces = /\.(.*)$/,
fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&");
},
- focusCounts = { focusin: 0, focusout: 0 };
+ eventKey = "events";
/*
* A number of helper functions used for managing events.
@@ -1852,7 +2124,7 @@ jQuery.event = {
}
// Init the element's event structure
- var elemData = jQuery.data( elem );
+ var elemData = jQuery._data( elem );
// If no elemData is found then we must be trying to bind to one of the
// banned noData elements
@@ -1860,12 +2132,9 @@ jQuery.event = {
return;
}
- // Use a key less likely to result in collisions for plain JS objects.
- // Fixes bug #7150.
- var eventKey = elem.nodeType ? "events" : "__events__",
- events = elemData[ eventKey ],
+ var events = elemData[ eventKey ],
eventHandle = elemData.handle;
-
+
if ( typeof events === "function" ) {
// On plain objects events is a fn that holds the the data
// which prevents this data from being JSON serialized
@@ -1945,9 +2214,9 @@ jQuery.event = {
}
}
}
-
- if ( special.add ) {
- special.add.call( elem, handleObj );
+
+ if ( special.add ) {
+ special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
@@ -1979,14 +2248,13 @@ jQuery.event = {
}
var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
- eventKey = elem.nodeType ? "events" : "__events__",
- elemData = jQuery.data( elem ),
+ elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
events = elemData && elemData[ eventKey ];
if ( !elemData || !events ) {
return;
}
-
+
if ( typeof events === "function" ) {
elemData = events;
events = events.events;
@@ -2024,7 +2292,7 @@ jQuery.event = {
namespaces = type.split(".");
type = namespaces.shift();
- namespace = new RegExp("(^|\\.)" +
+ namespace = new RegExp("(^|\\.)" +
jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
}
@@ -2092,10 +2360,10 @@ jQuery.event = {
delete elemData.handle;
if ( typeof elemData === "function" ) {
- jQuery.removeData( elem, eventKey );
+ jQuery.removeData( elem, eventKey, true );
} else if ( jQuery.isEmptyObject( elemData ) ) {
- jQuery.removeData( elem );
+ jQuery.removeData( elem, undefined, true );
}
}
},
@@ -2127,9 +2395,16 @@ jQuery.event = {
// Only trigger if we've ever bound an event for it
if ( jQuery.event.global[ type ] ) {
+ // XXX This code smells terrible. event.js should not be directly
+ // inspecting the data cache
jQuery.each( jQuery.cache, function() {
- if ( this.events && this.events[type] ) {
- jQuery.event.trigger( event, data, this.handle.elem );
+ // internalKey variable is just used to make it easier to find
+ // and potentially change this stuff later; currently it just
+ // points to jQuery.expando
+ var internalKey = jQuery.expando,
+ internalCache = this[ internalKey ];
+ if ( internalCache && internalCache.events && internalCache.events[type] ) {
+ jQuery.event.trigger( event, data, internalCache.handle.elem );
}
});
}
@@ -2155,8 +2430,8 @@ jQuery.event = {
// Trigger the event, it is assumed that "handle" is a function
var handle = elem.nodeType ?
- jQuery.data( elem, "handle" ) :
- (jQuery.data( elem, "__events__" ) || {}).handle;
+ jQuery._data( elem, "handle" ) :
+ (jQuery._data( elem, eventKey ) || {}).handle;
if ( handle ) {
handle.apply( elem, data );
@@ -2186,7 +2461,7 @@ jQuery.event = {
isClick = jQuery.nodeName( target, "a" ) && targetType === "click",
special = jQuery.event.special[ targetType ] || {};
- if ( (!special._default || special._default.call( elem, event ) === false) &&
+ if ( (!special._default || special._default.call( elem, event ) === false) &&
!isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) {
try {
@@ -2234,7 +2509,7 @@ jQuery.event = {
event.namespace = event.namespace || namespace_sort.join(".");
- events = jQuery.data(this, this.nodeType ? "events" : "__events__");
+ events = jQuery._data(this, eventKey);
if ( typeof events === "function" ) {
events = events.events;
@@ -2256,7 +2531,7 @@ jQuery.event = {
event.handler = handleObj.handler;
event.data = handleObj.data;
event.handleObj = handleObj;
-
+
var ret = handleObj.handler.apply( this, args );
if ( ret !== undefined ) {
@@ -2355,7 +2630,7 @@ jQuery.event = {
add: function( handleObj ) {
jQuery.event.add( this,
liveConvert( handleObj.origType, handleObj.selector ),
- jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
+ jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
},
remove: function( handleObj ) {
@@ -2385,7 +2660,7 @@ jQuery.removeEvent = document.removeEventListener ?
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
- } :
+ } :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
@@ -2402,6 +2677,12 @@ jQuery.Event = function( src ) {
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
+
+ // Events bubbling up the document may have been marked as prevented
+ // by a handler lower down the tree; reflect the correct value.
+ this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
+ src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
+
// Event type
} else {
this.type = src;
@@ -2432,7 +2713,7 @@ jQuery.Event.prototype = {
if ( !e ) {
return;
}
-
+
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
@@ -2518,7 +2799,7 @@ if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces ) {
- if ( this.nodeName.toLowerCase() !== "form" ) {
+ if ( this.nodeName && this.nodeName.toLowerCase() !== "form" ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
@@ -2528,7 +2809,7 @@ if ( !jQuery.support.submitBubbles ) {
return trigger( "submit", this, arguments );
}
});
-
+
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
@@ -2583,14 +2864,14 @@ if ( !jQuery.support.changeBubbles ) {
return;
}
- data = jQuery.data( elem, "_change_data" );
+ data = jQuery._data( elem, "_change_data" );
val = getVal(elem);
// the current data will be also retrieved by beforeactivate
if ( e.type !== "focusout" || elem.type !== "radio" ) {
- jQuery.data( elem, "_change_data", val );
+ jQuery._data( elem, "_change_data", val );
}
-
+
if ( data === undefined || val === data ) {
return;
}
@@ -2604,7 +2885,7 @@ if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
filters: {
- focusout: testChange,
+ focusout: testChange,
beforedeactivate: testChange,
@@ -2633,7 +2914,7 @@ if ( !jQuery.support.changeBubbles ) {
// information
beforeactivate: function( e ) {
var elem = e.target;
- jQuery.data( elem, "_change_data", getVal(elem) );
+ jQuery._data( elem, "_change_data", getVal(elem) );
}
},
@@ -2672,21 +2953,17 @@ if ( document.addEventListener ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
jQuery.event.special[ fix ] = {
setup: function() {
- if ( focusCounts[fix]++ === 0 ) {
- document.addEventListener( orig, handler, true );
- }
+ this.addEventListener( orig, handler, true );
},
teardown: function() {
- if ( --focusCounts[fix] === 0 ) {
- document.removeEventListener( orig, handler, true );
- }
+ this.removeEventListener( orig, handler, true );
}
};
- function handler( e ) {
+ function handler( e ) {
e = jQuery.event.fix( e );
e.type = fix;
- return jQuery.event.trigger( e, null, e.target );
+ return jQuery.event.handle.call( this, e );
}
});
}
@@ -2700,7 +2977,7 @@ jQuery.each(["bind", "one"], function( i, name ) {
}
return this;
}
-
+
if ( jQuery.isFunction( data ) || data === false ) {
fn = data;
data = undefined;
@@ -2740,20 +3017,20 @@ jQuery.fn.extend({
return this;
},
-
+
delegate: function( selector, types, data, fn ) {
return this.live( types, data, fn, selector );
},
-
+
undelegate: function( selector, types, fn ) {
if ( arguments.length === 0 ) {
return this.unbind( "live" );
-
+
} else {
return this.die( types, null, fn, selector );
}
},
-
+
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
@@ -2782,8 +3059,8 @@ jQuery.fn.extend({
return this.click( jQuery.proxy( fn, function( event ) {
// Figure out which function to execute
- var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
- jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
+ var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
+ jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
@@ -2810,12 +3087,12 @@ jQuery.each(["live", "die"], function( i, name ) {
var type, i = 0, match, namespaces, preType,
selector = origSelector || this.selector,
context = origSelector ? this : jQuery( this.context );
-
+
if ( typeof types === "object" && !types.preventDefault ) {
for ( var key in types ) {
context[ name ]( key, data, types[key], selector );
}
-
+
return this;
}
@@ -2862,7 +3139,7 @@ jQuery.each(["live", "die"], function( i, name ) {
context.unbind( "live." + liveConvert( type, selector ), fn );
}
}
-
+
return this;
};
});
@@ -2871,17 +3148,17 @@ function liveHandler( event ) {
var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
elems = [],
selectors = [],
- events = jQuery.data( this, this.nodeType ? "events" : "__events__" );
+ events = jQuery._data( this, eventKey );
if ( typeof events === "function" ) {
events = events.events;
}
- // Make sure we avoid non-left-click bubbling in Firefox (#3861)
- if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) {
+ // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
+ if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
return;
}
-
+
if ( event.namespace ) {
namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
}
@@ -2979,27 +3256,10 @@ jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblcl
}
});
-// Prevent memory leaks in IE
-// Window isn't included so as not to unbind existing unload events
-// More info:
-// - http://isaacschlueter.com/2006/10/msie-memory-leaks/
-if ( window.attachEvent && !window.addEventListener ) {
- jQuery(window).bind("unload", function() {
- for ( var id in jQuery.cache ) {
- if ( jQuery.cache[ id ].handle ) {
- // Try/Catch is to handle iframes being unloaded, see #4280
- try {
- jQuery.event.remove( jQuery.cache[ id ].handle.elem );
- } catch(e) {}
- }
- }
- });
-}
-
/*!
- * Sizzle CSS Selector Engine - v1.0
- * Copyright 2009, The Dojo Foundation
+ * Sizzle CSS Selector Engine
+ * Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
@@ -3220,7 +3480,9 @@ Sizzle.find = function( expr, context, isXML ) {
}
if ( !set ) {
- set = context.getElementsByTagName( "*" );
+ set = typeof context.getElementsByTagName !== "undefined" ?
+ context.getElementsByTagName( "*" ) :
+ [];
}
return { set: set, expr: expr };
@@ -3328,9 +3590,9 @@ var Expr = Sizzle.selectors = {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
- ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
+ ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
- CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
+ CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
@@ -3463,7 +3725,9 @@ var Expr = Sizzle.selectors = {
},
TAG: function( match, context ) {
- return context.getElementsByTagName( match[1] );
+ if ( typeof context.getElementsByTagName !== "undefined" ) {
+ return context.getElementsByTagName( match[1] );
+ }
}
},
preFilter: {
@@ -3476,7 +3740,7 @@ var Expr = Sizzle.selectors = {
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
- if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
+ if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
@@ -3500,8 +3764,14 @@ var Expr = Sizzle.selectors = {
CHILD: function( match ) {
if ( match[1] === "nth" ) {
+ if ( !match[2] ) {
+ Sizzle.error( match[0] );
+ }
+
+ match[2] = match[2].replace(/^\+|\s*/g, '');
+
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
- var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
+ var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
@@ -3509,6 +3779,9 @@ var Expr = Sizzle.selectors = {
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
+ else if ( match[2] ) {
+ Sizzle.error( match[0] );
+ }
// TODO: Move to normal caching system
match[0] = done++;
@@ -3517,12 +3790,15 @@ var Expr = Sizzle.selectors = {
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
- var name = match[1].replace(/\\/g, "");
+ var name = match[1] = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
+ // Handle if an un-quoted value was used
+ match[4] = ( match[4] || match[5] || "" ).replace(/\\/g, "");
+
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
@@ -3691,7 +3967,7 @@ var Expr = Sizzle.selectors = {
return true;
} else {
- Sizzle.error( "Syntax error, unrecognized expression: " + name );
+ Sizzle.error( name );
}
},
@@ -4081,13 +4357,47 @@ if ( document.querySelectorAll ) {
Sizzle = function( query, context, extra, seed ) {
context = context || document;
- // Make sure that attribute selectors are quoted
- query = query.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
-
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
+ // See if we find a selector to speed up
+ var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
+
+ if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
+ // Speed-up: Sizzle("TAG")
+ if ( match[1] ) {
+ return makeArray( context.getElementsByTagName( query ), extra );
+
+ // Speed-up: Sizzle(".CLASS")
+ } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
+ return makeArray( context.getElementsByClassName( match[2] ), extra );
+ }
+ }
+
if ( context.nodeType === 9 ) {
+ // Speed-up: Sizzle("body")
+ // The body element only exists once, optimize finding it
+ if ( query === "body" && context.body ) {
+ return makeArray( [ context.body ], extra );
+
+ // Speed-up: Sizzle("#ID")
+ } else if ( match && match[3] ) {
+ var elem = context.getElementById( match[3] );
+
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ if ( elem && elem.parentNode ) {
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id === match[3] ) {
+ return makeArray( [ elem ], extra );
+ }
+
+ } else {
+ return makeArray( [], extra );
+ }
+ }
+
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
@@ -4098,14 +4408,23 @@ if ( document.querySelectorAll ) {
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var old = context.getAttribute( "id" ),
- nid = old || id;
+ nid = old || id,
+ hasParent = context.parentNode,
+ relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
+ } else {
+ nid = nid.replace( /'/g, "\\$&" );
+ }
+ if ( relativeHierarchySelector && hasParent ) {
+ context = context.parentNode;
}
try {
- return makeArray( context.querySelectorAll( "#" + nid + " " + query ), extra );
+ if ( !relativeHierarchySelector || hasParent ) {
+ return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
+ }
} catch(pseudoError) {
} finally {
@@ -4328,7 +4647,14 @@ var runtil = /Until$/,
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
- POS = jQuery.expr.match.POS;
+ POS = jQuery.expr.match.POS,
+ // methods guaranteed to produce a unique set when starting from a unique set
+ guaranteedUnique = {
+ children: true,
+ contents: true,
+ next: true,
+ prev: true
+ };
jQuery.fn.extend({
find: function( selector ) {
@@ -4373,7 +4699,7 @@ jQuery.fn.extend({
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
-
+
is: function( selector ) {
return !!selector && jQuery.filter( selector, this ).length > 0;
},
@@ -4391,7 +4717,7 @@ jQuery.fn.extend({
selector = selectors[i];
if ( !matches[selector] ) {
- matches[selector] = jQuery.expr.match.POS.test( selector ) ?
+ matches[selector] = jQuery.expr.match.POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
@@ -4414,7 +4740,7 @@ jQuery.fn.extend({
return ret;
}
- var pos = POS.test( selectors ) ?
+ var pos = POS.test( selectors ) ?
jQuery( selectors, context || this.context ) : null;
for ( i = 0, l = this.length; i < l; i++ ) {
@@ -4435,10 +4761,10 @@ jQuery.fn.extend({
}
ret = ret.length > 1 ? jQuery.unique(ret) : ret;
-
+
return this.pushStack( ret, "closest", selectors );
},
-
+
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
@@ -4456,7 +4782,7 @@ jQuery.fn.extend({
add: function( selector, context ) {
var set = typeof selector === "string" ?
- jQuery( selector, context || this.context ) :
+ jQuery( selector, context ) :
jQuery.makeArray( selector ),
all = jQuery.merge( this.get(), set );
@@ -4518,8 +4844,13 @@ jQuery.each({
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
- var ret = jQuery.map( this, fn, until );
-
+ var ret = jQuery.map( this, fn, until ),
+ // The variable 'args' was introduced in
+ // https://github.com/jquery/jquery/commit/52a0238
+ // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
+ // http://code.google.com/p/v8/issues/detail?id=1050
+ args = slice.call(arguments);
+
if ( !runtil.test( name ) ) {
selector = until;
}
@@ -4528,13 +4859,13 @@ jQuery.each({
ret = jQuery.filter( selector, ret );
}
- ret = this.length > 1 ? jQuery.unique( ret ) : ret;
+ ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
- return this.pushStack( ret, name, slice.call(arguments).join(",") );
+ return this.pushStack( ret, name, args.join(",") );
};
});
@@ -4548,7 +4879,7 @@ jQuery.extend({
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
-
+
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
@@ -4630,7 +4961,6 @@ var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rnocache = /<(?:script|object|embed|option|style)/i,
// checked="checked" or checked (html5)
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
- raction = /\=([^="'>\s]+\/)>/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
@@ -4770,7 +5100,7 @@ jQuery.fn.extend({
return set;
}
},
-
+
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
@@ -4785,7 +5115,7 @@ jQuery.fn.extend({
}
}
}
-
+
return this;
},
@@ -4801,48 +5131,17 @@ jQuery.fn.extend({
elem.removeChild( elem.firstChild );
}
}
-
+
return this;
},
- clone: function( events ) {
- // Do the clone
- var ret = this.map(function() {
- if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
- // IE copies events bound via attachEvent when
- // using cloneNode. Calling detachEvent on the
- // clone will also remove the events from the orignal
- // In order to get around this, we use innerHTML.
- // Unfortunately, this means some modifications to
- // attributes in IE that are actually only stored
- // as properties will not be copied (such as the
- // the name attribute on an input).
- var html = this.outerHTML,
- ownerDocument = this.ownerDocument;
-
- if ( !html ) {
- var div = ownerDocument.createElement("div");
- div.appendChild( this.cloneNode(true) );
- html = div.innerHTML;
- }
-
- return jQuery.clean([html.replace(rinlinejQuery, "")
- // Handle the case in IE 8 where action=/test/> self-closes a tag
- .replace(raction, '="$1">')
- .replace(rleadingWhitespace, "")], ownerDocument)[0];
- } else {
- return this.cloneNode(true);
- }
- });
+ clone: function( dataAndEvents, deepDataAndEvents ) {
+ dataAndEvents = dataAndEvents == null ? true : dataAndEvents;
+ deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
- // Copy the events from the original to the clone
- if ( events === true ) {
- cloneCopyEvent( this, ret );
- cloneCopyEvent( this.find("*"), ret.find("*") );
- }
-
- // Return the cloned set
- return ret;
+ return this.map( function () {
+ return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
+ });
},
html: function( value ) {
@@ -4952,9 +5251,9 @@ jQuery.fn.extend({
} else {
results = jQuery.buildFragment( args, this, scripts );
}
-
+
fragment = results.fragment;
-
+
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
@@ -4964,13 +5263,20 @@ jQuery.fn.extend({
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
- for ( var i = 0, l = this.length; i < l; i++ ) {
+ for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
- i > 0 || results.cacheable || this.length > 1 ?
- fragment.cloneNode(true) :
+ // Make sure that we do not leak memory by inadvertently discarding
+ // the original fragment (which might have attached data) instead of
+ // using it; in addition, use the original fragment object for the last
+ // item instead of first because it can end up being emptied incorrectly
+ // in certain situations (Bug #8070).
+ // Fragments from the fragment cache must always be cloned and never used
+ // in place.
+ results.cacheable || (l > 1 && i < lastIndex) ?
+ jQuery.clone( fragment, true, true ) :
fragment
);
}
@@ -4992,41 +5298,97 @@ function root( elem, cur ) {
elem;
}
-function cloneCopyEvent(orig, ret) {
- var i = 0;
+function cloneCopyEvent( src, dest ) {
- ret.each(function() {
- if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
- return;
- }
+ if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
+ return;
+ }
- var oldData = jQuery.data( orig[i++] ),
- curData = jQuery.data( this, oldData ),
- events = oldData && oldData.events;
+ var internalKey = jQuery.expando,
+ oldData = jQuery.data( src ),
+ curData = jQuery.data( dest, oldData );
+
+ // Switch to use the internal data object, if it exists, for the next
+ // stage of data copying
+ if ( (oldData = oldData[ internalKey ]) ) {
+ var events = oldData.events;
+ curData = curData[ internalKey ] = jQuery.extend({}, oldData);
if ( events ) {
delete curData.handle;
curData.events = {};
for ( var type in events ) {
- for ( var handler in events[ type ] ) {
- jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
+ for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
+ jQuery.event.add( dest, type, events[ type ][ i ], events[ type ][ i ].data );
}
}
}
- });
+ }
+}
+
+function cloneFixAttributes(src, dest) {
+ // We do not need to do anything for non-Elements
+ if ( dest.nodeType !== 1 ) {
+ return;
+ }
+
+ var nodeName = dest.nodeName.toLowerCase();
+
+ // clearAttributes removes the attributes, which we don't want,
+ // but also removes the attachEvent events, which we *do* want
+ dest.clearAttributes();
+
+ // mergeAttributes, in contrast, only merges back on the
+ // original attributes, not the events
+ dest.mergeAttributes(src);
+
+ // IE6-8 fail to clone children inside object elements that use
+ // the proprietary classid attribute value (rather than the type
+ // attribute) to identify the type of content to display
+ if ( nodeName === "object" ) {
+ dest.outerHTML = src.outerHTML;
+
+ } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
+ // IE6-8 fails to persist the checked state of a cloned checkbox
+ // or radio button. Worse, IE6-7 fail to give the cloned element
+ // a checked appearance if the defaultChecked value isn't also set
+ if ( src.checked ) {
+ dest.defaultChecked = dest.checked = src.checked;
+ }
+
+ // IE6-7 get confused and end up setting the value of a cloned
+ // checkbox/radio button to an empty string instead of "on"
+ if ( dest.value !== src.value ) {
+ dest.value = src.value;
+ }
+
+ // IE6-8 fails to return the selected option to the default selected
+ // state when cloning options
+ } else if ( nodeName === "option" ) {
+ dest.selected = src.defaultSelected;
+
+ // IE6-8 fails to set the defaultValue to the correct value when
+ // cloning other types of input fields
+ } else if ( nodeName === "input" || nodeName === "textarea" ) {
+ dest.defaultValue = src.defaultValue;
+ }
+
+ // Event data gets referenced instead of copied if the expando
+ // gets copied too
+ dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
- // Only cache "small" (1/2 KB) strings that are associated with the main document
+ // Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
- !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
+ args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ args[0] ];
@@ -5062,24 +5424,72 @@ jQuery.each({
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
-
+
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
-
+
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
-
+
return this.pushStack( ret, name, insert.selector );
}
};
});
jQuery.extend({
+ clone: function( elem, dataAndEvents, deepDataAndEvents ) {
+ var clone = elem.cloneNode(true),
+ srcElements,
+ destElements,
+ i;
+
+ if ( !jQuery.support.noCloneEvent && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
+ // IE copies events bound via attachEvent when using cloneNode.
+ // Calling detachEvent on the clone will also remove the events
+ // from the original. In order to get around this, we use some
+ // proprietary methods to clear the events. Thanks to MooTools
+ // guys for this hotness.
+
+ // Using Sizzle here is crazy slow, so we use getElementsByTagName
+ // instead
+ srcElements = elem.getElementsByTagName("*");
+ destElements = clone.getElementsByTagName("*");
+
+ // Weird iteration because IE will replace the length property
+ // with an element if you are cloning the body and one of the
+ // elements on the page has a name or id of "length"
+ for ( i = 0; srcElements[i]; ++i ) {
+ cloneFixAttributes( srcElements[i], destElements[i] );
+ }
+
+ cloneFixAttributes( elem, clone );
+ }
+
+ // Copy the events from the original to the clone
+ if ( dataAndEvents ) {
+
+ cloneCopyEvent( elem, clone );
+
+ if ( deepDataAndEvents && "getElementsByTagName" in elem ) {
+
+ srcElements = elem.getElementsByTagName("*");
+ destElements = clone.getElementsByTagName("*");
+
+ if ( srcElements.length ) {
+ for ( i = 0; srcElements[i]; ++i ) {
+ cloneCopyEvent( srcElements[i], destElements[i] );
+ }
+ }
+ }
+ }
+ // Return the cloned set
+ return clone;
+ },
clean: function( elems, context, fragment, scripts ) {
context = context || document;
@@ -5161,7 +5571,7 @@ jQuery.extend({
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
-
+
} else {
if ( ret[i].nodeType === 1 ) {
ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
@@ -5173,40 +5583,45 @@ jQuery.extend({
return ret;
},
-
+
cleanData: function( elems ) {
- var data, id, cache = jQuery.cache,
- special = jQuery.event.special,
+ var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
-
+
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
-
+
if ( id ) {
- data = cache[ id ];
-
+ data = cache[ id ] && cache[ id ][ internalKey ];
+
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
+ // This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
+
+ // Null the DOM reference to avoid IE6/7/8 leak (#7054)
+ if ( data.handle ) {
+ data.handle.elem = null;
+ }
}
-
+
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
-
+
delete cache[ id ];
}
}
@@ -5495,8 +5910,9 @@ if ( document.defaultView && document.defaultView.getComputedStyle ) {
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
- var left, rsLeft,
+ var left,
ret = elem.currentStyle && elem.currentStyle[ name ],
+ rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ],
style = elem.style;
// From the awesome hack by Dean Edwards
@@ -5507,16 +5923,19 @@ if ( document.documentElement.currentStyle ) {
if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
// Remember the original values
left = style.left;
- rsLeft = elem.runtimeStyle.left;
// Put in the new values to get a computed value out
- elem.runtimeStyle.left = elem.currentStyle.left;
+ if ( rsLeft ) {
+ elem.runtimeStyle.left = elem.currentStyle.left;
+ }
style.left = name === "fontSize" ? "1em" : (ret || 0);
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
- elem.runtimeStyle.left = rsLeft;
+ if ( rsLeft ) {
+ elem.runtimeStyle.left = rsLeft;
+ }
}
return ret === "" ? "auto" : ret;
@@ -5565,21 +5984,117 @@ if ( jQuery.expr && jQuery.expr.filters ) {
-var jsc = jQuery.now(),
- rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
- rselectTextarea = /^(?:select|textarea)/i,
+var r20 = /%20/g,
+ rbracket = /\[\]$/,
+ rCRLF = /\r?\n/g,
+ rhash = /#.*$/,
+ rheaders = /^(.*?):\s*(.*?)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rnoContent = /^(?:GET|HEAD)$/,
- rbracket = /\[\]$/,
- jsre = /\=\?(&|$)/,
+ rprotocol = /^\/\//,
rquery = /\?/,
+ rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
+ rselectTextarea = /^(?:select|textarea)/i,
+ rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
- rurl = /^(\w+:)?\/\/([^\/?#]+)/,
- r20 = /%20/g,
- rhash = /#.*$/,
+ rurl = /^(\w+:)\/\/([^\/?#:]+)(?::(\d+))?/,
// Keep a copy of the old load method
- _load = jQuery.fn.load;
+ _load = jQuery.fn.load,
+
+ /* Prefilters
+ * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
+ * 2) These are called:
+ * - BEFORE asking for a transport
+ * - AFTER param serialization (s.data is a string if s.processData is true)
+ * 3) key is the dataType
+ * 4) the catchall symbol "*" can be used
+ * 5) execution will start with transport dataType and THEN continue down to "*" if needed
+ */
+ prefilters = {},
+
+ /* Transports bindings
+ * 1) key is the dataType
+ * 2) the catchall symbol "*" can be used
+ * 3) selection will start with transport dataType and THEN go to "*" if needed
+ */
+ transports = {};
+
+// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
+function addToPrefiltersOrTransports( structure ) {
+
+ // dataTypeExpression is optional and defaults to "*"
+ return function( dataTypeExpression, func ) {
+
+ if ( typeof dataTypeExpression !== "string" ) {
+ func = dataTypeExpression;
+ dataTypeExpression = "*";
+ }
+
+ if ( jQuery.isFunction( func ) ) {
+ var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
+ i = 0,
+ length = dataTypes.length,
+ dataType,
+ list,
+ placeBefore;
+
+ // For each dataType in the dataTypeExpression
+ for(; i < length; i++ ) {
+ dataType = dataTypes[ i ];
+ // We control if we're asked to add before
+ // any existing element
+ placeBefore = /^\+/.test( dataType );
+ if ( placeBefore ) {
+ dataType = dataType.substr( 1 ) || "*";
+ }
+ list = structure[ dataType ] = structure[ dataType ] || [];
+ // then we add to the structure accordingly
+ list[ placeBefore ? "unshift" : "push" ]( func );
+ }
+ }
+ };
+}
+
+//Base inspection function for prefilters and transports
+function inspectPrefiltersOrTransports( structure, options, originalOptions, jXHR,
+ dataType /* internal */, inspected /* internal */ ) {
+
+ dataType = dataType || options.dataTypes[ 0 ];
+ inspected = inspected || {};
+
+ inspected[ dataType ] = true;
+
+ var list = structure[ dataType ],
+ i = 0,
+ length = list ? list.length : 0,
+ executeOnly = ( structure === prefilters ),
+ selection;
+
+ for(; i < length && ( executeOnly || !selection ); i++ ) {
+ selection = list[ i ]( options, originalOptions, jXHR );
+ // If we got redirected to another dataType
+ // we try there if not done already
+ if ( typeof selection === "string" ) {
+ if ( inspected[ selection ] ) {
+ selection = undefined;
+ } else {
+ options.dataTypes.unshift( selection );
+ selection = inspectPrefiltersOrTransports(
+ structure, options, originalOptions, jXHR, selection, inspected );
+ }
+ }
+ }
+ // If we're only executing or nothing was selected
+ // we try the catchall dataType if not done already
+ if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
+ selection = inspectPrefiltersOrTransports(
+ structure, options, originalOptions, jXHR, "*", inspected );
+ }
+ // unnecessary when only executing (prefilters)
+ // but it'll be ignored by the caller in that case
+ return selection;
+}
jQuery.fn.extend({
load: function( url, params, callback ) {
@@ -5591,10 +6106,10 @@ jQuery.fn.extend({
return this;
}
- var off = url.indexOf(" ");
+ var off = url.indexOf( " " );
if ( off >= 0 ) {
- var selector = url.slice(off, url.length);
- url = url.slice(0, off);
+ var selector = url.slice( off, url.length );
+ url = url.slice( 0, off );
}
// Default to a GET request
@@ -5623,26 +6138,34 @@ jQuery.fn.extend({
type: type,
dataType: "html",
data: params,
- complete: function( res, status ) {
+ // Complete callback (responseText is used internally)
+ complete: function( jXHR, status, responseText ) {
+ // Store the response as specified by the jXHR object
+ responseText = jXHR.responseText;
// If successful, inject the HTML into all the matched elements
- if ( status === "success" || status === "notmodified" ) {
+ if ( jXHR.isResolved() ) {
+ // #4825: Get the actual response in case
+ // a dataFilter is present in ajaxSettings
+ jXHR.done(function( r ) {
+ responseText = r;
+ });
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
- .append(res.responseText.replace(rscript, ""))
+ .append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
- res.responseText );
+ responseText );
}
if ( callback ) {
- self.each( callback, [res.responseText, status, res] );
+ self.each( callback, [ responseText, status, jXHR ] );
}
}
});
@@ -5651,42 +6174,42 @@ jQuery.fn.extend({
},
serialize: function() {
- return jQuery.param(this.serializeArray());
+ return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
- return this.map(function() {
- return this.elements ? jQuery.makeArray(this.elements) : this;
+ return this.map(function(){
+ return this.elements ? jQuery.makeArray( this.elements ) : this;
})
- .filter(function() {
+ .filter(function(){
return this.name && !this.disabled &&
- (this.checked || rselectTextarea.test(this.nodeName) ||
- rinput.test(this.type));
+ ( this.checked || rselectTextarea.test( this.nodeName ) ||
+ rinput.test( this.type ) );
})
- .map(function( i, elem ) {
- var val = jQuery(this).val();
+ .map(function( i, elem ){
+ var val = jQuery( this ).val();
return val == null ?
null :
- jQuery.isArray(val) ?
- jQuery.map( val, function( val, i ) {
- return { name: elem.name, value: val };
+ jQuery.isArray( val ) ?
+ jQuery.map( val, function( val, i ){
+ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
- { name: elem.name, value: val };
+ { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
-jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
- jQuery.fn[o] = function( f ) {
- return this.bind(o, f);
+jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
+ jQuery.fn[ o ] = function( f ){
+ return this.bind( o, f );
};
-});
+} );
-jQuery.extend({
- get: function( url, data, callback, type ) {
- // shift arguments if data argument was omited
+jQuery.each( [ "get", "post" ], function( i, method ) {
+ jQuery[ method ] = function( url, data, callback, type ) {
+ // shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
@@ -5694,41 +6217,30 @@ jQuery.extend({
}
return jQuery.ajax({
- type: "GET",
+ type: method,
url: url,
data: data,
success: callback,
dataType: type
});
- },
+ };
+} );
+
+jQuery.extend({
getScript: function( url, callback ) {
- return jQuery.get(url, null, callback, "script");
+ return jQuery.get( url, null, callback, "script" );
},
getJSON: function( url, data, callback ) {
- return jQuery.get(url, data, callback, "json");
- },
-
- post: function( url, data, callback, type ) {
- // shift arguments if data argument was omited
- if ( jQuery.isFunction( data ) ) {
- type = type || callback;
- callback = data;
- data = {};
- }
-
- return jQuery.ajax({
- type: "POST",
- url: url,
- data: data,
- success: callback,
- dataType: type
- });
+ return jQuery.get( url, data, callback, "json" );
},
ajaxSetup: function( settings ) {
- jQuery.extend( jQuery.ajaxSettings, settings );
+ jQuery.extend( true, jQuery.ajaxSettings, settings );
+ if ( settings.context ) {
+ jQuery.ajaxSettings.context = settings.context;
+ }
},
ajaxSettings: {
@@ -5741,332 +6253,408 @@ jQuery.extend({
/*
timeout: 0,
data: null,
+ dataType: null,
username: null,
password: null,
+ cache: null,
traditional: false,
+ headers: {},
+ crossDomain: null,
*/
- // This function can be overriden by calling jQuery.ajaxSetup
- xhr: function() {
- return new window.XMLHttpRequest();
- },
+
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
- script: "text/javascript, application/javascript",
- json: "application/json, text/javascript",
text: "text/plain",
- _default: "*/*"
- }
- },
+ json: "application/json, text/javascript",
+ "*": "*/*"
+ },
- ajax: function( origSettings ) {
- var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
- jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type);
+ contents: {
+ xml: /xml/,
+ html: /html/,
+ json: /json/
+ },
- s.url = s.url.replace( rhash, "" );
+ responseFields: {
+ xml: "responseXML",
+ text: "responseText"
+ },
- // Use original (not extended) context object if it was provided
- s.context = origSettings && origSettings.context != null ? origSettings.context : s;
+ // List of data converters
+ // 1) key format is "source_type destination_type" (a single space in-between)
+ // 2) the catchall symbol "*" can be used for source_type
+ converters: {
+
+ // Convert anything to text
+ "* text": window.String,
+
+ // Text to html (true = no transformation)
+ "text html": true,
+
+ // Evaluate text as a json expression
+ "text json": jQuery.parseJSON,
+
+ // Parse text as xml
+ "text xml": jQuery.parseXML
+ }
+ },
+
+ ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
+ ajaxTransport: addToPrefiltersOrTransports( transports ),
+
+ // Main method
+ ajax: function( url, options ) {
+
+ // If options is not an object,
+ // we simulate pre-1.5 signature
+ if ( typeof options !== "object" ) {
+ options = url;
+ url = undefined;
+ }
+
+ // Force options to be an object
+ options = options || {};
+
+ var // Create the final options object
+ s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
+ // Callbacks contexts
+ // We force the original context if it exists
+ // or take it from jQuery.ajaxSettings otherwise
+ // (plain objects used as context get extended)
+ callbackContext =
+ ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
+ globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
+ // Deferreds
+ deferred = jQuery.Deferred(),
+ completeDeferred = jQuery._Deferred(),
+ // Status-dependent callbacks
+ statusCode = s.statusCode || {},
+ // Headers (they are sent all at once)
+ requestHeaders = {},
+ // Response headers
+ responseHeadersString,
+ responseHeaders,
+ // transport
+ transport,
+ // timeout handle
+ timeoutTimer,
+ // Cross-domain detection vars
+ loc = document.location,
+ protocol = loc.protocol || "http:",
+ parts,
+ // The jXHR state
+ state = 0,
+ // Loop variable
+ i,
+ // Fake xhr
+ jXHR = {
+
+ readyState: 0,
+
+ // Caches the header
+ setRequestHeader: function( name, value ) {
+ if ( state === 0 ) {
+ requestHeaders[ name.toLowerCase() ] = value;
+ }
+ return this;
+ },
+
+ // Raw string
+ getAllResponseHeaders: function() {
+ return state === 2 ? responseHeadersString : null;
+ },
+
+ // Builds headers hashtable if needed
+ getResponseHeader: function( key ) {
+ var match;
+ if ( state === 2 ) {
+ if ( !responseHeaders ) {
+ responseHeaders = {};
+ while( ( match = rheaders.exec( responseHeadersString ) ) ) {
+ responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
+ }
+ }
+ match = responseHeaders[ key.toLowerCase() ];
+ }
+ return match || null;
+ },
+
+ // Cancel the request
+ abort: function( statusText ) {
+ statusText = statusText || "abort";
+ if ( transport ) {
+ transport.abort( statusText );
+ }
+ done( 0, statusText );
+ return this;
+ }
+ };
- // convert data if not already a string
- if ( s.data && s.processData && typeof s.data !== "string" ) {
- s.data = jQuery.param( s.data, s.traditional );
- }
+ // Callback for when everything is done
+ // It is defined here because jslint complains if it is declared
+ // at the end of the function (which would be more logical and readable)
+ function done( status, statusText, responses, headers) {
- // Handle JSONP Parameter Callbacks
- if ( s.dataType === "jsonp" ) {
- if ( type === "GET" ) {
- if ( !jsre.test( s.url ) ) {
- s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
- }
- } else if ( !s.data || !jsre.test(s.data) ) {
- s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
+ // Called once
+ if ( state === 2 ) {
+ return;
}
- s.dataType = "json";
- }
- // Build temporary JSONP function
- if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
- jsonp = s.jsonpCallback || ("jsonp" + jsc++);
+ // State is "done" now
+ state = 2;
- // Replace the =? sequence both in the query string and the data
- if ( s.data ) {
- s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
+ // Clear timeout if it exists
+ if ( timeoutTimer ) {
+ clearTimeout( timeoutTimer );
}
- s.url = s.url.replace(jsre, "=" + jsonp + "$1");
+ // Dereference transport for early garbage collection
+ // (no matter how long the jXHR object will be used)
+ transport = undefined;
- // We need to make sure
- // that a JSONP style response is executed properly
- s.dataType = "script";
+ // Cache response headers
+ responseHeadersString = headers || "";
- // Handle JSONP-style loading
- var customJsonp = window[ jsonp ];
+ // Set readyState
+ jXHR.readyState = status ? 4 : 0;
- window[ jsonp ] = function( tmp ) {
- if ( jQuery.isFunction( customJsonp ) ) {
- customJsonp( tmp );
+ var isSuccess,
+ success,
+ error,
+ response = responses ? ajaxHandleResponses( s, jXHR, responses ) : undefined,
+ lastModified,
+ etag;
- } else {
- // Garbage collect
- window[ jsonp ] = undefined;
+ // If successful, handle type chaining
+ if ( status >= 200 && status < 300 || status === 304 ) {
- try {
- delete window[ jsonp ];
- } catch( jsonpError ) {}
- }
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
- data = tmp;
- jQuery.handleSuccess( s, xhr, status, data );
- jQuery.handleComplete( s, xhr, status, data );
-
- if ( head ) {
- head.removeChild( script );
+ if ( ( lastModified = jXHR.getResponseHeader( "Last-Modified" ) ) ) {
+ jQuery.lastModified[ s.url ] = lastModified;
+ }
+ if ( ( etag = jXHR.getResponseHeader( "Etag" ) ) ) {
+ jQuery.etag[ s.url ] = etag;
+ }
}
- };
- }
- if ( s.dataType === "script" && s.cache === null ) {
- s.cache = false;
- }
+ // If not modified
+ if ( status === 304 ) {
- if ( s.cache === false && noContent ) {
- var ts = jQuery.now();
+ statusText = "notmodified";
+ isSuccess = true;
- // try replacing _= if it is there
- var ret = s.url.replace(rts, "$1_=" + ts);
+ // If we have data
+ } else {
- // if nothing was replaced, add timestamp to the end
- s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
- }
+ try {
+ success = ajaxConvert( s, response );
+ statusText = "success";
+ isSuccess = true;
+ } catch(e) {
+ // We have a parsererror
+ statusText = "parsererror";
+ error = e;
+ }
+ }
+ } else {
+ // We extract error from statusText
+ // then normalize statusText and status for non-aborts
+ error = statusText;
+ if( status ) {
+ statusText = "error";
+ if ( status < 0 ) {
+ status = 0;
+ }
+ }
+ }
- // If data is available, append data to url for GET/HEAD requests
- if ( s.data && noContent ) {
- s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
- }
+ // Set data for the fake xhr object
+ jXHR.status = status;
+ jXHR.statusText = statusText;
- // Watch for a new set of requests
- if ( s.global && jQuery.active++ === 0 ) {
- jQuery.event.trigger( "ajaxStart" );
- }
+ // Success/Error
+ if ( isSuccess ) {
+ deferred.resolveWith( callbackContext, [ success, statusText, jXHR ] );
+ } else {
+ deferred.rejectWith( callbackContext, [ jXHR, statusText, error ] );
+ }
- // Matches an absolute URL, and saves the domain
- var parts = rurl.exec( s.url ),
- remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host);
+ // Status-dependent callbacks
+ jXHR.statusCode( statusCode );
+ statusCode = undefined;
- // If we're requesting a remote document
- // and trying to load JSON or Script with a GET
- if ( s.dataType === "script" && type === "GET" && remote ) {
- var head = document.getElementsByTagName("head")[0] || document.documentElement;
- var script = document.createElement("script");
- if ( s.scriptCharset ) {
- script.charset = s.scriptCharset;
+ if ( s.global ) {
+ globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
+ [ jXHR, s, isSuccess ? success : error ] );
}
- script.src = s.url;
- // Handle Script loading
- if ( !jsonp ) {
- var done = false;
+ // Complete
+ completeDeferred.resolveWith( callbackContext, [ jXHR, statusText ] );
- // Attach handlers for all browsers
- script.onload = script.onreadystatechange = function() {
- if ( !done && (!this.readyState ||
- this.readyState === "loaded" || this.readyState === "complete") ) {
- done = true;
- jQuery.handleSuccess( s, xhr, status, data );
- jQuery.handleComplete( s, xhr, status, data );
+ if ( s.global ) {
+ globalEventContext.trigger( "ajaxComplete", [ jXHR, s] );
+ // Handle the global AJAX counter
+ if ( !( --jQuery.active ) ) {
+ jQuery.event.trigger( "ajaxStop" );
+ }
+ }
+ }
- // Handle memory leak in IE
- script.onload = script.onreadystatechange = null;
- if ( head && script.parentNode ) {
- head.removeChild( script );
- }
+ // Attach deferreds
+ deferred.promise( jXHR );
+ jXHR.success = jXHR.done;
+ jXHR.error = jXHR.fail;
+ jXHR.complete = completeDeferred.done;
+
+ // Status-dependent callbacks
+ jXHR.statusCode = function( map ) {
+ if ( map ) {
+ var tmp;
+ if ( state < 2 ) {
+ for( tmp in map ) {
+ statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
- };
+ } else {
+ tmp = map[ jXHR.status ];
+ jXHR.then( tmp, tmp );
+ }
}
+ return this;
+ };
- // Use insertBefore instead of appendChild to circumvent an IE6 bug.
- // This arises when a base node is used (#2709 and #4378).
- head.insertBefore( script, head.firstChild );
+ // Remove hash character (#7531: and string promotion)
+ // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
+ // We also use the url parameter if available
+ s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, protocol + "//" );
+
+ // Extract dataTypes list
+ s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
+
+ // Determine if a cross-domain request is in order
+ if ( !s.crossDomain ) {
+ parts = rurl.exec( s.url.toLowerCase() );
+ s.crossDomain = !!( parts &&
+ ( parts[ 1 ] != protocol || parts[ 2 ] != loc.hostname ||
+ ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
+ ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
+ );
+ }
- // We handle everything using the script element injection
- return undefined;
+ // Convert data if not already a string
+ if ( s.data && s.processData && typeof s.data !== "string" ) {
+ s.data = jQuery.param( s.data, s.traditional );
}
- var requestDone = false;
+ // Apply prefilters
+ inspectPrefiltersOrTransports( prefilters, s, options, jXHR );
- // Create the request object
- var xhr = s.xhr();
+ // Uppercase the type
+ s.type = s.type.toUpperCase();
- if ( !xhr ) {
- return;
- }
+ // Determine if request has content
+ s.hasContent = !rnoContent.test( s.type );
- // Open the socket
- // Passing null username, generates a login popup on Opera (#2865)
- if ( s.username ) {
- xhr.open(type, s.url, s.async, s.username, s.password);
- } else {
- xhr.open(type, s.url, s.async);
+ // Watch for a new set of requests
+ if ( s.global && jQuery.active++ === 0 ) {
+ jQuery.event.trigger( "ajaxStart" );
}
- // Need an extra try/catch for cross domain requests in Firefox 3
- try {
- // Set content-type if data specified and content-body is valid for this type
- if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) {
- xhr.setRequestHeader("Content-Type", s.contentType);
- }
-
- // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
- if ( s.ifModified ) {
- if ( jQuery.lastModified[s.url] ) {
- xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
- }
+ // More options handling for requests with no content
+ if ( !s.hasContent ) {
- if ( jQuery.etag[s.url] ) {
- xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
- }
+ // If data is available, append data to url
+ if ( s.data ) {
+ s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
}
- // Set header so the called script knows that it's an XMLHttpRequest
- // Only send the header if it's not a remote XHR
- if ( !remote ) {
- xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
- }
+ // Add anti-cache in url if needed
+ if ( s.cache === false ) {
- // Set the Accepts header for the server, depending on the dataType
- xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
- s.accepts[ s.dataType ] + ", */*; q=0.01" :
- s.accepts._default );
- } catch( headerError ) {}
+ var ts = jQuery.now(),
+ // try replacing _= if it is there
+ ret = s.url.replace( rts, "$1_=" + ts );
- // Allow custom headers/mimetypes and early abort
- if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
- // Handle the global AJAX counter
- if ( s.global && jQuery.active-- === 1 ) {
- jQuery.event.trigger( "ajaxStop" );
+ // if nothing was replaced, add timestamp to the end
+ s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
-
- // close opended socket
- xhr.abort();
- return false;
}
- if ( s.global ) {
- jQuery.triggerGlobal( s, "ajaxSend", [xhr, s] );
+ // Set the correct header, if data is being sent
+ if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
+ requestHeaders[ "content-type" ] = s.contentType;
}
- // Wait for a response to come back
- var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
- // The request was aborted
- if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
- // Opera doesn't call onreadystatechange before this point
- // so we simulate the call
- if ( !requestDone ) {
- jQuery.handleComplete( s, xhr, status, data );
- }
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ if ( jQuery.lastModified[ s.url ] ) {
+ requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ s.url ];
+ }
+ if ( jQuery.etag[ s.url ] ) {
+ requestHeaders[ "if-none-match" ] = jQuery.etag[ s.url ];
+ }
+ }
- requestDone = true;
- if ( xhr ) {
- xhr.onreadystatechange = jQuery.noop;
- }
+ // Set the Accepts header for the server, depending on the dataType
+ requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
+ s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
+ s.accepts[ "*" ];
- // The transfer is complete and the data is available, or the request timed out
- } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
- requestDone = true;
- xhr.onreadystatechange = jQuery.noop;
+ // Check for headers option
+ for ( i in s.headers ) {
+ requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
+ }
- status = isTimeout === "timeout" ?
- "timeout" :
- !jQuery.httpSuccess( xhr ) ?
- "error" :
- s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
- "notmodified" :
- "success";
+ // Allow custom headers/mimetypes and early abort
+ if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jXHR, s ) === false || state === 2 ) ) {
+ // Abort if not done already
+ done( 0, "abort" );
+ // Return false
+ jXHR = false;
- var errMsg;
+ } else {
- if ( status === "success" ) {
- // Watch for, and catch, XML document parse errors
- try {
- // process the data (runs the xml through httpData regardless of callback)
- data = jQuery.httpData( xhr, s.dataType, s );
- } catch( parserError ) {
- status = "parsererror";
- errMsg = parserError;
- }
- }
+ // Install callbacks on deferreds
+ for ( i in { success: 1, error: 1, complete: 1 } ) {
+ jXHR[ i ]( s[ i ] );
+ }
- // Make sure that the request was successful or notmodified
- if ( status === "success" || status === "notmodified" ) {
- // JSONP handles its own success callback
- if ( !jsonp ) {
- jQuery.handleSuccess( s, xhr, status, data );
- }
- } else {
- jQuery.handleError( s, xhr, status, errMsg );
- }
+ // Get transport
+ transport = inspectPrefiltersOrTransports( transports, s, options, jXHR );
- // Fire the complete handlers
- if ( !jsonp ) {
- jQuery.handleComplete( s, xhr, status, data );
+ // If no transport, we auto-abort
+ if ( !transport ) {
+ done( -1, "No Transport" );
+ } else {
+ // Set state as sending
+ state = jXHR.readyState = 1;
+ // Send global event
+ if ( s.global ) {
+ globalEventContext.trigger( "ajaxSend", [ jXHR, s ] );
}
-
- if ( isTimeout === "timeout" ) {
- xhr.abort();
+ // Timeout
+ if ( s.async && s.timeout > 0 ) {
+ timeoutTimer = setTimeout( function(){
+ jXHR.abort( "timeout" );
+ }, s.timeout );
}
- // Stop memory leaks
- if ( s.async ) {
- xhr = null;
+ try {
+ transport.send( requestHeaders, done );
+ } catch (e) {
+ // Propagate exception as error if not done
+ if ( status < 2 ) {
+ done( -1, e );
+ // Simply rethrow otherwise
+ } else {
+ jQuery.error( e );
+ }
}
}
- };
-
- // Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK)
- // Opera doesn't fire onreadystatechange at all on abort
- try {
- var oldAbort = xhr.abort;
- xhr.abort = function() {
- if ( xhr ) {
- // oldAbort has no call property in IE7 so
- // just do it this way, which works in all
- // browsers
- Function.prototype.call.call( oldAbort, xhr );
- }
-
- onreadystatechange( "abort" );
- };
- } catch( abortError ) {}
-
- // Timeout checker
- if ( s.async && s.timeout > 0 ) {
- setTimeout(function() {
- // Check to see if the request is still happening
- if ( xhr && !requestDone ) {
- onreadystatechange( "timeout" );
- }
- }, s.timeout);
- }
-
- // Send the data
- try {
- xhr.send( noContent || s.data == null ? null : s.data );
-
- } catch( sendError ) {
- jQuery.handleError( s, xhr, null, sendError );
-
- // Fire the complete handlers
- jQuery.handleComplete( s, xhr, status, data );
- }
-
- // firefox 1.5 doesn't fire statechange for sync requests
- if ( !s.async ) {
- onreadystatechange();
}
-
- // return XMLHttpRequest to allow aborting the request etc.
- return xhr;
+ return jXHR;
},
// Serialize an array of form elements or a set of
@@ -6075,37 +6663,37 @@ jQuery.extend({
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
- value = jQuery.isFunction(value) ? value() : value;
- s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
+ value = jQuery.isFunction( value ) ? value() : value;
+ s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
-
+
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
-
+
// If an array was passed in, assume that it is an array of form elements.
- if ( jQuery.isArray(a) || a.jquery ) {
+ if ( jQuery.isArray( a ) || a.jquery ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
- });
-
+ } );
+
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
- buildParams( prefix, a[prefix], traditional, add );
+ buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
- return s.join("&").replace(r20, "+");
+ return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
- if ( jQuery.isArray(obj) && obj.length ) {
+ if ( jQuery.isArray( obj ) && obj.length ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
@@ -6123,9 +6711,11 @@ function buildParams( prefix, obj, traditional, add ) {
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
-
+
} else if ( !traditional && obj != null && typeof obj === "object" ) {
- if ( jQuery.isEmptyObject( obj ) ) {
+ // If we see an array here, it is empty and should be treated as an empty
+ // object
+ if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
add( prefix, "" );
// Serialize object item.
@@ -6134,7 +6724,7 @@ function buildParams( prefix, obj, traditional, add ) {
buildParams( prefix + "[" + k + "]", v, traditional, add );
});
}
-
+
} else {
// Serialize scalar item.
add( prefix, obj );
@@ -6150,143 +6740,548 @@ jQuery.extend({
// Last-Modified header cache for next request
lastModified: {},
- etag: {},
+ etag: {}
- handleError: function( s, xhr, status, e ) {
- // If a local callback was specified, fire it
- if ( s.error ) {
- s.error.call( s.context, xhr, status, e );
- }
+});
- // Fire the global callback
- if ( s.global ) {
- jQuery.triggerGlobal( s, "ajaxError", [xhr, s, e] );
+/* Handles responses to an ajax request:
+ * - sets all responseXXX fields accordingly
+ * - finds the right dataType (mediates between content-type and expected dataType)
+ * - returns the corresponding response
+ */
+function ajaxHandleResponses( s, jXHR, responses ) {
+
+ var contents = s.contents,
+ dataTypes = s.dataTypes,
+ responseFields = s.responseFields,
+ ct,
+ type,
+ finalDataType,
+ firstDataType;
+
+ // Fill responseXXX fields
+ for( type in responseFields ) {
+ if ( type in responses ) {
+ jXHR[ responseFields[type] ] = responses[ type ];
}
- },
+ }
- handleSuccess: function( s, xhr, status, data ) {
- // If a local callback was specified, fire it and pass it the data
- if ( s.success ) {
- s.success.call( s.context, data, status, xhr );
+ // Remove auto dataType and get content-type in the process
+ while( dataTypes[ 0 ] === "*" ) {
+ dataTypes.shift();
+ if ( ct === undefined ) {
+ ct = jXHR.getResponseHeader( "content-type" );
}
+ }
- // Fire the global callback
- if ( s.global ) {
- jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
+ // Check if we're dealing with a known content-type
+ if ( ct ) {
+ for ( type in contents ) {
+ if ( contents[ type ] && contents[ type ].test( ct ) ) {
+ dataTypes.unshift( type );
+ break;
+ }
}
- },
+ }
- handleComplete: function( s, xhr, status ) {
- // Process result
- if ( s.complete ) {
- s.complete.call( s.context, xhr, status );
+ // Check to see if we have a response for the expected dataType
+ if ( dataTypes[ 0 ] in responses ) {
+ finalDataType = dataTypes[ 0 ];
+ } else {
+ // Try convertible dataTypes
+ for ( type in responses ) {
+ if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
+ finalDataType = type;
+ break;
+ }
+ if ( !firstDataType ) {
+ firstDataType = type;
+ }
}
+ // Or just use first one
+ finalDataType = finalDataType || firstDataType;
+ }
- // The request was completed
- if ( s.global ) {
- jQuery.triggerGlobal( s, "ajaxComplete", [xhr, s] );
+ // If we found a dataType
+ // We add the dataType to the list if needed
+ // and return the corresponding response
+ if ( finalDataType ) {
+ if ( finalDataType !== dataTypes[ 0 ] ) {
+ dataTypes.unshift( finalDataType );
}
+ return responses[ finalDataType ];
+ }
+}
+
+// Chain conversions given the request and the original response
+function ajaxConvert( s, response ) {
- // Handle the global AJAX counter
- if ( s.global && jQuery.active-- === 1 ) {
- jQuery.event.trigger( "ajaxStop" );
+ // Apply the dataFilter if provided
+ if ( s.dataFilter ) {
+ response = s.dataFilter( response, s.dataType );
+ }
+
+ var dataTypes = s.dataTypes,
+ converters = s.converters,
+ i,
+ length = dataTypes.length,
+ tmp,
+ // Current and previous dataTypes
+ current = dataTypes[ 0 ],
+ prev,
+ // Conversion expression
+ conversion,
+ // Conversion function
+ conv,
+ // Conversion functions (transitive conversion)
+ conv1,
+ conv2;
+
+ // For each dataType in the chain
+ for( i = 1; i < length; i++ ) {
+
+ // Get the dataTypes
+ prev = current;
+ current = dataTypes[ i ];
+
+ // If current is auto dataType, update it to prev
+ if( current === "*" ) {
+ current = prev;
+ // If no auto and dataTypes are actually different
+ } else if ( prev !== "*" && prev !== current ) {
+
+ // Get the converter
+ conversion = prev + " " + current;
+ conv = converters[ conversion ] || converters[ "* " + current ];
+
+ // If there is no direct converter, search transitively
+ if ( !conv ) {
+ conv2 = undefined;
+ for( conv1 in converters ) {
+ tmp = conv1.split( " " );
+ if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
+ conv2 = converters[ tmp[1] + " " + current ];
+ if ( conv2 ) {
+ conv1 = converters[ conv1 ];
+ if ( conv1 === true ) {
+ conv = conv2;
+ } else if ( conv2 === true ) {
+ conv = conv1;
+ }
+ break;
+ }
+ }
+ }
+ }
+ // If we found no converter, dispatch an error
+ if ( !( conv || conv2 ) ) {
+ jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
+ }
+ // If found converter is not an equivalence
+ if ( conv !== true ) {
+ // Convert with 1 or 2 converters accordingly
+ response = conv ? conv( response ) : conv2( conv1(response) );
+ }
}
- },
-
- triggerGlobal: function( s, type, args ) {
- (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
- },
+ }
+ return response;
+}
- // Determines if an XMLHttpRequest was successful or not
- httpSuccess: function( xhr ) {
- try {
- // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
- return !xhr.status && location.protocol === "file:" ||
- xhr.status >= 200 && xhr.status < 300 ||
- xhr.status === 304 || xhr.status === 1223;
- } catch(e) {}
- return false;
- },
- // Determines if an XMLHttpRequest returns NotModified
- httpNotModified: function( xhr, url ) {
- var lastModified = xhr.getResponseHeader("Last-Modified"),
- etag = xhr.getResponseHeader("Etag");
- if ( lastModified ) {
- jQuery.lastModified[url] = lastModified;
- }
+var jsc = jQuery.now(),
+ jsre = /(\=)\?(&|$)|()\?\?()/i;
- if ( etag ) {
- jQuery.etag[url] = etag;
+// Default jsonp settings
+jQuery.ajaxSetup({
+ jsonp: "callback",
+ jsonpCallback: function() {
+ return jQuery.expando + "_" + ( jsc++ );
+ }
+});
+
+// Detect, normalize options and install callbacks for jsonp requests
+jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, dataIsString /* internal */ ) {
+
+ dataIsString = ( typeof s.data === "string" );
+
+ if ( s.dataTypes[ 0 ] === "jsonp" ||
+ originalSettings.jsonpCallback ||
+ originalSettings.jsonp != null ||
+ s.jsonp !== false && ( jsre.test( s.url ) ||
+ dataIsString && jsre.test( s.data ) ) ) {
+
+ var responseContainer,
+ jsonpCallback = s.jsonpCallback =
+ jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
+ previous = window[ jsonpCallback ],
+ url = s.url,
+ data = s.data,
+ replace = "$1" + jsonpCallback + "$2";
+
+ if ( s.jsonp !== false ) {
+ url = url.replace( jsre, replace );
+ if ( s.url === url ) {
+ if ( dataIsString ) {
+ data = data.replace( jsre, replace );
+ }
+ if ( s.data === data ) {
+ // Add callback manually
+ url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
+ }
+ }
}
- return xhr.status === 304;
- },
+ s.url = url;
+ s.data = data;
- httpData: function( xhr, type, s ) {
- var ct = xhr.getResponseHeader("content-type") || "",
- xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
- data = xml ? xhr.responseXML : xhr.responseText;
+ window[ jsonpCallback ] = function( response ) {
+ responseContainer = [ response ];
+ };
- if ( xml && data.documentElement.nodeName === "parsererror" ) {
- jQuery.error( "parsererror" );
- }
+ s.complete = [ function() {
- // Allow a pre-filtering function to sanitize the response
- // s is checked to keep backwards compatibility
- if ( s && s.dataFilter ) {
- data = s.dataFilter( data, type );
- }
+ // Set callback back to previous value
+ window[ jsonpCallback ] = previous;
- // The filter can actually parse the response
- if ( typeof data === "string" ) {
- // Get the JavaScript object, if JSON is used.
- if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
- data = jQuery.parseJSON( data );
+ // Call if it was a function and we have a response
+ if ( previous) {
+ if ( responseContainer && jQuery.isFunction( previous ) ) {
+ window[ jsonpCallback ] ( responseContainer[ 0 ] );
+ }
+ } else {
+ // else, more memory leak avoidance
+ try{
+ delete window[ jsonpCallback ];
+ } catch( e ) {}
+ }
+
+ }, s.complete ];
- // If the type is "script", eval it in global context
- } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
- jQuery.globalEval( data );
+ // Use data converter to retrieve json after script execution
+ s.converters["script json"] = function() {
+ if ( ! responseContainer ) {
+ jQuery.error( jsonpCallback + " was not called" );
}
- }
+ return responseContainer[ 0 ];
+ };
+
+ // force json dataType
+ s.dataTypes[ 0 ] = "json";
- return data;
+ // Delegate to script
+ return "script";
}
+} );
+
+
+
+// Install script dataType
+jQuery.ajaxSetup({
+ accepts: {
+ script: "text/javascript, application/javascript"
+ },
+ contents: {
+ script: /javascript/
+ },
+ converters: {
+ "text script": function( text ) {
+ jQuery.globalEval( text );
+ return text;
+ }
+ }
});
-/*
- * Create the request object; Microsoft failed to properly
- * implement the XMLHttpRequest in IE7 (can't request local files),
- * so we use the ActiveXObject when it is available
- * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
- * we need a fallback.
- */
-if ( window.ActiveXObject ) {
- jQuery.ajaxSettings.xhr = function() {
+// Handle cache's special case and global
+jQuery.ajaxPrefilter( "script", function( s ) {
+ if ( s.cache === undefined ) {
+ s.cache = false;
+ }
+ if ( s.crossDomain ) {
+ s.type = "GET";
+ s.global = false;
+ }
+} );
+
+// Bind script tag hack transport
+jQuery.ajaxTransport( "script", function(s) {
+
+ // This transport only deals with cross domain requests
+ if ( s.crossDomain ) {
+
+ var script,
+ head = document.getElementsByTagName( "head" )[ 0 ] || document.documentElement;
+
+ return {
+
+ send: function( _, callback ) {
+
+ script = document.createElement( "script" );
+
+ script.async = "async";
+
+ if ( s.scriptCharset ) {
+ script.charset = s.scriptCharset;
+ }
+
+ script.src = s.url;
+
+ // Attach handlers for all browsers
+ script.onload = script.onreadystatechange = function( _, isAbort ) {
+
+ if ( !script.readyState || /loaded|complete/.test( script.readyState ) ) {
+
+ // Handle memory leak in IE
+ script.onload = script.onreadystatechange = null;
+
+ // Remove the script
+ if ( head && script.parentNode ) {
+ head.removeChild( script );
+ }
+
+ // Dereference the script
+ script = undefined;
+
+ // Callback if not abort
+ if ( !isAbort ) {
+ callback( 200, "success" );
+ }
+ }
+ };
+ // Use insertBefore instead of appendChild to circumvent an IE6 bug.
+ // This arises when a base node is used (#2709 and #4378).
+ head.insertBefore( script, head.firstChild );
+ },
+
+ abort: function() {
+ if ( script ) {
+ script.onload( 0, 1 );
+ }
+ }
+ };
+ }
+} );
+
+
+
+
+var // Next active xhr id
+ xhrId = jQuery.now(),
+
+ // active xhrs
+ xhrs = {},
+
+ // #5280: see below
+ xhrUnloadAbortInstalled,
+
+ // XHR used to determine supports properties
+ testXHR;
+
+// Create the request object
+// (This is still attached to ajaxSettings for backward compatibility)
+jQuery.ajaxSettings.xhr = window.ActiveXObject ?
+ /* Microsoft failed to properly
+ * implement the XMLHttpRequest in IE7 (can't request local files),
+ * so we use the ActiveXObject when it is available
+ * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
+ * we need a fallback.
+ */
+ function() {
if ( window.location.protocol !== "file:" ) {
try {
return new window.XMLHttpRequest();
- } catch(xhrError) {}
+ } catch( xhrError ) {}
}
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
- } catch(activeError) {}
+ } catch( activeError ) {}
+ } :
+ // For all other browsers, use the standard XMLHttpRequest object
+ function() {
+ return new window.XMLHttpRequest();
};
-}
-// Does this browser support XHR requests?
-jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
+// Test if we can create an xhr object
+try {
+ testXHR = jQuery.ajaxSettings.xhr();
+} catch( xhrCreationException ) {}
+
+//Does this browser support XHR requests?
+jQuery.support.ajax = !!testXHR;
+
+// Does this browser support crossDomain XHR requests
+jQuery.support.cors = testXHR && ( "withCredentials" in testXHR );
+
+// No need for the temporary xhr anymore
+testXHR = undefined;
+
+// Create transport if the browser can provide an xhr
+if ( jQuery.support.ajax ) {
+
+ jQuery.ajaxTransport(function( s ) {
+ // Cross domain only allowed if supported through XMLHttpRequest
+ if ( !s.crossDomain || jQuery.support.cors ) {
+
+ var callback;
+
+ return {
+ send: function( headers, complete ) {
+
+ // #5280: we need to abort on unload or IE will keep connections alive
+ if ( !xhrUnloadAbortInstalled ) {
+
+ xhrUnloadAbortInstalled = 1;
+
+ jQuery(window).bind( "unload", function() {
+
+ // Abort all pending requests
+ jQuery.each( xhrs, function( _, xhr ) {
+ if ( xhr.onreadystatechange ) {
+ xhr.onreadystatechange( 1 );
+ }
+ } );
+
+ } );
+ }
+
+ // Get a new xhr
+ var xhr = s.xhr(),
+ handle;
+
+ // Open the socket
+ // Passing null username, generates a login popup on Opera (#2865)
+ if ( s.username ) {
+ xhr.open( s.type, s.url, s.async, s.username, s.password );
+ } else {
+ xhr.open( s.type, s.url, s.async );
+ }
+
+ // Requested-With header
+ // Not set for crossDomain requests with no content
+ // (see why at http://trac.dojotoolkit.org/ticket/9486)
+ // Won't change header if already provided
+ if ( !( s.crossDomain && !s.hasContent ) && !headers["x-requested-with"] ) {
+ headers[ "x-requested-with" ] = "XMLHttpRequest";
+ }
+
+ // Need an extra try/catch for cross domain requests in Firefox 3
+ try {
+ jQuery.each( headers, function( key, value ) {
+ xhr.setRequestHeader( key, value );
+ } );
+ } catch( _ ) {}
+
+ // Do send the request
+ // This may raise an exception which is actually
+ // handled in jQuery.ajax (so no try/catch here)
+ xhr.send( ( s.hasContent && s.data ) || null );
+
+ // Listener
+ callback = function( _, isAbort ) {
+
+ // Was never called and is aborted or complete
+ if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
+
+ // Only called once
+ callback = 0;
+
+ // Do not keep as active anymore
+ if ( handle ) {
+ xhr.onreadystatechange = jQuery.noop;
+ delete xhrs[ handle ];
+ }
+
+ // If it's an abort
+ if ( isAbort ) {
+ // Abort it manually if needed
+ if ( xhr.readyState !== 4 ) {
+ xhr.abort();
+ }
+ } else {
+ // Get info
+ var status = xhr.status,
+ statusText,
+ responseHeaders = xhr.getAllResponseHeaders(),
+ responses = {},
+ xml = xhr.responseXML;
+
+ // Construct response list
+ if ( xml && xml.documentElement /* #4958 */ ) {
+ responses.xml = xml;
+ }
+ responses.text = xhr.responseText;
+
+ // Firefox throws an exception when accessing
+ // statusText for faulty cross-domain requests
+ try {
+ statusText = xhr.statusText;
+ } catch( e ) {
+ // We normalize with Webkit giving an empty statusText
+ statusText = "";
+ }
+
+ // Filter status for non standard behaviours
+ status =
+ // Opera returns 0 when it should be 304
+ // Webkit returns 0 for failing cross-domain no matter the real status
+ status === 0 ?
+ (
+ // Webkit, Firefox: filter out faulty cross-domain requests
+ !s.crossDomain || statusText ?
+ (
+ // Opera: filter out real aborts #6060
+ responseHeaders ?
+ 304 :
+ 0
+ ) :
+ // We assume 302 but could be anything cross-domain related
+ 302
+ ) :
+ (
+ // IE sometimes returns 1223 when it should be 204 (see #1450)
+ status == 1223 ?
+ 204 :
+ status
+ );
+
+ // Call complete
+ complete( status, statusText, responses, responseHeaders );
+ }
+ }
+ };
+
+ // if we're in sync mode or it's in cache
+ // and has been retrieved directly (IE6 & IE7)
+ // we need to manually fire the callback
+ if ( !s.async || xhr.readyState === 4 ) {
+ callback();
+ } else {
+ // Add to list of active xhrs
+ handle = xhrId++;
+ xhrs[ handle ] = xhr;
+ xhr.onreadystatechange = callback;
+ }
+ },
+
+ abort: function() {
+ if ( callback ) {
+ callback(0,1);
+ }
+ }
+ };
+ }
+ });
+}
var elemdisplay = {},
rfxtypes = /^(?:toggle|show|hide)$/,
- rfxnum = /^([+\-]=)?([\d+.\-]+)(.*)$/,
+ rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
@@ -6311,7 +7306,7 @@ jQuery.fn.extend({
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
- if ( !jQuery.data(elem, "olddisplay") && display === "none" ) {
+ if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
@@ -6319,7 +7314,7 @@ jQuery.fn.extend({
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
- jQuery.data(elem, "olddisplay", defaultDisplay(elem.nodeName));
+ jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
}
@@ -6330,7 +7325,7 @@ jQuery.fn.extend({
display = elem.style.display;
if ( display === "" || display === "none" ) {
- elem.style.display = jQuery.data(elem, "olddisplay") || "";
+ elem.style.display = jQuery._data(elem, "olddisplay") || "";
}
}
@@ -6346,8 +7341,8 @@ jQuery.fn.extend({
for ( var i = 0, j = this.length; i < j; i++ ) {
var display = jQuery.css( this[i], "display" );
- if ( display !== "none" ) {
- jQuery.data( this[i], "olddisplay", display );
+ if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
+ jQuery._data( this[i], "olddisplay", display );
}
}
@@ -6621,7 +7616,7 @@ jQuery.fx.prototype = {
}
var r = parseFloat( jQuery.css( this.elem, this.prop ) );
- return r && r > -10000 ? r : 0;
+ return r || 0;
},
// Start an animation from one number to another
@@ -6815,7 +7810,7 @@ if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;
- if ( options ) {
+ if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
@@ -6838,7 +7833,7 @@ if ( "getBoundingClientRect" in document.documentElement ) {
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
- return box || { top: 0, left: 0 };
+ return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
@@ -6857,7 +7852,7 @@ if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0];
- if ( options ) {
+ if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
@@ -6976,7 +7971,7 @@ jQuery.offset = {
return { top: top, left: left };
},
-
+
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
@@ -7010,7 +8005,7 @@ jQuery.offset = {
if (options.left != null) {
props.left = (options.left - curOffset.left) + curLeft;
}
-
+
if ( "using" in options ) {
options.using.call( elem, props );
} else {
@@ -7070,7 +8065,7 @@ jQuery.each( ["Left", "Top"], function( i, name ) {
jQuery.fn[ method ] = function(val) {
var elem = this[0], win;
-
+
if ( !elem ) {
return null;
}
@@ -7138,7 +8133,7 @@ jQuery.each([ "Height", "Width" ], function( i, name ) {
if ( !elem ) {
return size == null ? null : this;
}
-
+
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
@@ -7148,8 +8143,10 @@ jQuery.each([ "Height", "Width" ], function( i, name ) {
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
- return elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] ||
- elem.document.body[ "client" + name ];
+ // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
+ var docElemProp = elem.document.documentElement[ "client" + name ];
+ return elem.document.compatMode === "CSS1Compat" && docElemProp ||
+ elem.document.body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js
index 43456a77f6..4dcb3779a2 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js
@@ -1,132 +1,148 @@
-jQuery(function ($) {
- var csrf_token = $('meta[name=csrf-token]').attr('content'),
- csrf_param = $('meta[name=csrf-param]').attr('content');
-
- $.fn.extend({
- /**
- * Triggers a custom event on an element and returns the event result
- * this is used to get around not being able to ensure callbacks are placed
- * at the end of the chain.
- *
- * TODO: deprecate with jQuery 1.4.2 release, in favor of subscribing to our
- * own events and placing ourselves at the end of the chain.
- */
- triggerAndReturn: function (name, data) {
- var event = new $.Event(name);
- this.trigger(event, data);
-
- return event.result !== false;
- },
-
- /**
- * Handles execution of remote calls firing overridable events along the way
- */
- callRemote: function () {
- var el = this,
- method = el.attr('method') || el.attr('data-method') || 'GET',
- url = el.attr('action') || el.attr('href'),
- dataType = el.attr('data-type') || 'script';
-
- if (url === undefined) {
- throw "No URL specified for remote call (action or href must be present).";
- } else {
- if (el.triggerAndReturn('ajax:before')) {
- var data = el.is('form') ? el.serializeArray() : [];
- $.ajax({
- url: url,
- data: data,
- dataType: dataType,
- type: method.toUpperCase(),
- beforeSend: function (xhr) {
- el.trigger('ajax:loading', xhr);
- },
- success: function (data, status, xhr) {
- el.trigger('ajax:success', [data, status, xhr]);
- },
- complete: function (xhr) {
- el.trigger('ajax:complete', xhr);
- },
- error: function (xhr, status, error) {
- el.trigger('ajax:failure', [xhr, status, error]);
- }
- });
- }
-
- el.trigger('ajax:after');
- }
- }
- });
-
- /**
- * confirmation handler
- */
- $('a[data-confirm],input[data-confirm]').live('click', function () {
- var el = $(this);
- if (el.triggerAndReturn('confirm')) {
- if (!confirm(el.attr('data-confirm'))) {
- return false;
- }
- }
- });
-
-
- /**
- * remote handlers
- */
- $('form[data-remote]').live('submit', function (e) {
- $(this).callRemote();
- e.preventDefault();
- });
-
- $('a[data-remote],input[data-remote]').live('click', function (e) {
- $(this).callRemote();
- e.preventDefault();
- });
-
- $('a[data-method]:not([data-remote])').live('click', function (e){
- var link = $(this),
- href = link.attr('href'),
- method = link.attr('data-method'),
- form = $('<form method="post" action="'+href+'"></form>'),
- metadata_input = '<input name="_method" value="'+method+'" type="hidden" />';
-
- if (csrf_param != null && csrf_token != null) {
- metadata_input += '<input name="'+csrf_param+'" value="'+csrf_token+'" type="hidden" />';
- }
-
- form.hide()
- .append(metadata_input)
- .appendTo('body');
-
- e.preventDefault();
- form.submit();
- });
-
- /**
- * disable-with handlers
- */
- var disable_with_input_selector = 'input[data-disable-with]';
- var disable_with_form_remote_selector = 'form[data-remote]:has(' + disable_with_input_selector + ')';
- var disable_with_form_not_remote_selector = 'form:not([data-remote]):has(' + disable_with_input_selector + ')';
-
- var disable_with_input_function = function () {
- $(this).find(disable_with_input_selector).each(function () {
- var input = $(this);
- input.data('enable-with', input.val())
- .attr('value', input.attr('data-disable-with'))
- .attr('disabled', 'disabled');
- });
- };
-
- $(disable_with_form_remote_selector).live('ajax:before', disable_with_input_function);
- $(disable_with_form_not_remote_selector).live('submit', disable_with_input_function);
-
- $(disable_with_form_remote_selector).live('ajax:complete', function () {
- $(this).find(disable_with_input_selector).each(function () {
- var input = $(this);
- input.removeAttr('disabled')
- .val(input.data('enable-with'));
- });
- });
-
-});
+/**
+ * Unobtrusive scripting adapter for jQuery
+ *
+ * Requires jQuery 1.4.3 or later.
+ * https://github.com/rails/jquery-ujs
+ */
+
+(function($) {
+ // Triggers an event on an element and returns the event result
+ function fire(obj, name, data) {
+ var event = new $.Event(name);
+ obj.trigger(event, data);
+ return event.result !== false;
+ }
+
+ // Submits "remote" forms and links with ajax
+ function handleRemote(element) {
+ var method, url, data,
+ dataType = element.attr('data-type') || ($.ajaxSettings && $.ajaxSettings.dataType);
+
+ if (element.is('form')) {
+ method = element.attr('method');
+ url = element.attr('action');
+ data = element.serializeArray();
+ // memoized value from clicked submit button
+ var button = element.data('ujs:submit-button');
+ if (button) {
+ data.push(button);
+ element.data('ujs:submit-button', null);
+ }
+ } else {
+ method = element.attr('data-method');
+ url = element.attr('href');
+ data = null;
+ }
+
+ $.ajax({
+ url: url, type: method || 'GET', data: data, dataType: dataType,
+ // stopping the "ajax:beforeSend" event will cancel the ajax request
+ beforeSend: function(xhr, settings) {
+ if (settings.dataType === undefined) {
+ xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
+ }
+ return fire(element, 'ajax:beforeSend', [xhr, settings]);
+ },
+ success: function(data, status, xhr) {
+ element.trigger('ajax:success', [data, status, xhr]);
+ },
+ complete: function(xhr, status) {
+ element.trigger('ajax:complete', [xhr, status]);
+ },
+ error: function(xhr, status, error) {
+ element.trigger('ajax:error', [xhr, status, error]);
+ }
+ });
+ }
+
+ // Handles "data-method" on links such as:
+ // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
+ function handleMethod(link) {
+ var href = link.attr('href'),
+ method = link.attr('data-method'),
+ csrf_token = $('meta[name=csrf-token]').attr('content'),
+ csrf_param = $('meta[name=csrf-param]').attr('content'),
+ form = $('<form method="post" action="' + href + '"></form>'),
+ metadata_input = '<input name="_method" value="' + method + '" type="hidden" />';
+
+ if (csrf_param !== undefined && csrf_token !== undefined) {
+ metadata_input += '<input name="' + csrf_param + '" value="' + csrf_token + '" type="hidden" />';
+ }
+
+ form.hide().append(metadata_input).appendTo('body');
+ form.submit();
+ }
+
+ function disableFormElements(form) {
+ form.find('input[data-disable-with]').each(function() {
+ var input = $(this);
+ input.data('ujs:enable-with', input.val())
+ .val(input.attr('data-disable-with'))
+ .attr('disabled', 'disabled');
+ });
+ }
+
+ function enableFormElements(form) {
+ form.find('input[data-disable-with]').each(function() {
+ var input = $(this);
+ input.val(input.data('ujs:enable-with')).removeAttr('disabled');
+ });
+ }
+
+ function allowAction(element) {
+ var message = element.attr('data-confirm');
+ return !message || (fire(element, 'confirm') && confirm(message));
+ }
+
+ function requiredValuesMissing(form) {
+ var missing = false;
+ form.find('input[name][required]').each(function() {
+ if (!$(this).val()) missing = true;
+ });
+ return missing;
+ }
+
+ $('a[data-confirm], a[data-method], a[data-remote]').live('click.rails', function(e) {
+ var link = $(this);
+ if (!allowAction(link)) return false;
+
+ if (link.attr('data-remote') != undefined) {
+ handleRemote(link);
+ return false;
+ } else if (link.attr('data-method')) {
+ handleMethod(link);
+ return false;
+ }
+ });
+
+ $('form').live('submit.rails', function(e) {
+ var form = $(this), remote = form.attr('data-remote') != undefined;
+ if (!allowAction(form)) return false;
+
+ // skip other logic when required values are missing
+ if (requiredValuesMissing(form)) return !remote;
+
+ if (remote) {
+ handleRemote(form);
+ return false;
+ } else {
+ disableFormElements(form);
+ }
+ });
+
+ $('form input[type=submit], form button[type=submit], form button:not([type])').live('click.rails', function() {
+ var button = $(this);
+ if (!allowAction(button)) return false;
+ // register the pressed submit button
+ var name = button.attr('name'), data = name ? {name:name, value:button.val()} : null;
+ button.closest('form').data('ujs:submit-button', data);
+ });
+
+ $('form').live('ajax:beforeSend.rails', function(event) {
+ if (this == event.target) disableFormElements($(this));
+ });
+
+ $('form').live('ajax:complete.rails', function(event) {
+ if (this == event.target) enableFormElements($(this));
+ });
+})( jQuery );
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js
index fc69f93c58..2cd1220786 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js
@@ -95,9 +95,10 @@
parameters: params,
evalScripts: true,
- onComplete: function(request) { element.fire("ajax:complete", request); },
- onSuccess: function(request) { element.fire("ajax:success", request); },
- onFailure: function(request) { element.fire("ajax:failure", request); }
+ onCreate: function(response) { element.fire("ajax:create", response); },
+ onComplete: function(response) { element.fire("ajax:complete", response); },
+ onSuccess: function(response) { element.fire("ajax:success", response); },
+ onFailure: function(response) { element.fire("ajax:failure", response); }
});
element.fire("ajax:after");
@@ -114,7 +115,7 @@
csrf_token = $$('meta[name=csrf-token]')[0];
var form = new Element('form', { method: "POST", action: url, style: "display: none;" });
- element.parentNode.insert(form);
+ $(element.parentNode).insert(form);
if (method !== 'post') {
insertHiddenField(form, '_method', method);
@@ -127,52 +128,81 @@
form.submit();
}
+ function disableFormElements(form) {
+ form.select('input[type=submit][data-disable-with]').each(function(input) {
+ input.store('rails:original-value', input.getValue());
+ input.setValue(input.readAttribute('data-disable-with')).disable();
+ });
+ }
+
+ function enableFormElements(form) {
+ form.select('input[type=submit][data-disable-with]').each(function(input) {
+ input.setValue(input.retrieve('rails:original-value')).enable();
+ });
+ }
- document.on("click", "*[data-confirm]", function(event, element) {
+ function allowAction(element) {
var message = element.readAttribute('data-confirm');
- if (!confirm(message)) event.stop();
- });
+ return !message || confirm(message);
+ }
- document.on("click", "a[data-remote]", function(event, element) {
- if (event.stopped) return;
- handleRemote(element);
- event.stop();
- });
+ document.on('click', 'a[data-confirm], a[data-remote], a[data-method]', function(event, link) {
+ if (!allowAction(link)) {
+ event.stop();
+ return false;
+ }
- document.on("click", "a[data-method]", function(event, element) {
- if (event.stopped) return;
- handleMethod(element);
- event.stop();
+ if (link.readAttribute('data-remote')) {
+ handleRemote(link);
+ event.stop();
+ } else if (link.readAttribute('data-method')) {
+ handleMethod(link);
+ event.stop();
+ }
});
- document.on("click", "form input[type=submit]", function(event, button) {
+ document.on("click", "form input[type=submit], form button[type=submit], form button:not([type])", function(event, button) {
// register the pressed submit button
event.findElement('form').store('rails:submit-button', button.name || false);
});
document.on("submit", function(event) {
- var form = event.findElement(),
- message = form.readAttribute('data-confirm');
+ var form = event.findElement();
- if (message && !confirm(message)) {
+ if (!allowAction(form)) {
event.stop();
return false;
}
- form.select('input[type=submit][data-disable-with]').each(function(input) {
- input.store('rails:original-value', input.getValue());
- input.disable().setValue(input.readAttribute('data-disable-with'));
- });
-
if (form.readAttribute('data-remote')) {
handleRemote(form);
event.stop();
+ } else {
+ disableFormElements(form);
}
});
- document.on("ajax:after", "form", function(event, form) {
- form.select('input[type=submit][data-disable-with]').each(function(input) {
- input.setValue(input.retrieve('rails:original-value')).enable();
- });
+ document.on('ajax:create', 'form', function(event, form) {
+ if (form == event.findElement()) disableFormElements(form);
+ });
+
+ document.on('ajax:complete', 'form', function(event, form) {
+ if (form == event.findElement()) enableFormElements(form);
+ });
+
+ Ajax.Responders.register({
+ onCreate: function(request) {
+ var csrf_meta_tag = $$('meta[name=csrf-token]')[0];
+
+ if (csrf_meta_tag) {
+ var header = 'X-CSRF-Token',
+ token = csrf_meta_tag.readAttribute('content');
+
+ if (!request.options.requestHeaders) {
+ request.options.requestHeaders = {};
+ }
+ request.options.requestHeaders[header] = token;
+ }
+ }
});
})();
diff --git a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
index 9461589ff5..8b1aed974f 100644
--- a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
@@ -16,7 +16,7 @@ module Rails
end
def readme
- copy_file "README.rdoc"
+ template "README.rdoc"
end
def gemfile
@@ -44,7 +44,7 @@ module Rails
end
def config
- template "config/routes.rb" if mountable?
+ template "config/routes.rb" if full?
end
def test
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb b/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb
index 42ddf380d8..8e158d5831 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb
@@ -1,3 +1,6 @@
+<% if mountable? -%>
<%= camelized %>::Engine.routes.draw do
-
+<% else -%>
+Rails.application.routes.draw do
+<% end -%>
end
diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb
index cab8708be3..ee85b70bb5 100644
--- a/railties/lib/rails/generators/test_case.rb
+++ b/railties/lib/rails/generators/test_case.rb
@@ -114,7 +114,7 @@ module Rails
end
alias :assert_no_directory :assert_no_file
- # Asserts a given file does not exist. You need to supply an absolute path or a
+ # Asserts a given migration exists. You need to supply an absolute path or a
# path relative to the configured destination:
#
# assert_migration "db/migrate/create_products.rb"
diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb
index 8570fc7b3f..d15887f561 100644
--- a/railties/lib/rails/paths.rb
+++ b/railties/lib/rails/paths.rb
@@ -134,10 +134,10 @@ module Rails
@root = root
@glob = options[:glob]
- autoload_once! if options[:autoload_once]
- eager_load! if options[:eager_load]
- autoload! if options[:autoload]
- load_path! if options[:load_path]
+ options[:autoload_once] ? autoload_once! : skip_autoload_once!
+ options[:eager_load] ? eager_load! : skip_eager_load!
+ options[:autoload] ? autoload! : skip_autoload!
+ options[:load_path] ? load_path! : skip_load_path!
end
def children
diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb
index b3dc1f894c..32acc66f10 100644
--- a/railties/lib/rails/rack/logger.rb
+++ b/railties/lib/rails/rack/logger.rb
@@ -21,7 +21,7 @@ module Rails
request = ActionDispatch::Request.new(env)
path = request.fullpath
- info "\n\nStarted #{env["REQUEST_METHOD"]} \"#{path}\" " \
+ info "\n\nStarted #{request.request_method} \"#{path}\" " \
"for #{request.ip} at #{Time.now.to_default_s}"
end
diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb
index 178b31cff3..390f65ab5c 100644
--- a/railties/test/application/initializers/i18n_test.rb
+++ b/railties/test/application/initializers/i18n_test.rb
@@ -63,6 +63,36 @@ module ApplicationTests
assert I18n.load_path.include?("#{app_path}/config/another_locale.yml")
end
+ test "load_path is populated before eager loaded models" do
+ add_to_config <<-RUBY
+ config.cache_classes = true
+ RUBY
+
+ app_file "config/locales/en.yml", <<-YAML
+en:
+ foo: "1"
+ YAML
+
+ app_file 'app/models/foo.rb', <<-RUBY
+ class Foo < ActiveRecord::Base
+ @foo = I18n.t(:foo)
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match '/i18n', :to => lambda { |env| [200, {}, [Foo.instance_variable_get('@foo')]] }
+ end
+ RUBY
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+ load_app
+
+ get "/i18n"
+ assert_equal "1", last_response.body
+ end
+
test "locales are reloaded if they change between requests" do
add_to_config <<-RUBY
config.cache_classes = false
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index 23cd2378c7..59e5ef4dee 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -63,5 +63,41 @@ module ApplicationTests
RUBY
assert_match 'cart GET /cart(.:format)', Dir.chdir(app_path){ `rake routes` }
end
+
+ def test_model_and_migration_generator_with_change_syntax
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+ `rails generate migration add_email_to_users email:string`
+ end
+
+ output = Dir.chdir(app_path){ `rake db:migrate` }
+ assert_match /create_table\(:users\)/, output
+ assert_match /CreateUsers: migrated/, output
+ assert_match /add_column\(:users, :email, :string\)/, output
+ assert_match /AddEmailToUsers: migrated/, output
+
+ output = Dir.chdir(app_path){ `rake db:rollback STEP=2` }
+ assert_match /drop_table\("users"\)/, output
+ assert_match /CreateUsers: reverted/, output
+ assert_match /remove_column\("users", :email\)/, output
+ assert_match /AddEmailToUsers: reverted/, output
+ end
+
+ def test_loading_specific_fixtures
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+ `rails generate model product name:string`
+ `rake db:migrate`
+ end
+
+ require "#{rails_root}/config/environment"
+
+ # loading a specific fixture
+ errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` }
+ assert $?.success?, errormsg
+
+ assert_equal 2, ::AppTemplate::Application::Product.count
+ assert_equal 0, ::AppTemplate::Application::User.count
+ end
end
end
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 0fe5cdc4a8..018c2fa6bf 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -64,6 +64,23 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "things-43/config/application.rb", /^module Things43$/
end
+ def test_application_new_exits_with_non_zero_code_on_invalid_application_name
+ # TODO: Suppress the output of this (it's because of a Thor::Error)
+ `rails new test`
+ assert_equal false, $?.success?
+ end
+
+ def test_application_new_exits_with_message_and_non_zero_code_when_generating_inside_existing_rails_directory
+ app_root = File.join(destination_root, 'myfirstapp')
+ run_generator [app_root]
+ output = nil
+ Dir.chdir(app_root) do
+ output = `rails new mysecondapp`
+ end
+ assert_equal "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\nType 'rails' for help.\n", output
+ assert_equal false, $?.success?
+ end
+
def test_application_name_is_detected_if_it_exists_and_app_folder_renamed
app_root = File.join(destination_root, "myapp")
app_moved_root = File.join(destination_root, "myapp_moved")
@@ -106,7 +123,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_config_database_is_added_by_default
run_generator
assert_file "config/database.yml", /sqlite3/
- assert_file "Gemfile", /^gem\s+["']sqlite3-ruby["'],\s+:require\s+=>\s+["']sqlite3["']$/
+ assert_file "Gemfile", /^gem\s+["']sqlite3["']$/
end
def test_config_another_database
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
index 288ec30460..6eecfc8e2e 100644
--- a/railties/test/generators/migration_generator_test.rb
+++ b/railties/test/generators/migration_generator_test.rb
@@ -34,15 +34,10 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
run_generator [migration, "title:string", "body:text"]
assert_migration "db/migrate/#{migration}.rb" do |content|
- assert_method :up, content do |up|
+ assert_method :change, content do |up|
assert_match /add_column :posts, :title, :string/, up
assert_match /add_column :posts, :body, :text/, up
end
-
- assert_method :down, content do |down|
- assert_match /remove_column :posts, :title/, down
- assert_match /remove_column :posts, :body/, down
- end
end
end
diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb
index 552b7eb30a..3d773b4134 100644
--- a/railties/test/generators/model_generator_test.rb
+++ b/railties/test/generators/model_generator_test.rb
@@ -99,15 +99,11 @@ class ModelGeneratorTest < Rails::Generators::TestCase
run_generator ["product", "name:string", "supplier_id:integer"]
assert_migration "db/migrate/create_products.rb" do |m|
- assert_method :up, m do |up|
+ assert_method :change, m do |up|
assert_match /create_table :products/, up
assert_match /t\.string :name/, up
assert_match /t\.integer :supplier_id/, up
end
-
- assert_method :down, m do |down|
- assert_match /drop_table :products/, down
- end
end
end
@@ -141,7 +137,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
run_generator ["account", "--no-timestamps"]
assert_migration "db/migrate/create_accounts.rb" do |m|
- assert_method :up, m do |up|
+ assert_method :change, m do |up|
assert_no_match /t.timestamps/, up
end
end
@@ -181,7 +177,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
run_generator
old_migration = Dir["#{destination_root}/db/migrate/*_create_accounts.rb"].first
error = capture(:stderr) { run_generator ["Account", "--force"] }
- assert_no_match /Another migration is already named create_foos/, error
+ assert_no_match /Another migration is already named create_accounts/, error
assert_no_file old_migration
assert_migration 'db/migrate/create_accounts.rb'
end
@@ -207,4 +203,45 @@ class ModelGeneratorTest < Rails::Generators::TestCase
content = capture(:stderr){ run_generator ["object"] }
assert_match /The name 'Object' is either already used in your application or reserved/, content
end
+
+ def test_index_is_added_for_belongs_to_association
+ run_generator ["account", "supplier:belongs_to"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match /add_index/, up
+ end
+ end
+ end
+
+ def test_index_is_added_for_references_association
+ run_generator ["account", "supplier:references"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match /add_index/, up
+ end
+ end
+ end
+
+ def test_index_is_skipped_for_belongs_to_association
+ run_generator ["account", "supplier:belongs_to", "--no-indexes"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match /add_index/, up
+ end
+ end
+ end
+
+ def test_index_is_skipped_for_references_association
+ run_generator ["account", "supplier:references", "--no-indexes"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match /add_index/, up
+ end
+ end
+ end
+
end
diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb
index 2a9e8046b8..2a8b337144 100644
--- a/railties/test/generators/plugin_new_generator_test.rb
+++ b/railties/test/generators/plugin_new_generator_test.rb
@@ -38,8 +38,10 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_file "things-43/lib/things-43.rb", /module Things43/
end
- def test_generating_test_files
+ def test_generating_without_options
run_generator
+ assert_file "README.rdoc", /Bukkits/
+ assert_no_file "config/routes.rb"
assert_file "test/test_helper.rb"
assert_file "test/bukkits_test.rb", /assert_kind_of Module, Bukkits/
end
@@ -66,7 +68,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
def test_database_entry_is_assed_by_default_in_full_mode
run_generator([destination_root, "--full"])
assert_file "test/dummy/config/database.yml", /sqlite/
- assert_file "Gemfile", /^gem\s+["']sqlite3-ruby["'],\s+:require\s+=>\s+["']sqlite3["']$/
+ assert_file "Gemfile", /^gem\s+["']sqlite3["']$/
end
def test_config_another_database
@@ -151,6 +153,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
def test_creating_engine_in_full_mode
run_generator [destination_root, "--full"]
+ assert_file "config/routes.rb", /Rails.application.routes.draw do/
assert_file "lib/bukkits/engine.rb", /module Bukkits\n class Engine < Rails::Engine\n end\nend/
assert_file "lib/bukkits.rb", /require "bukkits\/engine"/
end
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
index 346c9ceb9d..99c9d790eb 100644
--- a/railties/test/generators_test.rb
+++ b/railties/test/generators_test.rb
@@ -94,6 +94,14 @@ class GeneratorsTest < Rails::Generators::TestCase
assert_match /Rails 2\.x generator/, output
end
+ def test_invoke_with_nested_namespaces
+ model_generator = mock('ModelGenerator') do
+ expects(:start).with(["Account"], {})
+ end
+ Rails::Generators.expects(:find_by_namespace).with('namespace', 'my:awesome').returns(model_generator)
+ Rails::Generators.invoke 'my:awesome:namespace', ["Account"]
+ end
+
def test_rails_generators_help_with_builtin_information
output = capture(:stdout){ Rails::Generators.help }
assert_match /Rails:/, output
@@ -120,6 +128,16 @@ class GeneratorsTest < Rails::Generators::TestCase
assert_match /^ active_record:fixjour$/, output
end
+ def test_default_banner_should_show_generator_namespace
+ klass = Rails::Generators.find_by_namespace(:foobar)
+ assert_match /^rails generate foobar:foobar/, klass.banner
+ end
+
+ def test_default_banner_should_not_show_rails_generator_namespace
+ klass = Rails::Generators.find_by_namespace(:model)
+ assert_match /^rails generate model/, klass.banner
+ end
+
def test_no_color_sets_proper_shell
Rails::Generators.no_color!
assert_equal Thor::Shell::Basic, Thor::Base.shell
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 92aa025238..0ce00db3c4 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -306,6 +306,34 @@ module RailtiesTest
assert_equal File.read(File.join(app_path, "public/bukkits/file_from_app.html")), last_response.body
end
+ test "an applications files are given priority over an engines files when served via ActionDispatch::Static" do
+ add_to_config "config.serve_static_assets = true"
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ class Engine < ::Rails::Engine
+ engine_name :bukkits
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ mount Bukkits::Engine => "/bukkits"
+ end
+ RUBY
+
+ @plugin.write "public/bukkits.html", "in engine"
+
+ app_file "public/bukkits/bukkits.html", "in app"
+
+ boot_rails
+
+ get('/bukkits/bukkits.html')
+
+ assert_equal 'in app', last_response.body.strip
+ end
+
test "shared engine should include application's helpers and own helpers" do
app_file "config/routes.rb", <<-RUBY
AppTemplate::Application.routes.draw do
diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb
index 31ba2eaca2..3eb79d57c8 100644
--- a/railties/test/railties/shared_tests.rb
+++ b/railties/test/railties/shared_tests.rb
@@ -294,7 +294,7 @@ YAML
boot_rails
- assert_equal %W(
+ expected_locales = %W(
#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/locale/en.yml
#{RAILS_FRAMEWORK_ROOT}/activemodel/lib/active_model/locale/en.yml
#{RAILS_FRAMEWORK_ROOT}/activerecord/lib/active_record/locale/en.yml
@@ -302,7 +302,13 @@ YAML
#{@plugin.path}/config/locales/en.yml
#{app_path}/config/locales/en.yml
#{app_path}/app/locales/en.yml
- ).map { |path| File.expand_path(path) }, I18n.load_path.map { |path| File.expand_path(path) }
+ ).map { |path| File.expand_path(path) }
+
+ actual_locales = I18n.load_path.map { |path|
+ File.expand_path(path)
+ } & expected_locales # remove locales external to Rails
+
+ assert_equal expected_locales, actual_locales
assert_equal "2", I18n.t(:foo)
assert_equal "1", I18n.t(:bar)