aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Gemfile5
-rw-r--r--actionmailer/lib/action_mailer.rb1
-rw-r--r--actionmailer/lib/action_mailer/railtie.rb6
-rw-r--r--actionmailer/test/old_base/mail_service_test.rb5
-rw-r--r--actionpack/CHANGELOG8
-rw-r--r--actionpack/RUNNING_UNIT_TESTS13
-rw-r--r--actionpack/lib/abstract_controller/base.rb1
-rw-r--r--actionpack/lib/abstract_controller/rendering.rb5
-rw-r--r--actionpack/lib/action_controller/metal.rb5
-rw-r--r--actionpack/lib/action_controller/metal/head.rb6
-rw-r--r--actionpack/lib/action_controller/metal/rendering.rb1
-rw-r--r--actionpack/lib/action_controller/metal/responder.rb20
-rw-r--r--actionpack/lib/action_controller/metal/streaming.rb4
-rw-r--r--actionpack/lib/action_controller/railtie.rb8
-rw-r--r--actionpack/lib/action_controller/railties/paths.rb6
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/show_exceptions.rb13
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb58
-rw-r--r--actionpack/lib/action_view.rb22
-rw-r--r--actionpack/lib/action_view/base.rb42
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helper.rb5
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb11
-rw-r--r--actionpack/lib/action_view/helpers/form_tag_helper.rb4
-rw-r--r--actionpack/lib/action_view/helpers/prototype_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/translation_helper.rb4
-rw-r--r--actionpack/lib/action_view/helpers/url_helper.rb12
-rw-r--r--actionpack/lib/action_view/lookup_context.rb31
-rw-r--r--actionpack/lib/action_view/partials.rb (renamed from actionpack/lib/action_view/render/partials.rb)161
-rw-r--r--actionpack/lib/action_view/path_set.rb (renamed from actionpack/lib/action_view/paths.rb)4
-rw-r--r--actionpack/lib/action_view/render/rendering.rb67
-rw-r--r--actionpack/lib/action_view/renderer/abstract_renderer.rb36
-rw-r--r--actionpack/lib/action_view/renderer/partial_renderer.rb166
-rw-r--r--actionpack/lib/action_view/renderer/template_renderer.rb98
-rw-r--r--actionpack/lib/action_view/rendering.rb (renamed from actionpack/lib/action_view/render/layouts.rb)63
-rw-r--r--actionpack/lib/action_view/template.rb145
-rw-r--r--actionpack/lib/action_view/template/error.rb5
-rw-r--r--actionpack/lib/action_view/template/handler.rb10
-rw-r--r--actionpack/lib/action_view/template/handlers.rb10
-rw-r--r--actionpack/lib/action_view/template/handlers/builder.rb8
-rw-r--r--actionpack/lib/action_view/template/handlers/erb.rb25
-rw-r--r--actionpack/lib/action_view/template/handlers/rjs.rb12
-rw-r--r--actionpack/lib/action_view/template/resolver.rb115
-rw-r--r--actionpack/lib/action_view/template/text.rb4
-rw-r--r--actionpack/lib/action_view/testing/resolvers.rb13
-rw-r--r--actionpack/test/controller/content_type_test.rb24
-rw-r--r--actionpack/test/controller/layout_test.rb18
-rw-r--r--actionpack/test/controller/mime_responds_test.rb19
-rw-r--r--actionpack/test/controller/new_base/bare_metal_test.rb15
-rw-r--r--actionpack/test/controller/new_base/render_once_test.rb86
-rw-r--r--actionpack/test/controller/new_base/render_partial_test.rb17
-rw-r--r--actionpack/test/controller/new_base/render_template_test.rb26
-rw-r--r--actionpack/test/dispatch/request_test.rb12
-rw-r--r--actionpack/test/dispatch/show_exceptions_test.rb20
-rw-r--r--actionpack/test/fixtures/layout_tests/alt/hello.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/alt/hello.rhtml1
-rw-r--r--actionpack/test/fixtures/layout_tests/alt/layouts/alt.erb (renamed from actionpack/test/fixtures/layout_tests/alt/layouts/alt.rhtml)0
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.rhtml1
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/item.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/item.rhtml1
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/layout_test.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/layout_test.rhtml1
-rw-r--r--actionpack/test/fixtures/layout_tests/views/goodbye.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/views/goodbye.rhtml1
-rw-r--r--actionpack/test/fixtures/layout_tests/views/hello.erb1
-rw-r--r--actionpack/test/fixtures/layout_tests/views/hello.rhtml1
-rw-r--r--actionpack/test/fixtures/old_content_type/render_default_for_builder.builder (renamed from actionpack/test/fixtures/old_content_type/render_default_for_rxml.rxml)0
-rw-r--r--actionpack/test/fixtures/old_content_type/render_default_for_erb.erb (renamed from actionpack/test/fixtures/old_content_type/render_default_for_rhtml.rhtml)0
-rw-r--r--actionpack/test/fixtures/test/_object_inspector.erb1
-rw-r--r--actionpack/test/template/form_helper_test.rb45
-rw-r--r--actionpack/test/template/form_tag_helper_test.rb10
-rw-r--r--actionpack/test/template/log_subscriber_test.rb6
-rw-r--r--actionpack/test/template/lookup_context_test.rb66
-rw-r--r--actionpack/test/template/render_test.rb17
-rw-r--r--actionpack/test/template/template_test.rb110
-rw-r--r--actionpack/test/template/translation_helper_test.rb4
-rw-r--r--actionpack/test/template/url_helper_test.rb23
-rw-r--r--activemodel/lib/active_model.rb3
-rw-r--r--activemodel/lib/active_model/validations.rb2
-rw-r--r--activerecord/RUNNING_UNIT_TESTS7
-rw-r--r--activerecord/lib/active_record.rb4
-rw-r--r--activerecord/lib/active_record/base.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb16
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/quoting.rb45
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb9
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb6
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb4
-rw-r--r--activerecord/lib/active_record/migration.rb41
-rw-r--r--activerecord/lib/active_record/railties/databases.rake50
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb14
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb4
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb11
-rw-r--r--activerecord/lib/active_record/relation/spawn_methods.rb11
-rw-r--r--activerecord/lib/active_record/serialization.rb2
-rw-r--r--activerecord/lib/active_record/test_case.rb15
-rw-r--r--activerecord/test/cases/calculations_test.rb9
-rw-r--r--activerecord/test/cases/connection_pool_test.rb29
-rw-r--r--activerecord/test/cases/locking_test.rb3
-rw-r--r--activerecord/test/cases/migration_test.rb64
-rw-r--r--activerecord/test/cases/quoting_test.rb220
-rw-r--r--activerecord/test/cases/relation_scoping_test.rb10
-rw-r--r--activerecord/test/cases/relations_test.rb6
-rw-r--r--activerecord/test/cases/transactions_test.rb2
-rw-r--r--activerecord/test/migrations/to_copy2/1_create_articles.rb7
-rw-r--r--activerecord/test/migrations/to_copy2/2_create_comments.rb7
-rw-r--r--activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb7
-rw-r--r--activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb7
-rw-r--r--activerecord/test/models/developer.rb1
-rw-r--r--activeresource/lib/active_resource.rb1
-rw-r--r--activeresource/lib/active_resource/http_mock.rb56
-rw-r--r--activeresource/test/cases/http_mock_test.rb36
-rw-r--r--activesupport/lib/active_support.rb1
-rw-r--r--activesupport/lib/active_support/cache/mem_cache_store.rb2
-rw-r--r--activesupport/lib/active_support/callbacks.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/logger.rb49
-rw-r--r--activesupport/lib/active_support/hash_with_indifferent_access.rb2
-rw-r--r--activesupport/lib/active_support/ordered_hash.rb7
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb10
-rw-r--r--railties/CHANGELOG6
-rw-r--r--railties/Rakefile5
-rw-r--r--railties/guides/source/action_mailer_basics.textile16
-rw-r--r--railties/guides/source/action_view_overview.textile3
-rw-r--r--railties/guides/source/getting_started.textile11
-rw-r--r--railties/guides/source/initialization.textile2
-rw-r--r--railties/guides/source/routing.textile2
-rw-r--r--railties/lib/rails.rb2
-rw-r--r--railties/lib/rails/application.rb9
-rw-r--r--railties/lib/rails/application/bootstrap.rb2
-rw-r--r--railties/lib/rails/application/configuration.rb18
-rw-r--r--railties/lib/rails/application/finisher.rb2
-rw-r--r--railties/lib/rails/application/routes_reloader.rb24
-rw-r--r--railties/lib/rails/engine.rb192
-rw-r--r--railties/lib/rails/engine/configuration.rb43
-rw-r--r--railties/lib/rails/engine/railties.rb2
-rw-r--r--railties/lib/rails/generators/actions.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb32
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js6078
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js132
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js (renamed from railties/lib/rails/generators/rails/app/templates/public/javascripts/rails.js)85
-rw-r--r--railties/lib/rails/paths.rb154
-rw-r--r--railties/lib/rails/plugin.rb6
-rw-r--r--railties/lib/rails/railtie.rb7
-rw-r--r--railties/lib/rails/tasks/documentation.rake2
-rw-r--r--railties/lib/rails/tasks/framework.rake2
-rw-r--r--railties/lib/rails/tasks/railties.rake33
-rw-r--r--railties/lib/rails/test_unit/testing.rake7
-rw-r--r--railties/test/application/configuration_test.rb4
-rw-r--r--railties/test/application/console_test.rb5
-rw-r--r--railties/test/application/generators_test.rb2
-rw-r--r--railties/test/application/paths_test.rb28
-rw-r--r--railties/test/generators/app_generator_test.rb34
-rw-r--r--railties/test/generators/namespaced_generators_test.rb4
-rw-r--r--railties/test/paths_test.rb268
-rw-r--r--railties/test/railties/engine_test.rb80
-rw-r--r--railties/test/railties/mounted_engine_test.rb2
-rw-r--r--railties/test/railties/plugin_test.rb2
-rw-r--r--railties/test/railties/railtie_test.rb24
-rw-r--r--railties/test/railties/shared_tests.rb65
160 files changed, 8646 insertions, 1320 deletions
diff --git a/Gemfile b/Gemfile
index 7fe1c3ad22..13bf277d7a 100644
--- a/Gemfile
+++ b/Gemfile
@@ -55,6 +55,11 @@ platforms :jruby do
gem "activerecord-jdbcsqlite3-adapter"
+ # This is needed by now to let tests work on JRuby
+ # TODO: When the JRuby guys merge jruby-openssl in
+ # jruby this will be removed
+ gem "jruby-openssl"
+
group :db do
gem "activerecord-jdbcmysql-adapter"
gem "activerecord-jdbcpostgresql-adapter"
diff --git a/actionmailer/lib/action_mailer.rb b/actionmailer/lib/action_mailer.rb
index 05ba12197a..02a9916703 100644
--- a/actionmailer/lib/action_mailer.rb
+++ b/actionmailer/lib/action_mailer.rb
@@ -26,6 +26,7 @@ $:.unshift(actionpack_path) if File.directory?(actionpack_path) && !$:.include?(
require 'abstract_controller'
require 'action_view'
+require 'action_mailer/version'
# Common Active Support usage in Action Mailer
require 'active_support/core_ext/class'
diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb
index 86136bdafd..d67a5b6521 100644
--- a/actionmailer/lib/action_mailer/railtie.rb
+++ b/actionmailer/lib/action_mailer/railtie.rb
@@ -14,9 +14,9 @@ module ActionMailer
paths = app.config.paths
options = app.config.action_mailer
- options.assets_dir ||= paths.public.to_a.first
- options.javascripts_dir ||= paths.public.javascripts.to_a.first
- options.stylesheets_dir ||= paths.public.stylesheets.to_a.first
+ options.assets_dir ||= paths["public"].first
+ options.javascripts_dir ||= paths["public/javascripts"].first
+ options.stylesheets_dir ||= paths["public/stylesheets"].first
# make sure readers methods get compiled
options.asset_path ||= nil
diff --git a/actionmailer/test/old_base/mail_service_test.rb b/actionmailer/test/old_base/mail_service_test.rb
index 93921978b6..0b5b0b2da3 100644
--- a/actionmailer/test/old_base/mail_service_test.rb
+++ b/actionmailer/test/old_base/mail_service_test.rb
@@ -328,7 +328,6 @@ class ActionMailerTest < Test::Unit::TestCase
mail
end
- # Replacing logger work around for mocha bug. Should be fixed in mocha 0.3.3
def setup
set_delivery_method :test
ActionMailer::Base.perform_deliveries = true
@@ -336,14 +335,12 @@ class ActionMailerTest < Test::Unit::TestCase
ActionMailer::Base.deliveries.clear
ActiveSupport::Deprecation.silenced = true
- @original_logger = TestMailer.logger
@recipient = 'test@localhost'
TestMailer.delivery_method = :test
end
def teardown
- TestMailer.logger = @original_logger
ActiveSupport::Deprecation.silenced = false
restore_delivery_method
end
@@ -1097,4 +1094,4 @@ EOF
ensure
TestMailer.smtp_settings.merge!(:enable_starttls_auto => true)
end
-end \ No newline at end of file
+end
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
index 6352b97a6b..3f8188b1f7 100644
--- a/actionpack/CHANGELOG
+++ b/actionpack/CHANGELOG
@@ -1,5 +1,13 @@
*Rails 3.1.0 (unreleased)*
+* Added render :once. You can pass either a string or an array of strings and Rails will ensure they each of them are rendered just once. [José Valim]
+
+* Deprecate old template handler API. The new API simply requires a template handler to respond to call. [José Valim]
+
+* :rhtml and :rxml were finally removed as template handlers. [José Valim]
+
+* Moved etag responsibility from ActionDispatch::Response to the middleware stack. [José Valim]
+
* Rely on Rack::Session stores API for more compatibility across the Ruby world. This is backwards incompatible since Rack::Session expects #get_session to accept 4 arguments and requires #destroy_session instead of simply #destroy. [José Valim]
* file_field automatically adds :multipart => true to the enclosing form. [Santiago Pastorino]
diff --git a/actionpack/RUNNING_UNIT_TESTS b/actionpack/RUNNING_UNIT_TESTS
index d6a1ccf871..1e3ba7abe7 100644
--- a/actionpack/RUNNING_UNIT_TESTS
+++ b/actionpack/RUNNING_UNIT_TESTS
@@ -8,15 +8,18 @@ Rake can be found at http://rake.rubyforge.org
== Running by hand
-If you only want to run a single test suite, or don't want to bother with Rake,
-you can do so with something like:
+To run a single test suite
- ruby -Itest test/controller/base_tests.rb
+ rake test TEST=path/to/test.rb
-== Dependency on ActiveRecord and database setup
+which can be further narrowed down to one test:
+
+ rake test TEST=path/to/test.rb TESTOPTS="--name=test_something"
+
+== Dependency on Active Record and database setup
Test cases in the test/controller/active_record/ directory depend on having
-activerecord and sqlite installed. If ActiveRecord is not in
+activerecord and sqlite installed. If Active Record is not in
actionpack/../activerecord directory, or the sqlite rubygem is not installed,
these tests are skipped.
diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb
index f9f6eb945e..f83eaded88 100644
--- a/actionpack/lib/abstract_controller/base.rb
+++ b/actionpack/lib/abstract_controller/base.rb
@@ -13,6 +13,7 @@ module AbstractController
class Base
attr_internal :response_body
attr_internal :action_name
+ attr_internal :formats
include ActiveSupport::Configurable
extend ActiveSupport::DescendantsTracker
diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb
index 5d9b35d297..1c63fb2d14 100644
--- a/actionpack/lib/abstract_controller/rendering.rb
+++ b/actionpack/lib/abstract_controller/rendering.rb
@@ -12,7 +12,6 @@ module AbstractController
# This is a class to fix I18n global state. Whenever you provide I18n.locale during a request,
# it will trigger the lookup_context and consequently expire the cache.
- # TODO Add some deprecation warnings to remove I18n.locale from controllers
class I18nProxy < ::I18n::Config #:nodoc:
attr_reader :i18n_config, :lookup_context
@@ -50,7 +49,7 @@ module AbstractController
if controller.respond_to?(:_helpers)
include controller._helpers
- if controller.respond_to?(:_routes)
+ if controller.respond_to?(:_routes) && controller._routes
include controller._routes.url_helpers
include controller._routes.mounted_helpers
end
@@ -156,7 +155,7 @@ module AbstractController
options[:partial] = action_name
end
- if (options.keys & [:partial, :file, :template]).empty?
+ if (options.keys & [:partial, :file, :template, :once]).empty?
options[:prefix] ||= _prefix
end
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
index ace1aabe03..329798e84f 100644
--- a/actionpack/lib/action_controller/metal.rb
+++ b/actionpack/lib/action_controller/metal.rb
@@ -119,6 +119,11 @@ module ActionController
headers["Location"] = url
end
+ # basic url_for that can be overridden for more robust functionality
+ def url_for(string)
+ string
+ end
+
def status
@_status
end
diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb
index 2b4a3b9392..8abcad55a2 100644
--- a/actionpack/lib/action_controller/metal/head.rb
+++ b/actionpack/lib/action_controller/metal/head.rb
@@ -2,8 +2,6 @@ module ActionController
module Head
extend ActiveSupport::Concern
- include ActionController::UrlFor
-
# Return a response that has no content (merely headers). The options
# argument is interpreted to be a hash of header names and values.
# This allows you to easily return a response that consists only of
@@ -27,8 +25,8 @@ module ActionController
self.status = status
self.location = url_for(location) if location
- self.content_type = Mime[formats.first]
+ self.content_type = Mime[formats.first] if formats
self.response_body = " "
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb
index 86bb810947..e524e546ad 100644
--- a/actionpack/lib/action_controller/metal/rendering.rb
+++ b/actionpack/lib/action_controller/metal/rendering.rb
@@ -2,7 +2,6 @@ module ActionController
module Rendering
extend ActiveSupport::Concern
- include ActionController::RackDelegation
include AbstractController::Rendering
# Before processing, set the request formats in current controller formats.
diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb
index 851925e1b7..38d32211cc 100644
--- a/actionpack/lib/action_controller/metal/responder.rb
+++ b/actionpack/lib/action_controller/metal/responder.rb
@@ -161,6 +161,8 @@ module ActionController #:nodoc:
display resource.errors, :status => :unprocessable_entity
elsif post?
display resource, :status => :created, :location => api_location
+ elsif has_empty_resource_definition?
+ display empty_resource, :status => :ok
else
head :ok
end
@@ -221,5 +223,23 @@ module ActionController #:nodoc:
def default_action
@action ||= ACTIONS_FOR_VERBS[request.request_method_symbol]
end
+
+ # Check whether resource needs a specific definition of empty resource to be valid
+ #
+ def has_empty_resource_definition?
+ respond_to?("empty_#{format}_resource")
+ end
+
+ # Delegate to proper empty resource method
+ #
+ def empty_resource
+ send("empty_#{format}_resource")
+ end
+
+ # Return a valid empty JSON resource
+ #
+ def empty_json_resource
+ "{}"
+ end
end
end
diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb
index 2013da3adb..312dc8eb3e 100644
--- a/actionpack/lib/action_controller/metal/streaming.rb
+++ b/actionpack/lib/action_controller/metal/streaming.rb
@@ -101,10 +101,6 @@ module ActionController #:nodoc:
# send_data image.data, :type => image.content_type, :disposition => 'inline'
#
# See +send_file+ for more information on HTTP Content-* headers and caching.
- #
- # <b>Tip:</b> if you want to stream large amounts of on-the-fly generated
- # data to the browser, then use <tt>render :text => proc { ... }</tt>
- # instead. See ActionController::Base#render for more information.
def send_data(data, options = {}) #:doc:
send_file_headers! options.dup
render options.slice(:status, :content_type).merge(:text => data)
diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb
index 0ade42ba2d..c5a661f2b0 100644
--- a/actionpack/lib/action_controller/railtie.rb
+++ b/actionpack/lib/action_controller/railtie.rb
@@ -21,10 +21,10 @@ module ActionController
paths = app.config.paths
options = app.config.action_controller
- options.assets_dir ||= paths.public.to_a.first
- options.javascripts_dir ||= paths.public.javascripts.to_a.first
- options.stylesheets_dir ||= paths.public.stylesheets.to_a.first
- options.page_cache_directory ||= paths.public.to_a.first
+ options.assets_dir ||= paths["public"].first
+ options.javascripts_dir ||= paths["public/javascripts"].first
+ options.stylesheets_dir ||= paths["public/stylesheets"].first
+ options.page_cache_directory ||= paths["public"].first
# make sure readers methods get compiled
options.asset_path ||= nil
diff --git a/actionpack/lib/action_controller/railties/paths.rb b/actionpack/lib/action_controller/railties/paths.rb
index fa71d55946..7a59d4f2f3 100644
--- a/actionpack/lib/action_controller/railties/paths.rb
+++ b/actionpack/lib/action_controller/railties/paths.rb
@@ -5,12 +5,14 @@ module ActionController
Module.new do
define_method(:inherited) do |klass|
super(klass)
+
if namespace = klass.parents.detect {|m| m.respond_to?(:_railtie) }
- klass.helpers_path = namespace._railtie.config.paths.app.helpers.to_a
+ paths = namespace._railtie.paths["app/helpers"].existent
else
- klass.helpers_path = app.config.helpers_paths
+ paths = app.config.helpers_paths
end
+ klass.helpers_path = paths
klass.helper :all if klass.superclass == ActionController::Base
end
end
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index bbcdefb190..55a3166f6d 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -214,13 +214,13 @@ module ActionDispatch
# Override Rack's GET method to support indifferent access
def GET
- @env["action_dispatch.request.query_parameters"] ||= normalize_parameters(super)
+ @env["action_dispatch.request.query_parameters"] ||= (normalize_parameters(super) || {})
end
alias :query_parameters :GET
# Override Rack's POST method to support indifferent access
def POST
- @env["action_dispatch.request.request_parameters"] ||= normalize_parameters(super)
+ @env["action_dispatch.request.request_parameters"] ||= (normalize_parameters(super) || {})
end
alias :request_parameters :POST
diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
index ef0c9c51f5..71e736ce9f 100644
--- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -62,6 +62,7 @@ module ActionDispatch
private
def render_exception(env, exception)
log_error(exception)
+ exception = original_exception(exception)
request = Request.new(env)
if @consider_all_requests_local || request.local?
@@ -154,5 +155,17 @@ module ActionDispatch
def logger
defined?(Rails.logger) ? Rails.logger : Logger.new($stderr)
end
+
+ def original_exception(exception)
+ if registered_original_exception?(exception)
+ exception.original_exception
+ else
+ exception
+ end
+ end
+
+ def registered_original_exception?(exception)
+ exception.respond_to?(:original_exception) && @@rescue_responses.has_key?(exception.original_exception.class.name)
+ end
end
end
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index bf10f81127..3c7dcea003 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -735,15 +735,15 @@ module ActionDispatch
resource_scope(SingletonResource.new(resources.pop, options)) do
yield if block_given?
- collection_scope do
+ collection do
post :create
end if parent_resource.actions.include?(:create)
- new_scope do
+ new do
get :new
end if parent_resource.actions.include?(:new)
- member_scope do
+ member do
get :edit if parent_resource.actions.include?(:edit)
get :show if parent_resource.actions.include?(:show)
put :update if parent_resource.actions.include?(:update)
@@ -780,16 +780,16 @@ module ActionDispatch
resource_scope(Resource.new(resources.pop, options)) do
yield if block_given?
- collection_scope do
+ collection do
get :index if parent_resource.actions.include?(:index)
post :create if parent_resource.actions.include?(:create)
end
- new_scope do
+ new do
get :new
end if parent_resource.actions.include?(:new)
- member_scope do
+ member do
get :edit if parent_resource.actions.include?(:edit)
get :show if parent_resource.actions.include?(:show)
put :update if parent_resource.actions.include?(:update)
@@ -813,12 +813,14 @@ module ActionDispatch
# create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
# route helpers.
def collection
- unless @scope[:scope_level] == :resources
- raise ArgumentError, "can't use collection outside resources scope"
+ unless resource_scope?
+ raise ArgumentError, "can't use collection outside resource(s) scope"
end
- collection_scope do
- yield
+ with_scope_level(:collection) do
+ scope(parent_resource.collection_scope) do
+ yield
+ end
end
end
@@ -838,8 +840,10 @@ module ActionDispatch
raise ArgumentError, "can't use member outside resource(s) scope"
end
- member_scope do
- yield
+ with_scope_level(:member) do
+ scope(parent_resource.member_scope) do
+ yield
+ end
end
end
@@ -848,8 +852,10 @@ module ActionDispatch
raise ArgumentError, "can't use new outside resource(s) scope"
end
- new_scope do
- yield
+ with_scope_level(:new) do
+ scope(parent_resource.new_scope(action_path(:new))) do
+ yield
+ end
end
end
@@ -1034,30 +1040,6 @@ module ActionDispatch
end
end
- def new_scope
- with_scope_level(:new) do
- scope(parent_resource.new_scope(action_path(:new))) do
- yield
- end
- end
- end
-
- def collection_scope
- with_scope_level(:collection) do
- scope(parent_resource.collection_scope) do
- yield
- end
- end
- end
-
- def member_scope
- with_scope_level(:member) do
- scope(parent_resource.member_scope) do
- yield
- end
- end
- end
-
def nested_options
{}.tap do |options|
options[:as] = parent_resource.member_name
diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb
index 5f9dc70766..dada64a86f 100644
--- a/actionpack/lib/action_view.rb
+++ b/actionpack/lib/action_view.rb
@@ -21,9 +21,6 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
-$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
require 'active_support/ruby/shim'
require 'active_support/core_ext/class/attribute_accessors'
@@ -33,24 +30,27 @@ module ActionView
extend ActiveSupport::Autoload
eager_autoload do
+ autoload :Base
autoload :Context
- autoload :Template
autoload :Helpers
- autoload :Base
autoload :LookupContext
- autoload :PathSet, "action_view/paths"
- autoload :TestCase, "action_view/test_case"
+ autoload :Partials
+ autoload :PathSet
+ autoload :Rendering
+ autoload :Template
+ autoload :TestCase
- autoload_under "render" do
- autoload :Layouts
- autoload :Partials
- autoload :Rendering
+ autoload_under "renderer" do
+ autoload :AbstractRenderer
+ autoload :PartialRenderer
+ autoload :TemplateRenderer
end
autoload_at "action_view/template/resolver" do
autoload :Resolver
autoload :PathResolver
autoload :FileSystemResolver
+ autoload :FallbackFileSystemResolver
end
autoload_at "action_view/template/error" do
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index 0bef3e3a08..1beae37af3 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -155,10 +155,7 @@ module ActionView #:nodoc:
#
# See the ActionView::Helpers::PrototypeHelper::JavaScriptGenerator::GeneratorMethods documentation for more details.
class Base
- module Subclasses
- end
-
- include Helpers, Rendering, Partials, Layouts, ::ERB::Util, Context
+ include Helpers, Rendering, Partials, ::ERB::Util, Context
# Specify whether RJS responses should be wrapped in a try/catch block
# that alert()s the caught exception (and then re-raises it).
@@ -177,13 +174,12 @@ module ActionView #:nodoc:
delegate :logger, :to => 'ActionController::Base', :allow_nil => true
end
- attr_accessor :base_path, :assigns, :template_extension, :lookup_context
- attr_internal :captures, :request, :controller, :template, :config
+ attr_accessor :_template
+ attr_internal :request, :controller, :config, :assigns, :lookup_context
- delegate :find_template, :template_exists?, :formats, :formats=, :locale, :locale=,
- :view_paths, :view_paths=, :with_fallbacks, :update_details, :with_layout_format, :to => :lookup_context
+ delegate :formats, :formats=, :locale, :locale=, :view_paths, :view_paths=, :to => :lookup_context
- delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers,
+ delegate :request_forgery_protection_token, :params, :session, :cookies, :response, :headers,
:flash, :action_name, :controller_name, :to => :controller
delegate :logger, :to => :controller, :allow_nil => true
@@ -198,32 +194,40 @@ module ActionView #:nodoc:
end
def assign(new_assigns) # :nodoc:
- self.assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) }
+ @_assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) }
end
def initialize(lookup_context = nil, assigns_for_first_render = {}, controller = nil, formats = nil) #:nodoc:
assign(assigns_for_first_render)
- self.helpers = self.class.helpers || Module.new
-
- if @_controller = controller
- @_request = controller.request if controller.respond_to?(:request)
- end
-
- @_config = controller && controller.respond_to?(:config) ? controller.config.inheritable_copy : {}
+ self.helpers = Module.new unless self.class.helpers
+ @_config = {}
@_content_for = Hash.new { |h,k| h[k] = ActiveSupport::SafeBuffer.new }
@_virtual_path = nil
@output_buffer = nil
- @lookup_context = lookup_context.is_a?(ActionView::LookupContext) ?
+ if @_controller = controller
+ @_request = controller.request if controller.respond_to?(:request)
+ @_config = controller.config.inheritable_copy if controller.respond_to?(:config)
+ end
+
+ @_lookup_context = lookup_context.is_a?(ActionView::LookupContext) ?
lookup_context : ActionView::LookupContext.new(lookup_context)
- @lookup_context.formats = formats if formats
+ @_lookup_context.formats = formats if formats
+ end
+
+ def store_content_for(key, value)
+ @_content_for[key] = value
end
def controller_path
@controller_path ||= controller && controller.controller_path
end
+ def controller_prefix
+ @controller_prefix ||= controller && controller._prefix
+ end
+
ActiveSupport.run_load_hooks(:action_view, self)
end
end
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
index c1dfbe5dc3..d0f91f6b71 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
@@ -152,7 +152,7 @@ module ActionView
#
# # Normally you'd calculate RELEASE_NUMBER at startup.
# RELEASE_NUMBER = 12345
- # config.action_controller.asset_path_template = proc { |asset_path|
+ # config.action_controller.asset_path = proc { |asset_path|
# "/release-#{RELEASE_NUMBER}#{asset_path}"
# }
#
@@ -292,9 +292,6 @@ module ActionView
#
# * = The application.js file is only referenced if it exists
#
- # Though it's not really recommended practice, if you need to extend the default JavaScript set for any reason
- # (e.g., you're going to be using a certain .js file in every action), then take a look at the register_javascript_include_default method.
- #
# You can also include all javascripts in the +javascripts+ directory using <tt>:all</tt> as the source:
#
# javascript_include_tag :all # =>
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index 3cd8b02bc4..b34a74788e 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -1020,14 +1020,9 @@ module ActionView
def value_before_type_cast(object, method_name)
unless object.nil?
- if object.respond_to?(method_name)
- object.send(method_name)
- # FIXME: this is AR dependent
- elsif object.respond_to?(method_name + "_before_type_cast")
- object.send(method_name + "_before_type_cast")
- else
- raise NoMethodError, "Model #{object.class} does not respond to #{method_name}"
- end
+ object.respond_to?(method_name + "_before_type_cast") ?
+ object.send(method_name + "_before_type_cast") :
+ object.send(method_name)
end
end
diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb
index 298db46177..ae83b6bf39 100644
--- a/actionpack/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb
@@ -390,7 +390,7 @@ module ActionView
end
if confirm = options.delete("confirm")
- add_confirm_to_attributes!(options, confirm)
+ options["data-confirm"] = confirm
end
tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options.stringify_keys)
@@ -423,7 +423,7 @@ module ActionView
options.stringify_keys!
if confirm = options.delete("confirm")
- add_confirm_to_attributes!(options, confirm)
+ options["data-confirm"] = confirm
end
tag :input, { "type" => "image", "src" => path_to_image(source) }.update(options.stringify_keys)
diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb
index 300207dfac..41cd8d5171 100644
--- a/actionpack/lib/action_view/helpers/prototype_helper.rb
+++ b/actionpack/lib/action_view/helpers/prototype_helper.rb
@@ -546,7 +546,7 @@ module ActionView
end
def with_formats(*args)
- @context ? @context.update_details(:formats => args) { yield } : yield
+ @context ? @context.lookup_context.update_details(:formats => args) { yield } : yield
end
def javascript_object_for(object)
diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb
index 13767a09f9..8574ca6595 100644
--- a/actionpack/lib/action_view/helpers/translation_helper.rb
+++ b/actionpack/lib/action_view/helpers/translation_helper.rb
@@ -45,8 +45,8 @@ module ActionView
private
def scope_key_by_partial(key)
if key.to_s.first == "."
- if @_virtual_path
- @_virtual_path.gsub(%r{/_?}, ".") + key.to_s
+ if (path = @_template && @_template.virtual_path)
+ path.gsub(%r{/_?}, ".") + key.to_s
else
raise "Cannot use t(#{key.inspect}) shortcut because path is not available"
end
diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb
index da42d94318..c007cac47f 100644
--- a/actionpack/lib/action_view/helpers/url_helper.rb
+++ b/actionpack/lib/action_view/helpers/url_helper.rb
@@ -587,10 +587,12 @@ module ActionView
html_options = html_options.stringify_keys
html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options)
+ disable_with = html_options.delete("disable_with")
confirm = html_options.delete('confirm')
method = html_options.delete('method')
- add_confirm_to_attributes!(html_options, confirm) if confirm
+ html_options["data-disable-with"] = disable_with if disable_with
+ html_options["data-confirm"] = confirm if confirm
add_method_to_attributes!(html_options, method) if method
html_options
@@ -601,13 +603,9 @@ module ActionView
options.is_a?(Hash) && options.key?('remote') && options.delete('remote')
end
- def add_confirm_to_attributes!(html_options, confirm)
- html_options["data-confirm"] = confirm if confirm
- end
-
def add_method_to_attributes!(html_options, method)
- html_options["rel"] = "nofollow" if method && method.to_s.downcase != "get"
- html_options["data-method"] = method if method
+ html_options["rel"] = "nofollow" if method.to_s.downcase != "get"
+ html_options["data-method"] = method
end
def options_for_javascript(options)
diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb
index 3ea8b86af1..27f94a73a6 100644
--- a/actionpack/lib/action_view/lookup_context.rb
+++ b/actionpack/lib/action_view/lookup_context.rb
@@ -10,7 +10,7 @@ module ActionView
# this key is generated just once during the request, it speeds up all cache accesses.
class LookupContext #:nodoc:
mattr_accessor :fallbacks
- @@fallbacks = [FileSystemResolver.new(""), FileSystemResolver.new("/")]
+ @@fallbacks = FallbackFileSystemResolver.instances
mattr_accessor :registered_details
self.registered_details = []
@@ -61,6 +61,7 @@ module ActionView
def initialize(view_paths, details = {})
@details, @details_key = { :handlers => default_handlers }, nil
@frozen_formats, @skip_default_locale = false, false
+ @cache = true
self.view_paths = view_paths
self.registered_detail_setters.each do |key, setter|
@@ -77,17 +78,17 @@ module ActionView
@view_paths = ActionView::Base.process_view_paths(paths)
end
- def find(name, prefix = nil, partial = false)
- @view_paths.find(*args_for_lookup(name, prefix, partial))
+ def find(name, prefix = nil, partial = false, keys = [])
+ @view_paths.find(*args_for_lookup(name, prefix, partial, keys))
end
alias :find_template :find
- def find_all(name, prefix = nil, partial = false)
- @view_paths.find_all(*args_for_lookup(name, prefix, partial))
+ def find_all(name, prefix = nil, partial = false, keys = [])
+ @view_paths.find_all(*args_for_lookup(name, prefix, partial, keys))
end
- def exists?(name, prefix = nil, partial = false)
- @view_paths.exists?(*args_for_lookup(name, prefix, partial))
+ def exists?(name, prefix = nil, partial = false, keys = [])
+ @view_paths.exists?(*args_for_lookup(name, prefix, partial, keys))
end
alias :template_exists? :exists?
@@ -106,9 +107,9 @@ module ActionView
protected
- def args_for_lookup(name, prefix, partial) #:nodoc:
+ def args_for_lookup(name, prefix, partial, keys) #:nodoc:
name, prefix = normalize_name(name, prefix)
- [name, prefix, partial || false, @details, details_key]
+ [name, prefix, partial || false, @details, keys, details_key]
end
# Support legacy foo.erb names even though we now ignore .erb
@@ -130,10 +131,20 @@ module ActionView
end
module Details
+ attr_accessor :cache
+
# Calculate the details key. Remove the handlers from calculation to improve performance
# since the user cannot modify it explicitly.
def details_key #:nodoc:
- @details_key ||= DetailsKey.get(@details)
+ @details_key ||= DetailsKey.get(@details) if @cache
+ end
+
+ # Temporary skip passing the details_key forward.
+ def disable_cache
+ old_value, @cache = @cache, false
+ yield
+ ensure
+ @cache = old_value
end
# Freeze the current formats in the lookup context. By freezing them, you are guaranteeing
diff --git a/actionpack/lib/action_view/render/partials.rb b/actionpack/lib/action_view/partials.rb
index cc9b444837..844c3e9572 100644
--- a/actionpack/lib/action_view/render/partials.rb
+++ b/actionpack/lib/action_view/partials.rb
@@ -210,165 +210,12 @@ module ActionView
# <%- end -%>
# <% end %>
module Partials
- extend ActiveSupport::Concern
-
- class PartialRenderer
- PARTIAL_NAMES = Hash.new {|h,k| h[k] = {} }
-
- def initialize(view_context, options, block)
- @view = view_context
- @partial_names = PARTIAL_NAMES[@view.controller.class.name]
-
- setup(options, block)
- end
-
- def setup(options, block)
- partial = options[:partial]
-
- @options = options
- @locals = options[:locals] || {}
- @block = block
-
- if String === partial
- @object = options[:object]
- @path = partial
- @collection = collection
- else
- @object = partial
-
- if @collection = collection
- paths = @collection_paths = @collection.map { |o| partial_path(o) }
- @path = paths.uniq.size == 1 ? paths.first : nil
- else
- @path = partial_path
- end
- end
- end
-
- def render
- identifier = ((@template = find_template) ? @template.identifier : @path)
-
- if @collection
- ActiveSupport::Notifications.instrument("render_collection.action_view",
- :identifier => identifier || "collection", :count => @collection.size) do
- render_collection
- end
- else
- content = ActiveSupport::Notifications.instrument("render_partial.action_view",
- :identifier => identifier) do
- render_partial
- end
-
- if !@block && (layout = @options[:layout])
- content = @view._render_layout(find_template(layout), @locals){ content }
- end
-
- content
- end
- end
-
- def render_collection
- return nil if @collection.blank?
-
- if @options.key?(:spacer_template)
- spacer = find_template(@options[:spacer_template]).render(@view, @locals)
- end
-
- result = @template ? collection_with_template : collection_without_template
- result.join(spacer).html_safe
- end
-
- def collection_with_template(template = @template)
- segments, locals, template = [], @locals, @template
-
- if @options[:as]
- as = @options[:as]
- counter = "#{as}_counter".to_sym
- else
- as = template.variable_name
- counter = template.counter_name
- end
-
- locals[counter] = -1
-
- @collection.each do |object|
- locals[counter] += 1
- locals[as] = object
- segments << template.render(@view, locals)
- end
-
- segments
- end
-
- def collection_without_template(collection_paths = @collection_paths)
- segments, locals = [], @locals
- index, template = -1, nil
-
- if @options[:as]
- as = @options[:as]
- counter = "#{as}_counter"
- end
-
- @collection.each_with_index do |object, i|
- template = find_template(collection_paths[i])
- locals[as || template.variable_name] = object
- locals[counter || template.counter_name] = (index += 1)
-
- segments << template.render(@view, locals)
- end
-
- @template = template
- segments
- end
-
- def render_partial(object = @object)
- locals, view, template = @locals, @view, @template
-
- object ||= locals[template.variable_name]
- locals[@options[:as] || template.variable_name] = object
-
- template.render(view, locals) do |*name|
- view._layout_for(*name, &@block)
- end
- end
-
- private
-
- def collection
- if @object.respond_to?(:to_ary)
- @object
- elsif @options.key?(:collection)
- @options[:collection] || []
- end
- end
-
- def find_template(path=@path)
- return path unless path.is_a?(String)
- prefix = @view.controller_path unless path.include?(?/)
- @view.find_template(path, prefix, true)
- end
-
- def partial_path(object = @object)
- @partial_names[object.class.name] ||= begin
- object = object.to_model if object.respond_to?(:to_model)
-
- object.class.model_name.partial_path.dup.tap do |partial|
- path = @view.controller_path
- partial.insert(0, "#{File.dirname(path)}/") if partial.include?(?/) && path.include?(?/)
- end
- end
- end
- end
-
def _render_partial(options, &block) #:nodoc:
- if defined?(@renderer)
- @renderer.setup(options, block)
- else
- @renderer = PartialRenderer.new(self, options, block)
- end
-
- @renderer.render
+ _partial_renderer.setup(options, block).render
end
+ def _partial_renderer #:nodoc:
+ @_partial_renderer ||= PartialRenderer.new(self)
+ end
end
end
diff --git a/actionpack/lib/action_view/paths.rb b/actionpack/lib/action_view/path_set.rb
index 9857d688d2..dc26d75ff3 100644
--- a/actionpack/lib/action_view/paths.rb
+++ b/actionpack/lib/action_view/path_set.rb
@@ -10,8 +10,8 @@ module ActionView #:nodoc:
METHOD
end
- def find(path, prefix = nil, partial = false, details = {}, key = nil)
- template = find_all(path, prefix, partial, details, key).first
+ def find(path, prefix = nil, partial = false, details = {}, keys = [], key = nil)
+ template = find_all(path, prefix, partial, details, keys, key).first
raise MissingTemplate.new(self, "#{prefix}/#{path}", details, partial) unless template
template
end
diff --git a/actionpack/lib/action_view/render/rendering.rb b/actionpack/lib/action_view/render/rendering.rb
deleted file mode 100644
index 5320245173..0000000000
--- a/actionpack/lib/action_view/render/rendering.rb
+++ /dev/null
@@ -1,67 +0,0 @@
-require 'active_support/core_ext/object/try'
-
-module ActionView
- # = Action View Rendering
- module Rendering
- # Returns the result of a render that's dictated by the options hash. The primary options are:
- #
- # * <tt>:partial</tt> - See ActionView::Partials.
- # * <tt>:update</tt> - Calls update_page with the block given.
- # * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
- # * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
- # * <tt>:text</tt> - Renders the text passed in out.
- #
- # If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
- # as the locals hash.
- def render(options = {}, locals = {}, &block)
- case options
- when Hash
- if block_given?
- _render_partial(options.merge(:partial => options[:layout]), &block)
- elsif options.key?(:partial)
- _render_partial(options)
- else
- template = _determine_template(options)
- lookup_context.freeze_formats(template.formats, true)
- _render_template(template, options[:layout], options)
- end
- when :update
- update_page(&block)
- else
- _render_partial(:partial => options, :locals => locals)
- end
- end
-
- # Determine the template to be rendered using the given options.
- def _determine_template(options) #:nodoc:
- if options.key?(:inline)
- handler = Template.handler_class_for_extension(options[:type] || "erb")
- Template.new(options[:inline], "inline template", handler, {})
- elsif options.key?(:text)
- Template::Text.new(options[:text], formats.try(:first))
- elsif options.key?(:file)
- with_fallbacks { find_template(options[:file], options[:prefix]) }
- elsif options.key?(:template)
- options[:template].respond_to?(:render) ?
- options[:template] : find_template(options[:template], options[:prefix])
- end
- end
-
- # Renders the given template. An string representing the layout can be
- # supplied as well.
- def _render_template(template, layout = nil, options = {}) #:nodoc:
- locals = options[:locals] || {}
- layout = find_layout(layout) if layout
-
- ActiveSupport::Notifications.instrument("render_template.action_view",
- :identifier => template.identifier, :layout => layout.try(:virtual_path)) do
-
- content = template.render(self, locals) { |*name| _layout_for(*name) }
- @_content_for[:layout] = content if layout
-
- content = _render_layout(layout, locals) if layout
- content
- end
- end
- end
-end
diff --git a/actionpack/lib/action_view/renderer/abstract_renderer.rb b/actionpack/lib/action_view/renderer/abstract_renderer.rb
new file mode 100644
index 0000000000..77cfa51dff
--- /dev/null
+++ b/actionpack/lib/action_view/renderer/abstract_renderer.rb
@@ -0,0 +1,36 @@
+module ActionView
+ class AbstractRenderer #:nodoc:
+ attr_reader :vew, :lookup_context
+
+ delegate :find_template, :template_exists?, :with_fallbacks, :update_details,
+ :with_layout_format, :formats, :to => :lookup_context
+
+ def initialize(view)
+ @view = view
+ @lookup_context = view.lookup_context
+ end
+
+ def render
+ raise NotImplementedError
+ end
+
+ # Checks if the given path contains a format and if so, change
+ # the lookup context to take this new format into account.
+ def wrap_formats(value)
+ return yield unless value.is_a?(String)
+ @@formats_regexp ||= /\.(#{Mime::SET.symbols.join('|')})$/
+
+ if value.sub!(@@formats_regexp, "")
+ update_details(:formats => [$1.to_sym]){ yield }
+ else
+ yield
+ end
+ end
+
+ protected
+
+ def instrument(name, options={})
+ ActiveSupport::Notifications.instrument("render_#{name}.action_view", options){ yield }
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb
new file mode 100644
index 0000000000..c580397cad
--- /dev/null
+++ b/actionpack/lib/action_view/renderer/partial_renderer.rb
@@ -0,0 +1,166 @@
+require 'action_view/renderer/abstract_renderer'
+
+module ActionView
+ class PartialRenderer < AbstractRenderer #:nodoc:
+ PARTIAL_NAMES = Hash.new {|h,k| h[k] = {} }
+
+ def initialize(view)
+ super
+ @partial_names = PARTIAL_NAMES[@view.controller.class.name]
+ end
+
+ def setup(options, block)
+ partial = options[:partial]
+
+ @options = options
+ @locals = options[:locals] || {}
+ @block = block
+
+ if String === partial
+ @object = options[:object]
+ @path = partial
+ @collection = collection
+ else
+ @object = partial
+
+ if @collection = collection_from_object || collection
+ paths = @collection_data = @collection.map { |o| partial_path(o) }
+ @path = paths.uniq.size == 1 ? paths.first : nil
+ else
+ @path = partial_path
+ end
+ end
+
+ if @path
+ @variable, @variable_counter = retrieve_variable(@path)
+ else
+ paths.map! { |path| retrieve_variable(path).unshift(path) }
+ end
+
+ self
+ end
+
+ def render
+ wrap_formats(@path) do
+ identifier = ((@template = find_partial) ? @template.identifier : @path)
+
+ if @collection
+ instrument(:collection, :identifier => identifier || "collection", :count => @collection.size) do
+ render_collection
+ end
+ else
+ instrument(:partial, :identifier => identifier) do
+ render_partial
+ end
+ end
+ end
+ end
+
+ def render_collection
+ return nil if @collection.blank?
+
+ if @options.key?(:spacer_template)
+ spacer = find_template(@options[:spacer_template]).render(@view, @locals)
+ end
+
+ result = @template ? collection_with_template : collection_without_template
+ result.join(spacer).html_safe
+ end
+
+ def render_partial
+ locals, view, block = @locals, @view, @block
+ object, as = @object, @variable
+
+ if !block && (layout = @options[:layout])
+ layout = find_template(layout)
+ end
+
+ object ||= locals[as]
+ locals[as] = object
+
+ content = @template.render(view, locals) do |*name|
+ view._layout_for(*name, &block)
+ end
+
+ content = layout.render(view, locals){ content } if layout
+ content
+ end
+
+ private
+
+ def collection
+ if @options.key?(:collection)
+ @options[:collection] || []
+ end
+ end
+
+ def collection_from_object
+ if @object.respond_to?(:to_ary)
+ @object
+ end
+ end
+
+ def find_partial
+ if path = @path
+ locals = @locals.keys
+ locals << @variable
+ locals << @variable_counter if @collection
+ find_template(path, locals)
+ end
+ end
+
+ def find_template(path=@path, locals=@locals.keys)
+ prefix = @view.controller_prefix unless path.include?(?/)
+ @lookup_context.find_template(path, prefix, true, locals)
+ end
+
+ def collection_with_template
+ segments, locals, template = [], @locals, @template
+ as, counter = @variable, @variable_counter
+
+ locals[counter] = -1
+
+ @collection.each do |object|
+ locals[counter] += 1
+ locals[as] = object
+ segments << template.render(@view, locals)
+ end
+
+ segments
+ end
+
+ def collection_without_template
+ segments, locals, collection_data = [], @locals, @collection_data
+ index, template, cache = -1, nil, {}
+ keys = @locals.keys
+
+ @collection.each_with_index do |object, i|
+ path, *data = collection_data[i]
+ template = (cache[path] ||= find_template(path, keys + data))
+ locals[data[0]] = object
+ locals[data[1]] = (index += 1)
+ segments << template.render(@view, locals)
+ end
+
+ @template = template
+ segments
+ end
+
+ def partial_path(object = @object)
+ @partial_names[object.class.name] ||= begin
+ object = object.to_model if object.respond_to?(:to_model)
+
+ object.class.model_name.partial_path.dup.tap do |partial|
+ path = @view.controller_prefix
+ partial.insert(0, "#{File.dirname(path)}/") if partial.include?(?/) && path.include?(?/)
+ end
+ end
+ end
+
+ def retrieve_variable(path)
+ variable = @options[:as] || path[%r'_?(\w+)(\.\w+)*$', 1].to_sym
+ variable_counter = :"#{variable}_counter" if @collection
+ [variable, variable_counter]
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb
new file mode 100644
index 0000000000..36beb5c8d0
--- /dev/null
+++ b/actionpack/lib/action_view/renderer/template_renderer.rb
@@ -0,0 +1,98 @@
+require 'set'
+require 'active_support/core_ext/object/try'
+require 'active_support/core_ext/array/wrap'
+require 'action_view/renderer/abstract_renderer'
+
+module ActionView
+ class TemplateRenderer < AbstractRenderer #:nodoc:
+ attr_reader :rendered
+
+ def initialize(view)
+ super
+ @rendered = Set.new
+ end
+
+ def render(options)
+ wrap_formats(options[:template] || options[:file]) do
+ template = determine_template(options)
+ render_template(template, options[:layout], options[:locals])
+ end
+ end
+
+ def render_once(options)
+ paths, locals = options[:once], options[:locals] || {}
+ layout, keys = options[:layout], locals.keys
+ prefix = options.fetch(:prefix, @view.controller_prefix)
+
+ raise "render :once expects a String or an Array to be given" unless paths
+
+ render_with_layout(layout, locals) do
+ contents = []
+ Array.wrap(paths).each do |path|
+ template = find_template(path, prefix, false, keys)
+ contents << render_template(template, nil, locals) if @rendered.add?(template)
+ end
+ contents.join("\n")
+ end
+ end
+
+ # Determine the template to be rendered using the given options.
+ def determine_template(options) #:nodoc:
+ keys = options[:locals].try(:keys) || []
+
+ if options.key?(:text)
+ Template::Text.new(options[:text], formats.try(:first))
+ elsif options.key?(:file)
+ with_fallbacks { find_template(options[:file], options[:prefix], false, keys) }
+ elsif options.key?(:inline)
+ handler = Template.handler_class_for_extension(options[:type] || "erb")
+ Template.new(options[:inline], "inline template", handler, :locals => keys)
+ elsif options.key?(:template)
+ options[:template].respond_to?(:render) ?
+ options[:template] : find_template(options[:template], options[:prefix], false, keys)
+ end
+ end
+
+ # Renders the given template. An string representing the layout can be
+ # supplied as well.
+ def render_template(template, layout_name = nil, locals = {}) #:nodoc:
+ lookup_context.freeze_formats(template.formats, true)
+ view, locals = @view, locals || {}
+
+ render_with_layout(layout_name, locals) do |layout|
+ instrument(:template, :identifier => template.identifier, :layout => layout.try(:virtual_path)) do
+ template.render(view, locals) { |*name| view._layout_for(*name) }
+ end
+ end
+ end
+
+ def render_with_layout(path, locals) #:nodoc:
+ layout = path && find_layout(path, locals.keys)
+ content = yield(layout)
+
+ if layout
+ view = @view
+ view.store_content_for(:layout, content)
+ layout.render(view, locals){ |*name| view._layout_for(*name) }
+ else
+ content
+ end
+ end
+
+ # This is the method which actually finds the layout using details in the lookup
+ # context object. If no layout is found, it checks if at least a layout with
+ # the given name exists across all details before raising the error.
+ def find_layout(layout, keys)
+ begin
+ with_layout_format do
+ layout =~ /^\// ?
+ with_fallbacks { find_template(layout, nil, false, keys) } : find_template(layout, nil, false, keys)
+ end
+ rescue ActionView::MissingTemplate => e
+ update_details(:formats => nil) do
+ raise unless template_exists?(layout)
+ end
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/render/layouts.rb b/actionpack/lib/action_view/rendering.rb
index 8882acca31..baa5d2c3fd 100644
--- a/actionpack/lib/action_view/render/layouts.rb
+++ b/actionpack/lib/action_view/rendering.rb
@@ -1,6 +1,38 @@
+require 'active_support/core_ext/object/try'
+
module ActionView
- # = Action View Layouts
- module Layouts
+ # = Action View Rendering
+ module Rendering
+ # Returns the result of a render that's dictated by the options hash. The primary options are:
+ #
+ # * <tt>:partial</tt> - See ActionView::Partials.
+ # * <tt>:update</tt> - Calls update_page with the block given.
+ # * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
+ # * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
+ # * <tt>:text</tt> - Renders the text passed in out.
+ # * <tt>:once</tt> - Accepts a string or an array of strings and Rails will ensure they each of them are rendered just once.
+ #
+ # If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
+ # as the locals hash.
+ def render(options = {}, locals = {}, &block)
+ case options
+ when Hash
+ if block_given?
+ _render_partial(options.merge(:partial => options[:layout]), &block)
+ elsif options.key?(:partial)
+ _render_partial(options)
+ elsif options.key?(:once)
+ _render_once(options)
+ else
+ _render_template(options)
+ end
+ when :update
+ update_page(&block)
+ else
+ _render_partial(:partial => options, :locals => locals)
+ end
+ end
+
# Returns the contents that are yielded to a layout, given a name or a block.
#
# You can think of a layout as a method that is called with a block. If the user calls
@@ -47,7 +79,7 @@ module ActionView
# Hello David
# </html>
#
- def _layout_for(*args, &block) #:nodoc:
+ def _layout_for(*args, &block)
name = args.first
if name.is_a?(Symbol)
@@ -59,25 +91,16 @@ module ActionView
end
end
- # This is the method which actually finds the layout using details in the lookup
- # context object. If no layout is found, it checks if at least a layout with
- # the given name exists across all details before raising the error.
- def find_layout(layout)
- begin
- with_layout_format do
- layout =~ /^\// ?
- with_fallbacks { find_template(layout) } : find_template(layout)
- end
- rescue ActionView::MissingTemplate => e
- update_details(:formats => nil) do
- raise unless template_exists?(layout)
- end
- end
+ def _render_once(options) #:nodoc:
+ _template_renderer.render_once(options)
+ end
+
+ def _render_template(options) #:nodoc:
+ _template_renderer.render(options)
end
- # Contains the logic that actually renders the layout.
- def _render_layout(layout, locals, &block) #:nodoc:
- layout.render(self, locals){ |*name| _layout_for(*name, &block) }
+ def _template_renderer #:nodoc:
+ @_template_renderer ||= TemplateRenderer.new(self)
end
end
end
diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb
index 164d177dcc..7dd8acf37b 100644
--- a/actionpack/lib/action_view/template.rb
+++ b/actionpack/lib/action_view/template.rb
@@ -98,8 +98,9 @@ module ActionView
extend Template::Handlers
- attr_reader :source, :identifier, :handler, :virtual_path, :formats,
- :original_encoding
+ attr_accessor :locals, :formats, :virtual_path
+
+ attr_reader :source, :identifier, :handler, :original_encoding, :updated_at
# This finalizer is needed (and exactly with a proc inside another proc)
# otherwise templates leak in development.
@@ -112,49 +113,75 @@ module ActionView
end
def initialize(source, identifier, handler, details)
- @source = source
- @identifier = identifier
- @handler = handler
- @original_encoding = nil
- @method_names = {}
-
- format = details[:format] || :html
- @formats = Array.wrap(format).map(&:to_sym)
- @virtual_path = details[:virtual_path].try(:sub, ".#{format}", "")
+ format = details[:format] || (handler.default_format if handler.respond_to?(:default_format))
+
+ @source = source
+ @identifier = identifier
+ @handler = handler
+ @compiled = false
+ @original_encoding = nil
+ @locals = details[:locals] || []
+ @virtual_path = details[:virtual_path]
+ @updated_at = details[:updated_at] || Time.now
+ @formats = Array.wrap(format).map(&:to_sym)
end
+ # Render a template. If the template was not compiled yet, it is done
+ # exactly before rendering.
+ #
+ # This method is instrumented as "!render_template.action_view". Notice that
+ # we use a bang in this instrumentation because you don't want to
+ # consume this in production. This is only slow if it's being listened to.
def render(view, locals, &block)
- # Notice that we use a bang in this instrumentation because you don't want to
- # consume this in production. This is only slow if it's being listened to.
+ old_template, view._template = view._template, self
ActiveSupport::Notifications.instrument("!render_template.action_view", :virtual_path => @virtual_path) do
- if view.is_a?(ActionView::CompiledTemplates)
- mod = ActionView::CompiledTemplates
- else
- mod = view.singleton_class
- end
-
- method_name = compile(locals, view, mod)
+ compile!(view)
view.send(method_name, locals, &block)
end
rescue Exception => e
- if e.is_a?(Template::Error)
- e.sub_template_of(self)
- raise e
- else
- raise Template::Error.new(self, view.respond_to?(:assigns) ? view.assigns : {}, e)
- end
+ handle_render_error(view, e)
+ ensure
+ view._template = old_template
end
def mime_type
@mime_type ||= Mime::Type.lookup_by_extension(@formats.first.to_s) if @formats.first
end
- def variable_name
- @variable_name ||= @virtual_path[%r'_?(\w+)(\.\w+)*$', 1].to_sym
+ # Receives a view object and return a template similar to self by using @virtual_path.
+ #
+ # This method is useful if you have a template object but it does not contain its source
+ # anymore since it was already compiled. In such cases, all you need to do is to call
+ # refresh passing in the view object.
+ #
+ # Notice this method raises an error if the template to be refreshed does not have a
+ # virtual path set (true just for inline templates).
+ def refresh(view)
+ raise "A template needs to have a virtual path in order to be refreshed" unless @virtual_path
+ lookup = view.lookup_context
+ pieces = @virtual_path.split("/")
+ name = pieces.pop
+ partial = !!name.sub!(/^_/, "")
+ lookup.disable_cache do
+ lookup.find_template(name, pieces.join, partial, @locals)
+ end
end
- def counter_name
- @counter_name ||= "#{variable_name}_counter".to_sym
+ # Expires this template by setting his updated_at date to Jan 1st, 1970.
+ def expire!
+ @updated_at = Time.utc(1970)
+ end
+
+ # Receives a view context and renders a template exactly like self by using
+ # the @virtual_path. It raises an error if no @virtual_path was given.
+ def rerender(view)
+ raise "A template needs to have a virtual path in order to be rerendered" unless @virtual_path
+ name = @virtual_path.dup
+ if name.sub!(/(^|\/)_([^\/]*)$/, '\1\2')
+ view.render :partial => name
+ else
+ view.render :template => @virtual_path
+ end
end
def inspect
@@ -166,7 +193,27 @@ module ActionView
end
end
- private
+ protected
+
+ # Compile a template. This method ensures a template is compiled
+ # just once and removes the source after it is compiled.
+ def compile!(view) #:nodoc:
+ return if @compiled
+
+ if view.is_a?(ActionView::CompiledTemplates)
+ mod = ActionView::CompiledTemplates
+ else
+ mod = view.singleton_class
+ end
+
+ compile(view, mod)
+
+ # Just discard the source if we have a virtual path. This
+ # means we can get the template back.
+ @source = nil if @virtual_path
+ @compiled = true
+ end
+
# Among other things, this method is responsible for properly setting
# the encoding of the source. Until this point, we assume that the
# source is BINARY data. If no additional information is supplied,
@@ -187,11 +234,8 @@ module ActionView
# encode the source into Encoding.default_internal. In general,
# this means that templates will be UTF-8 inside of Rails,
# regardless of the original source encoding.
- def compile(locals, view, mod)
- method_name = build_method_name(locals)
- return method_name if view.respond_to?(method_name)
-
- locals_code = locals.keys.map! { |key| "#{key} = local_assigns[:#{key}];" }.join
+ def compile(view, mod) #:nodoc:
+ method_name = self.method_name
if source.encoding_aware?
# Look for # encoding: *. If we find one, we'll encode the
@@ -231,9 +275,9 @@ module ActionView
# encoding of the code
source = <<-end_src
def #{method_name}(local_assigns)
- _old_virtual_path, @_virtual_path = @_virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code}
+ _old_output_buffer = @output_buffer;#{locals_code};#{code}
ensure
- @_virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer
+ @output_buffer = _old_output_buffer
end
end_src
@@ -256,8 +300,6 @@ module ActionView
begin
mod.module_eval(source, identifier, 0)
ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
-
- method_name
rescue Exception => e # errors from template code
if logger = (view && view.logger)
logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
@@ -269,12 +311,27 @@ module ActionView
end
end
- def build_method_name(locals)
- @method_names[locals.keys.hash] ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}_#{locals.keys.hash}".gsub('-', "_")
+ def handle_render_error(view, e) #:nodoc:
+ if e.is_a?(Template::Error)
+ e.sub_template_of(self)
+ raise e
+ else
+ assigns = view.respond_to?(:assigns) ? view.assigns : {}
+ template = @virtual_path ? refresh(view) : self
+ raise Template::Error.new(template, assigns, e)
+ end
+ end
+
+ def locals_code #:nodoc:
+ @locals.map { |key| "#{key} = local_assigns[:#{key}];" }.join
+ end
+
+ def method_name #:nodoc:
+ @method_name ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}".gsub('-', "_")
end
- def identifier_method_name
- @identifier_method_name ||= inspect.gsub(/[^a-z_]/, '_')
+ def identifier_method_name #:nodoc:
+ inspect.gsub(/[^a-z_]/, '_')
end
end
end
diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb
index 423e1e0bf5..ff256738a9 100644
--- a/actionpack/lib/action_view/template/error.rb
+++ b/actionpack/lib/action_view/template/error.rb
@@ -43,8 +43,9 @@ module ActionView
end
class Template
- # The Template::Error exception is raised when the compilation of the template fails. This exception then gathers a
- # bunch of intimate details and uses it to report a very precise exception message.
+ # The Template::Error exception is raised when the compilation or rendering of the template
+ # fails. This exception then gathers a bunch of intimate details and uses it to report a
+ # precise exception message.
class Error < ActionViewError #:nodoc:
SOURCE_CODE_RADIUS = 3
diff --git a/actionpack/lib/action_view/template/handler.rb b/actionpack/lib/action_view/template/handler.rb
index c6a1bc6235..636f3ebbad 100644
--- a/actionpack/lib/action_view/template/handler.rb
+++ b/actionpack/lib/action_view/template/handler.rb
@@ -1,4 +1,4 @@
-require "action_dispatch/http/mime_type"
+require 'action_dispatch/http/mime_type'
require 'active_support/core_ext/class/attribute'
# Legacy TemplateHandler stub
@@ -7,6 +7,8 @@ module ActionView
module Handlers #:nodoc:
module Compilable
def self.included(base)
+ ActiveSupport::Deprecation.warn "Including Compilable in your template handler is deprecated. " <<
+ "Since Rails 3, all the API your template handler needs to implement is to respond to #call."
base.extend(ClassMethods)
end
@@ -26,6 +28,12 @@ module ActionView
class_attribute :default_format
self.default_format = Mime::HTML
+ def self.inherited(base)
+ ActiveSupport::Deprecation.warn "Inheriting from ActionView::Template::Handler is deprecated. " <<
+ "Since Rails 3, all the API your template handler needs to implement is to respond to #call."
+ super
+ end
+
def self.call(template)
raise "Need to implement #{self.class.name}#call(template)"
end
diff --git a/actionpack/lib/action_view/template/handlers.rb b/actionpack/lib/action_view/template/handlers.rb
index ed397699b0..60347e2a95 100644
--- a/actionpack/lib/action_view/template/handlers.rb
+++ b/actionpack/lib/action_view/template/handlers.rb
@@ -7,13 +7,9 @@ module ActionView #:nodoc:
autoload :Builder, 'action_view/template/handlers/builder'
def self.extended(base)
- base.register_default_template_handler :erb, ERB
- base.register_template_handler :rjs, RJS
- base.register_template_handler :builder, Builder
-
- # TODO: Depreciate old template extensions
- base.register_template_handler :rhtml, ERB
- base.register_template_handler :rxml, Builder
+ base.register_default_template_handler :erb, ERB.new
+ base.register_template_handler :rjs, RJS.new
+ base.register_template_handler :builder, Builder.new
end
@@template_handlers = {}
diff --git a/actionpack/lib/action_view/template/handlers/builder.rb b/actionpack/lib/action_view/template/handlers/builder.rb
index a93cfca8aa..2c52cfd90e 100644
--- a/actionpack/lib/action_view/template/handlers/builder.rb
+++ b/actionpack/lib/action_view/template/handlers/builder.rb
@@ -1,11 +1,11 @@
module ActionView
module Template::Handlers
- class Builder < Template::Handler
- include Compilable
-
+ class Builder
+ # Default format used by Builder.
+ class_attribute :default_format
self.default_format = Mime::XML
- def compile(template)
+ def call(template)
require 'builder'
"xml = ::Builder::XmlMarkup.new(:indent => 2);" +
"self.output_buffer = xml.target!;" +
diff --git a/actionpack/lib/action_view/template/handlers/erb.rb b/actionpack/lib/action_view/template/handlers/erb.rb
index 24e1e44c1d..b827610456 100644
--- a/actionpack/lib/action_view/template/handlers/erb.rb
+++ b/actionpack/lib/action_view/template/handlers/erb.rb
@@ -1,6 +1,7 @@
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/string/output_safety'
-require "action_view/template"
+require 'action_view/template'
+require 'action_view/template/handler'
require 'erubis'
module ActionView
@@ -47,28 +48,31 @@ module ActionView
end
end
- class ERB < Handler
- include Compilable
-
- ##
- # :singleton-method:
+ class ERB
# Specify trim mode for the ERB compiler. Defaults to '-'.
# See ERb documentation for suitable values.
- cattr_accessor :erb_trim_mode
+ class_attribute :erb_trim_mode
self.erb_trim_mode = '-'
+ # Default format used by ERB.
+ class_attribute :default_format
self.default_format = Mime::HTML
- cattr_accessor :erb_implementation
+ # Default implemenation used.
+ class_attribute :erb_implementation
self.erb_implementation = Erubis
ENCODING_TAG = Regexp.new("\\A(<%#{ENCODING_FLAG}-?%>)[ \\t]*")
- def self.handles_encoding?
+ def self.call(template)
+ new.call(template)
+ end
+
+ def handles_encoding?
true
end
- def compile(template)
+ def call(template)
if template.source.encoding_aware?
# First, convert to BINARY, so in case the encoding is
# wrong, we can still find an encoding tag
@@ -94,6 +98,7 @@ module ActionView
end
private
+
def valid_encoding(string, encoding)
# If a magic encoding comment was found, tag the
# String with this encoding. This is for a case
diff --git a/actionpack/lib/action_view/template/handlers/rjs.rb b/actionpack/lib/action_view/template/handlers/rjs.rb
index 128be5077c..9d71059134 100644
--- a/actionpack/lib/action_view/template/handlers/rjs.rb
+++ b/actionpack/lib/action_view/template/handlers/rjs.rb
@@ -1,17 +1,13 @@
module ActionView
module Template::Handlers
- class RJS < Template::Handler
- include Compilable
-
+ class RJS
+ # Default format used by RJS.
+ class_attribute :default_format
self.default_format = Mime::JS
- def compile(template)
+ def call(template)
"update_page do |page|;#{template.source}\nend"
end
-
- def default_format
- Mime::JS
- end
end
end
end
diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb
index a261e08dbc..7707dbcf98 100644
--- a/actionpack/lib/action_view/template/resolver.rb
+++ b/actionpack/lib/action_view/template/resolver.rb
@@ -6,9 +6,8 @@ module ActionView
# = Action View Resolver
class Resolver
def initialize
- @path = nil
- @cached = Hash.new { |h1,k1| h1[k1] =
- Hash.new { |h2,k2| h2[k2] = Hash.new { |h3, k3| h3[k3] = {} } } }
+ @cached = Hash.new { |h1,k1| h1[k1] = Hash.new { |h2,k2|
+ h2[k2] = Hash.new { |h3,k3| h3[k3] = Hash.new { |h4,k4| h4[k4] = {} } } } }
end
def clear_cache
@@ -16,8 +15,8 @@ module ActionView
end
# Normalizes the arguments and passes it on to find_template.
- def find_all(name, prefix=nil, partial=false, details={}, key=nil)
- cached(key, prefix, name, partial) do
+ def find_all(name, prefix=nil, partial=false, details={}, locals=[], key=nil)
+ cached(key, [name, prefix, partial], details, locals) do
find_templates(name, prefix, partial, details)
end
end
@@ -35,34 +34,73 @@ module ActionView
raise NotImplementedError
end
- def cached(key, prefix, name, partial)
- return yield unless key && caching?
- @cached[key][prefix][name][partial] ||= yield
+ # Helpers that builds a path. Useful for building virtual paths.
+ def build_path(name, prefix, partial)
+ path = ""
+ path << "#{prefix}/" unless prefix.empty?
+ path << (partial ? "_#{name}" : name)
+ path
+ end
+
+ # Hnadles templates caching. If a key is given and caching is on
+ # always check the cache before hitting the resolver. Otherwise,
+ # it always hits the resolver but check if the resolver is fresher
+ # before returning it.
+ def cached(key, path_info, details, locals) #:nodoc:
+ name, prefix, partial = path_info
+ locals = sort_locals(locals)
+
+ if key && caching?
+ @cached[key][name][prefix][partial][locals] ||= decorate(yield, path_info, details, locals)
+ else
+ fresh = decorate(yield, path_info, details, locals)
+ return fresh unless key
+
+ scope = @cached[key][name][prefix][partial]
+ cache = scope[locals]
+ mtime = cache && cache.map(&:updated_at).max
+
+ if !mtime || fresh.empty? || fresh.any? { |t| t.updated_at > mtime }
+ scope[locals] = fresh
+ else
+ cache
+ end
+ end
+ end
+
+ # Ensures all the resolver information is set in the template.
+ def decorate(templates, path_info, details, locals) #:nodoc:
+ cached = nil
+ templates.each do |t|
+ t.locals = locals
+ t.formats = details[:formats] || [:html] if t.formats.empty?
+ t.virtual_path ||= (cached ||= build_path(*path_info))
+ end
+ end
+
+ if :symbol.respond_to?("<=>")
+ def sort_locals(locals) #:nodoc:
+ locals.sort.freeze
+ end
+ else
+ def sort_locals(locals) #:nodoc:
+ locals = locals.map{ |l| l.to_s }
+ locals.sort!
+ locals.freeze
+ end
end
end
class PathResolver < Resolver
EXTENSION_ORDER = [:locale, :formats, :handlers]
- def to_s
- @path.to_s
- end
- alias :to_path :to_s
-
- private
+ private
def find_templates(name, prefix, partial, details)
- path = build_path(name, prefix, partial, details)
+ path = build_path(name, prefix, partial)
query(path, EXTENSION_ORDER.map { |ext| details[ext] }, details[:formats])
end
- def build_path(name, prefix, partial, details)
- path = ""
- path << "#{prefix}/" unless prefix.empty?
- path << (partial ? "_#{name}" : name)
- path
- end
-
def query(path, exts, formats)
query = File.join(@path, path)
@@ -76,26 +114,28 @@ module ActionView
contents = File.open(p, "rb") {|io| io.read }
Template.new(contents, File.expand_path(p), handler,
- :virtual_path => path, :format => format)
+ :virtual_path => path, :format => format, :updated_at => mtime(p))
end
end
+ # Returns the file mtime from the filesystem.
+ def mtime(p)
+ File.stat(p).mtime
+ end
+
# Extract handler and formats from path. If a format cannot be a found neither
# from the path, or the handler, we should return the array of formats given
# to the resolver.
def extract_handler_and_format(path, default_formats)
pieces = File.basename(path).split(".")
pieces.shift
-
- handler = Template.handler_class_for_extension(pieces.pop)
- format = pieces.last && Mime[pieces.last] && pieces.pop.to_sym
- format ||= handler.default_format if handler.respond_to?(:default_format)
- format ||= default_formats
-
+ handler = Template.handler_class_for_extension(pieces.pop)
+ format = pieces.last && Mime[pieces.last]
[handler, format]
end
end
+ # A resolver that loads files from the filesystem.
class FileSystemResolver < PathResolver
def initialize(path)
raise ArgumentError, "path already is a Resolver class" if path.is_a?(Resolver)
@@ -103,9 +143,26 @@ module ActionView
@path = File.expand_path(path)
end
+ def to_s
+ @path.to_s
+ end
+ alias :to_path :to_s
+
def eql?(resolver)
self.class.equal?(resolver.class) && to_path == resolver.to_path
end
alias :== :eql?
end
+
+ # The same as FileSystemResolver but does not allow templates to store
+ # a virtual path since it is invalid for such resolvers.
+ class FallbackFileSystemResolver < FileSystemResolver
+ def self.instances
+ [new(""), new("/")]
+ end
+
+ def decorate(*)
+ super.each { |t| t.virtual_path = nil }
+ end
+ end
end
diff --git a/actionpack/lib/action_view/template/text.rb b/actionpack/lib/action_view/template/text.rb
index 51be831dfb..4261c3b5e2 100644
--- a/actionpack/lib/action_view/template/text.rb
+++ b/actionpack/lib/action_view/template/text.rb
@@ -25,10 +25,6 @@ module ActionView #:nodoc:
def formats
[@mime_type.to_sym]
end
-
- def partial?
- false
- end
end
end
end
diff --git a/actionpack/lib/action_view/testing/resolvers.rb b/actionpack/lib/action_view/testing/resolvers.rb
index b2b62528a9..55583096e0 100644
--- a/actionpack/lib/action_view/testing/resolvers.rb
+++ b/actionpack/lib/action_view/testing/resolvers.rb
@@ -13,26 +13,29 @@ module ActionView #:nodoc:
@hash = hash
end
- private
+ private
def query(path, exts, formats)
- query = Regexp.escape(path)
+ query = ""
exts.each do |ext|
query << '(' << ext.map {|e| e && Regexp.escape(".#{e}") }.join('|') << '|)'
end
+ query = /^(#{Regexp.escape(path)})#{query}$/
templates = []
- @hash.select { |k,v| k =~ /^#{query}$/ }.each do |_path, source|
+ @hash.each do |_path, array|
+ source, updated_at = array
+ next unless _path =~ query
handler, format = extract_handler_and_format(_path, formats)
templates << Template.new(source, _path, handler,
- :virtual_path => _path, :format => format)
+ :virtual_path => $1, :format => format, :updated_at => updated_at)
end
templates.sort_by {|t| -t.identifier.match(/^#{query}$/).captures.reject(&:blank?).size }
end
end
- class NullResolver < ActionView::PathResolver
+ class NullResolver < PathResolver
def query(path, exts, formats)
handler, format = extract_handler_and_format(path, formats)
[ActionView::Template.new("Template generated by Null Resolver", path, handler, :virtual_path => path, :format => format)]
diff --git a/actionpack/test/controller/content_type_test.rb b/actionpack/test/controller/content_type_test.rb
index 967107853b..9500c25a32 100644
--- a/actionpack/test/controller/content_type_test.rb
+++ b/actionpack/test/controller/content_type_test.rb
@@ -29,18 +29,18 @@ class OldContentTypeController < ActionController::Base
render :text => "hello world!"
end
- def render_default_for_rhtml
+ def render_default_for_erb
end
- def render_default_for_rxml
+ def render_default_for_builder
end
def render_default_for_rjs
end
- def render_change_for_rxml
+ def render_change_for_builder
response.content_type = Mime::HTML
- render :action => "render_default_for_rxml"
+ render :action => "render_default_for_builder"
end
def render_default_content_types_for_respond_to
@@ -108,23 +108,23 @@ class ContentTypeTest < ActionController::TestCase
assert_equal "utf-8", @response.charset, @response.headers.inspect
end
- def test_nil_default_for_rhtml
+ def test_nil_default_for_erb
OldContentTypeController.default_charset = nil
- get :render_default_for_rhtml
+ get :render_default_for_erb
assert_equal Mime::HTML, @response.content_type
assert_nil @response.charset, @response.headers.inspect
ensure
OldContentTypeController.default_charset = "utf-8"
end
- def test_default_for_rhtml
- get :render_default_for_rhtml
+ def test_default_for_erb
+ get :render_default_for_erb
assert_equal Mime::HTML, @response.content_type
assert_equal "utf-8", @response.charset
end
- def test_default_for_rxml
- get :render_default_for_rxml
+ def test_default_for_builder
+ get :render_default_for_builder
assert_equal Mime::XML, @response.content_type
assert_equal "utf-8", @response.charset
end
@@ -135,8 +135,8 @@ class ContentTypeTest < ActionController::TestCase
assert_equal "utf-8", @response.charset
end
- def test_change_for_rxml
- get :render_change_for_rxml
+ def test_change_for_builder
+ get :render_change_for_builder
assert_equal Mime::HTML, @response.content_type
assert_equal "utf-8", @response.charset
end
diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb
index 32a0f40614..cafe2b9320 100644
--- a/actionpack/test/controller/layout_test.rb
+++ b/actionpack/test/controller/layout_test.rb
@@ -46,13 +46,13 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase
def test_application_layout_is_default_when_no_controller_match
@controller = ProductController.new
get :hello
- assert_equal 'layout_test.rhtml hello.rhtml', @response.body
+ assert_equal 'layout_test.erb hello.erb', @response.body
end
def test_controller_name_layout_name_match
@controller = ItemController.new
get :hello
- assert_equal 'item.rhtml hello.rhtml', @response.body
+ assert_equal 'item.erb hello.erb', @response.body
end
def test_third_party_template_library_auto_discovers_layout
@@ -65,13 +65,13 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase
def test_namespaced_controllers_auto_detect_layouts1
@controller = ControllerNameSpace::NestedController.new
get :hello
- assert_equal 'controller_name_space/nested.rhtml hello.rhtml', @response.body
+ assert_equal 'controller_name_space/nested.erb hello.erb', @response.body
end
def test_namespaced_controllers_auto_detect_layouts2
@controller = MultipleExtensions.new
get :hello
- assert_equal 'multiple_extensions.html.erb hello.rhtml', @response.body.strip
+ assert_equal 'multiple_extensions.html.erb hello.erb', @response.body.strip
end
end
@@ -79,7 +79,7 @@ class DefaultLayoutController < LayoutTest
end
class AbsolutePathLayoutController < LayoutTest
- layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.rhtml')
+ layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.erb')
end
class HasOwnLayoutController < LayoutTest
@@ -137,7 +137,7 @@ class LayoutSetInResponseTest < ActionController::TestCase
def test_layout_only_exception_when_excepted
@controller = OnlyLayoutController.new
get :goodbye
- assert !@response.body.include?("item.rhtml"), "#{@response.body.inspect} included 'item.rhtml'"
+ assert !@response.body.include?("item.erb"), "#{@response.body.inspect} included 'item.erb'"
end
def test_layout_except_exception_when_included
@@ -149,7 +149,7 @@ class LayoutSetInResponseTest < ActionController::TestCase
def test_layout_except_exception_when_excepted
@controller = ExceptLayoutController.new
get :goodbye
- assert !@response.body.include?("item.rhtml"), "#{@response.body.inspect} included 'item.rhtml'"
+ assert !@response.body.include?("item.erb"), "#{@response.body.inspect} included 'item.erb'"
end
def test_layout_set_when_using_render
@@ -173,7 +173,7 @@ class LayoutSetInResponseTest < ActionController::TestCase
def test_absolute_pathed_layout
@controller = AbsolutePathLayoutController.new
get :hello
- assert_equal "layout_test.rhtml hello.rhtml", @response.body.strip
+ assert_equal "layout_test.erb hello.erb", @response.body.strip
end
end
@@ -184,7 +184,7 @@ class RenderWithTemplateOptionController < LayoutTest
end
class SetsNonExistentLayoutFile < LayoutTest
- layout "nofile.rhtml"
+ layout "nofile.erb"
end
class LayoutExceptionRaised < ActionController::TestCase
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
index adccfa028f..a898ef76e5 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -709,6 +709,15 @@ class RespondWithControllerTest < ActionController::TestCase
assert_equal " ", @response.body
end
+ def test_using_resource_for_put_with_json_yields_ok_on_success
+ Customer.any_instance.stubs(:to_json).returns('{"name": "David"}')
+ @request.accept = "application/json"
+ put :using_resource
+ assert_equal "application/json", @response.content_type
+ assert_equal 200, @response.status
+ assert_equal "{}", @response.body
+ end
+
def test_using_resource_for_put_with_xml_yields_unprocessable_entity_on_failure
@request.accept = "application/xml"
errors = { :name => :invalid }
@@ -739,6 +748,16 @@ class RespondWithControllerTest < ActionController::TestCase
assert_equal " ", @response.body
end
+ def test_using_resource_for_delete_with_json_yields_ok_on_success
+ Customer.any_instance.stubs(:to_json).returns('{"name": "David"}')
+ Customer.any_instance.stubs(:destroyed?).returns(true)
+ @request.accept = "application/json"
+ delete :using_resource
+ assert_equal "application/json", @response.content_type
+ assert_equal 200, @response.status
+ assert_equal "{}", @response.body
+ end
+
def test_using_resource_for_delete_with_html_redirects_on_failure
with_test_route_set do
errors = { :name => :invalid }
diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb
index 8a06e8d2a0..44922cecff 100644
--- a/actionpack/test/controller/new_base/bare_metal_test.rb
+++ b/actionpack/test/controller/new_base/bare_metal_test.rb
@@ -24,4 +24,19 @@ module BareMetalTest
assert_equal "Hello world", string
end
end
+
+ class HeadController < ActionController::Metal
+ include ActionController::Head
+
+ def index
+ head :not_found
+ end
+ end
+
+ class HeadTest < ActiveSupport::TestCase
+ test "head works on its own" do
+ status, headers, body = HeadController.action(:index).call(Rack::MockRequest.env_for("/"))
+ assert_equal 404, status
+ end
+ end
end
diff --git a/actionpack/test/controller/new_base/render_once_test.rb b/actionpack/test/controller/new_base/render_once_test.rb
new file mode 100644
index 0000000000..3035ed4ff2
--- /dev/null
+++ b/actionpack/test/controller/new_base/render_once_test.rb
@@ -0,0 +1,86 @@
+require 'abstract_unit'
+
+module RenderTemplate
+ class RenderOnceController < ActionController::Base
+ layout false
+
+ RESOLVER = ActionView::FixtureResolver.new(
+ "test/a.html.erb" => "a",
+ "test/b.html.erb" => "<>",
+ "test/c.html.erb" => "c",
+ "test/one.html.erb" => "<%= render :once => 'result' %>",
+ "test/two.html.erb" => "<%= render :once => 'result' %>",
+ "test/three.html.erb" => "<%= render :once => 'result' %>",
+ "test/result.html.erb" => "YES!",
+ "other/result.html.erb" => "NO!",
+ "layouts/test.html.erb" => "l<%= yield %>l"
+ )
+
+ self.view_paths = [RESOLVER]
+
+ def _prefix
+ "test"
+ end
+
+ def multiple
+ render :once => %w(a b c)
+ end
+
+ def once
+ render :once => %w(one two three)
+ end
+
+ def duplicate
+ render :once => %w(a a a)
+ end
+
+ def with_layout
+ render :once => %w(a b c), :layout => "test"
+ end
+
+ def with_prefix
+ render :once => "result", :prefix => "other"
+ end
+
+ def with_nil_prefix
+ render :once => "test/result", :prefix => nil
+ end
+ end
+
+ module Tests
+ def test_mutliple_arguments_get_all_rendered
+ get :multiple
+ assert_response "a\n<>\nc"
+ end
+
+ def test_referenced_templates_get_rendered_once
+ get :once
+ assert_response "YES!\n\n"
+ end
+
+ def test_duplicated_templates_get_rendered_once
+ get :duplicate
+ assert_response "a"
+ end
+
+ def test_layout_wraps_all_rendered_templates
+ get :with_layout
+ assert_response "la\n<>\ncl"
+ end
+
+ def test_with_prefix_option
+ get :with_prefix
+ assert_response "NO!"
+ end
+
+ def test_with_nil_prefix_option
+ get :with_nil_prefix
+ assert_response "YES!"
+ end
+ end
+
+ class TestRenderOnce < Rack::TestCase
+ testing RenderTemplate::RenderOnceController
+ include Tests
+ end
+end
diff --git a/actionpack/test/controller/new_base/render_partial_test.rb b/actionpack/test/controller/new_base/render_partial_test.rb
index 5c7e66dba2..d800ea264d 100644
--- a/actionpack/test/controller/new_base/render_partial_test.rb
+++ b/actionpack/test/controller/new_base/render_partial_test.rb
@@ -5,10 +5,17 @@ module RenderPartial
class BasicController < ActionController::Base
self.view_paths = [ActionView::FixtureResolver.new(
- "render_partial/basic/_basic.html.erb" => "BasicPartial!",
- "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>"
+ "render_partial/basic/_basic.html.erb" => "BasicPartial!",
+ "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>",
+ "render_partial/basic/with_json.html.erb" => "<%= render 'with_json.json' %>",
+ "render_partial/basic/_with_json.json.erb" => "<%= render 'final' %>",
+ "render_partial/basic/_final.json.erb" => "{ final: json }"
)]
+ def html_with_json_inside_json
+ render :action => "with_json"
+ end
+
def changing
@test_unchanged = 'hello'
render :action => "basic"
@@ -22,6 +29,12 @@ module RenderPartial
get :changing
assert_response("goodbyeBasicPartial!goodbye")
end
+
+ test "rendering a template with renders another partial with other format that renders other partial in the same format" do
+ get :html_with_json_inside_json
+ assert_content_type "text/html; charset=utf-8"
+ assert_response "{ final: json }"
+ end
end
end
diff --git a/actionpack/test/controller/new_base/render_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb
index fea98d6bbd..d31193a063 100644
--- a/actionpack/test/controller/new_base/render_template_test.rb
+++ b/actionpack/test/controller/new_base/render_template_test.rb
@@ -8,13 +8,21 @@ module RenderTemplate
"shared.html.erb" => "Elastica",
"locals.html.erb" => "The secret is <%= secret %>",
"xml_template.xml.builder" => "xml.html do\n xml.p 'Hello'\nend",
- "with_raw.html.erb" => "Hello <%=raw '<strong>this is raw</strong>' %>"
+ "with_raw.html.erb" => "Hello <%=raw '<strong>this is raw</strong>' %>",
+ "test/with_json.html.erb" => "<%= render :template => 'test/with_json.json' %>",
+ "test/with_json.json.erb" => "<%= render :template => 'test/final' %>",
+ "test/final.json.erb" => "{ final: json }",
+ "test/with_error.html.erb" => "<%= idontexist %>"
)]
def index
render :template => "test/basic"
end
+ def html_with_json_inside_json
+ render :template => "test/with_json"
+ end
+
def index_without_key
render "test/basic"
end
@@ -42,6 +50,10 @@ module RenderTemplate
def with_raw
render :template => "with_raw"
end
+
+ def with_error
+ render :template => "test/with_error"
+ end
end
class TestWithoutLayout < Rack::TestCase
@@ -88,6 +100,18 @@ module RenderTemplate
assert_body "Hello <strong>this is raw</strong>"
assert_status 200
end
+
+ test "rendering a template with renders another template with other format that renders other template in the same format" do
+ get :html_with_json_inside_json
+ assert_content_type "text/html; charset=utf-8"
+ assert_response "{ final: json }"
+ end
+
+ test "rendering a template with error properly exceprts the code" do
+ get :with_error
+ assert_status 500
+ assert_match "undefined local variable or method `idontexist'", response.body
+ end
end
class WithLayoutController < ::ApplicationController
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index 3efed8bef6..04709e5346 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -385,6 +385,18 @@ class RequestTest < ActiveSupport::TestCase
assert_equal({"bar" => 2}, request.query_parameters)
end
+ test "parameters still accessible after rack parse error" do
+ mock_rack_env = { "QUERY_STRING" => "x[y]=1&x[y][][w]=2", "rack.input" => "foo" }
+ request = nil
+ begin
+ request = stub_request(mock_rack_env)
+ request.parameters
+ rescue TypeError => e
+ # rack will raise a TypeError when parsing this query string
+ end
+ assert_equal({}, request.parameters)
+ end
+
test "formats with accept header" do
request = stub_request 'HTTP_ACCEPT' => 'text/html'
request.expects(:parameters).at_least_once.returns({})
diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb
index ce6c397e32..2a478c214f 100644
--- a/actionpack/test/dispatch/show_exceptions_test.rb
+++ b/actionpack/test/dispatch/show_exceptions_test.rb
@@ -1,6 +1,7 @@
require 'abstract_unit'
class ShowExceptionsTest < ActionDispatch::IntegrationTest
+
Boomer = lambda do |env|
req = ActionDispatch::Request.new(env)
case req.path
@@ -12,6 +13,8 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
raise ActionController::NotImplemented
when "/unprocessable_entity"
raise ActionController::InvalidAuthenticityToken
+ when "/not_found_original_exception"
+ raise ActionView::Template::Error.new('template', {}, AbstractController::ActionNotFound.new)
else
raise "puke!"
end
@@ -101,4 +104,21 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
assert_response 500
assert_match("&quot;foo&quot;=&gt;&quot;[FILTERED]&quot;", body)
end
+
+ test "show registered original exception for wrapped exceptions when consider_all_requests_local is false" do
+ @app = ProductionApp
+ self.remote_addr = '208.77.188.166'
+
+ get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_match(/404 error/, body)
+ end
+
+ test "show registered original exception for wrapped exceptions when consider_all_requests_local is true" do
+ @app = DevelopmentApp
+
+ get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_match(/AbstractController::ActionNotFound/, body)
+ end
end
diff --git a/actionpack/test/fixtures/layout_tests/alt/hello.erb b/actionpack/test/fixtures/layout_tests/alt/hello.erb
new file mode 100644
index 0000000000..1055c36659
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/alt/hello.erb
@@ -0,0 +1 @@
+alt/hello.erb
diff --git a/actionpack/test/fixtures/layout_tests/alt/hello.rhtml b/actionpack/test/fixtures/layout_tests/alt/hello.rhtml
deleted file mode 100644
index fcda6cf97a..0000000000
--- a/actionpack/test/fixtures/layout_tests/alt/hello.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-alt/hello.rhtml
diff --git a/actionpack/test/fixtures/layout_tests/alt/layouts/alt.rhtml b/actionpack/test/fixtures/layout_tests/alt/layouts/alt.erb
index e69de29bb2..e69de29bb2 100644
--- a/actionpack/test/fixtures/layout_tests/alt/layouts/alt.rhtml
+++ b/actionpack/test/fixtures/layout_tests/alt/layouts/alt.erb
diff --git a/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.erb b/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.erb
new file mode 100644
index 0000000000..121bc079a1
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.erb
@@ -0,0 +1 @@
+controller_name_space/nested.erb <%= yield %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.rhtml b/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.rhtml
deleted file mode 100644
index 5f86a7de4d..0000000000
--- a/actionpack/test/fixtures/layout_tests/layouts/controller_name_space/nested.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-controller_name_space/nested.rhtml <%= yield %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/layouts/item.erb b/actionpack/test/fixtures/layout_tests/layouts/item.erb
new file mode 100644
index 0000000000..60f04d77d5
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/layouts/item.erb
@@ -0,0 +1 @@
+item.erb <%= yield %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/layouts/item.rhtml b/actionpack/test/fixtures/layout_tests/layouts/item.rhtml
deleted file mode 100644
index 1bc7cbda06..0000000000
--- a/actionpack/test/fixtures/layout_tests/layouts/item.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-item.rhtml <%= yield %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/layouts/layout_test.erb b/actionpack/test/fixtures/layout_tests/layouts/layout_test.erb
new file mode 100644
index 0000000000..b74ac0840d
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/layouts/layout_test.erb
@@ -0,0 +1 @@
+layout_test.erb <%= yield %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/layouts/layout_test.rhtml b/actionpack/test/fixtures/layout_tests/layouts/layout_test.rhtml
deleted file mode 100644
index c0f2642b40..0000000000
--- a/actionpack/test/fixtures/layout_tests/layouts/layout_test.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-layout_test.rhtml <%= yield %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/views/goodbye.erb b/actionpack/test/fixtures/layout_tests/views/goodbye.erb
new file mode 100644
index 0000000000..4ee911188e
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/views/goodbye.erb
@@ -0,0 +1 @@
+hello.erb \ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/views/goodbye.rhtml b/actionpack/test/fixtures/layout_tests/views/goodbye.rhtml
deleted file mode 100644
index bbccf0913e..0000000000
--- a/actionpack/test/fixtures/layout_tests/views/goodbye.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-hello.rhtml \ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/views/hello.erb b/actionpack/test/fixtures/layout_tests/views/hello.erb
new file mode 100644
index 0000000000..4ee911188e
--- /dev/null
+++ b/actionpack/test/fixtures/layout_tests/views/hello.erb
@@ -0,0 +1 @@
+hello.erb \ No newline at end of file
diff --git a/actionpack/test/fixtures/layout_tests/views/hello.rhtml b/actionpack/test/fixtures/layout_tests/views/hello.rhtml
deleted file mode 100644
index bbccf0913e..0000000000
--- a/actionpack/test/fixtures/layout_tests/views/hello.rhtml
+++ /dev/null
@@ -1 +0,0 @@
-hello.rhtml \ No newline at end of file
diff --git a/actionpack/test/fixtures/old_content_type/render_default_for_rxml.rxml b/actionpack/test/fixtures/old_content_type/render_default_for_builder.builder
index 598d62e2fc..598d62e2fc 100644
--- a/actionpack/test/fixtures/old_content_type/render_default_for_rxml.rxml
+++ b/actionpack/test/fixtures/old_content_type/render_default_for_builder.builder
diff --git a/actionpack/test/fixtures/old_content_type/render_default_for_rhtml.rhtml b/actionpack/test/fixtures/old_content_type/render_default_for_erb.erb
index c7926d48bb..c7926d48bb 100644
--- a/actionpack/test/fixtures/old_content_type/render_default_for_rhtml.rhtml
+++ b/actionpack/test/fixtures/old_content_type/render_default_for_erb.erb
diff --git a/actionpack/test/fixtures/test/_object_inspector.erb b/actionpack/test/fixtures/test/_object_inspector.erb
new file mode 100644
index 0000000000..53af593821
--- /dev/null
+++ b/actionpack/test/fixtures/test/_object_inspector.erb
@@ -0,0 +1 @@
+<%= object_inspector.inspect -%> \ No newline at end of file
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index 8809e510fb..acb6e7aa64 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -4,18 +4,6 @@ require 'controller/fake_models'
class FormHelperTest < ActionView::TestCase
tests ActionView::Helpers::FormHelper
- class Developer
- def name_before_type_cast
- "David"
- end
-
- def name
- "Santiago"
- end
-
- attr_writer :language
- end
-
def form_for(*)
@output_buffer = super
end
@@ -278,24 +266,6 @@ class FormHelperTest < ActionView::TestCase
text_field("user", "email", :type => "email")
end
- def test_text_field_from_a_user_defined_method
- @developer = Developer.new
- assert_dom_equal(
- '<input id="developer_name" name="developer[name]" size="30" type="text" value="Santiago" />', text_field("developer", "name")
- )
- end
-
- def test_text_field_on_a_model_with_undefined_attr_reader
- @developer = Developer.new
- @developer.language = 'ruby'
- begin
- text_field("developer", "language")
- rescue NoMethodError => error
- message = error.message
- end
- assert_equal "Model #{Developer} does not respond to language", message
- end
-
def test_check_box
assert_dom_equal(
'<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />',
@@ -765,11 +735,11 @@ class FormHelperTest < ActionView::TestCase
def test_form_for_with_search_field
# Test case for bug which would emit an "object" attribute
# when used with form_for using a search_field form helper
- form_for(Post.new, :url => "/search", :html => { :id => 'search-post' }) do |f|
+ form_for(Post.new, :url => "/search", :html => { :id => 'search-post', :method => :get}) do |f|
concat f.search_field(:title)
end
- expected = whole_form("/search", "search-post", "new_post") do
+ expected = whole_form("/search", "search-post", "new_post", "get") do
"<input name='post[title]' size='30' type='search' id='post_title' />"
end
@@ -1558,17 +1528,20 @@ class FormHelperTest < ActionView::TestCase
def snowman(method = nil)
txt = %{<div style="margin:0;padding:0;display:inline">}
txt << %{<input name="utf8" type="hidden" value="&#x2713;" />}
- txt << %{<input name="_method" type="hidden" value="#{method}" />} if method
+ if (method && !['get','post'].include?(method.to_s))
+ txt << %{<input name="_method" type="hidden" value="#{method}" />}
+ end
txt << %{</div>}
end
- def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil)
+ def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil)
txt = %{<form accept-charset="UTF-8" action="#{action}"}
txt << %{ enctype="multipart/form-data"} if multipart
txt << %{ data-remote="true"} if remote
txt << %{ class="#{html_class}"} if html_class
txt << %{ id="#{id}"} if id
- txt << %{ method="post">}
+ method = method.to_s == "get" ? "get" : "post"
+ txt << %{ method="#{method}">}
end
def whole_form(action = "/", id = nil, html_class = nil, options = nil)
@@ -1580,7 +1553,7 @@ class FormHelperTest < ActionView::TestCase
method = options
end
- form_text(action, id, html_class, remote, multipart) + snowman(method) + contents + "</form>"
+ form_text(action, id, html_class, remote, multipart, method) + snowman(method) + contents + "</form>"
end
def test_default_form_builder
diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb
index 8c8e87ae9f..f3933a25b9 100644
--- a/actionpack/test/template/form_tag_helper_test.rb
+++ b/actionpack/test/template/form_tag_helper_test.rb
@@ -13,19 +13,23 @@ class FormTagHelperTest < ActionView::TestCase
txt = %{<div style="margin:0;padding:0;display:inline">}
txt << %{<input name="utf8" type="hidden" value="&#x2713;" />}
- txt << %{<input name="_method" type="hidden" value="#{method}" />} if method
+ if (method && !['get','post'].include?(method.to_s))
+ txt << %{<input name="_method" type="hidden" value="#{method}" />}
+ end
txt << %{</div>}
end
def form_text(action = "http://www.example.com", options = {})
- remote, enctype, html_class, id = options.values_at(:remote, :enctype, :html_class, :id)
+ remote, enctype, html_class, id, method = options.values_at(:remote, :enctype, :html_class, :id, :method)
+
+ method = method.to_s == "get" ? "get" : "post"
txt = %{<form accept-charset="UTF-8" action="#{action}"}
txt << %{ enctype="multipart/form-data"} if enctype
txt << %{ data-remote="true"} if remote
txt << %{ class="#{html_class}"} if html_class
txt << %{ id="#{id}"} if id
- txt << %{ method="post">}
+ txt << %{ method="#{method}">}
end
def whole_form(action = "http://www.example.com", options = {})
diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb
index 6fb8d39818..435936b19f 100644
--- a/actionpack/test/template/log_subscriber_test.rb
+++ b/actionpack/test/template/log_subscriber_test.rb
@@ -57,7 +57,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
end
def test_render_partial_with_implicit_path
- @view.stubs(:controller_path).returns("test")
+ @view.stubs(:controller_prefix).returns("test")
@view.render(Customer.new("david"), :greeting => "hi")
wait
@@ -74,7 +74,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
end
def test_render_collection_with_implicit_path
- @view.stubs(:controller_path).returns("test")
+ @view.stubs(:controller_prefix).returns("test")
@view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi")
wait
@@ -83,7 +83,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
end
def test_render_collection_template_without_path
- @view.stubs(:controller_path).returns("test")
+ @view.stubs(:controller_prefix).returns("test")
@view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi")
wait
diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb
index cc71cb42d0..6d3b26e131 100644
--- a/actionpack/test/template/lookup_context_test.rb
+++ b/actionpack/test/template/lookup_context_test.rb
@@ -100,8 +100,8 @@ class LookupContextTest < ActiveSupport::TestCase
@lookup_context.with_fallbacks do
assert_equal 3, @lookup_context.view_paths.size
- assert @lookup_context.view_paths.include?(ActionView::FileSystemResolver.new(""))
- assert @lookup_context.view_paths.include?(ActionView::FileSystemResolver.new("/"))
+ assert @lookup_context.view_paths.include?(ActionView::FallbackFileSystemResolver.new(""))
+ assert @lookup_context.view_paths.include?(ActionView::FallbackFileSystemResolver.new("/"))
end
end
@@ -163,4 +163,66 @@ class LookupContextTest < ActiveSupport::TestCase
template = @lookup_context.find("foo", "test", true)
assert_equal "Bar", template.source
end
+
+ test "can disable the cache on demand" do
+ @lookup_context.view_paths = ActionView::FixtureResolver.new("test/_foo.erb" => "Foo")
+ old_template = @lookup_context.find("foo", "test", true)
+
+ template = @lookup_context.find("foo", "test", true)
+ assert_equal template, old_template
+
+ assert @lookup_context.cache
+ template = @lookup_context.disable_cache do
+ assert !@lookup_context.cache
+ @lookup_context.find("foo", "test", true)
+ end
+ assert @lookup_context.cache
+
+ assert_not_equal template, old_template
+ end
+end
+
+class LookupContextWithFalseCaching < ActiveSupport::TestCase
+ def setup
+ @resolver = ActionView::FixtureResolver.new("test/_foo.erb" => ["Foo", Time.utc(2000)])
+ @resolver.stubs(:caching?).returns(false)
+ @lookup_context = ActionView::LookupContext.new(@resolver, {})
+ end
+
+ test "templates are always found in the resolver but timestamp is checked before being compiled" do
+ template = @lookup_context.find("foo", "test", true)
+ assert_equal "Foo", template.source
+
+ # Now we are going to change the template, but it won't change the returned template
+ # since the timestamp is the same.
+ @resolver.hash["test/_foo.erb"][0] = "Bar"
+ template = @lookup_context.find("foo", "test", true)
+ assert_equal "Foo", template.source
+
+ # Now update the timestamp.
+ @resolver.hash["test/_foo.erb"][1] = Time.now.utc
+ template = @lookup_context.find("foo", "test", true)
+ assert_equal "Bar", template.source
+ end
+
+ test "if no template was found in the second lookup, give it higher preference" do
+ template = @lookup_context.find("foo", "test", true)
+ assert_equal "Foo", template.source
+
+ @resolver.hash.clear
+ assert_raise ActionView::MissingTemplate do
+ @lookup_context.find("foo", "test", true)
+ end
+ end
+
+ test "if no template was cached in the first lookup, do not use the cache in the second" do
+ @resolver.hash.clear
+ assert_raise ActionView::MissingTemplate do
+ @lookup_context.find("foo", "test", true)
+ end
+
+ @resolver.hash["test/_foo.erb"] = ["Foo", Time.utc(2000)]
+ template = @lookup_context.find("foo", "test", true)
+ assert_equal "Foo", template.source
+ end
end \ No newline at end of file
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 205fdcf345..17bb610b6a 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -114,7 +114,7 @@ module RenderTestCases
end
def test_render_sub_template_with_errors
- @view.render(:file => "test/sub_template_raise")
+ @view.render(:template => "test/sub_template_raise")
flunk "Render did not raise Template::Error"
rescue ActionView::Template::Error => e
assert_match %r!method.*doesnt_exist!, e.message
@@ -123,10 +123,25 @@ module RenderTestCases
assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name
end
+ def test_render_file_with_errors
+ @view.render(:file => File.expand_path("test/_raise", FIXTURE_LOAD_PATH))
+ flunk "Render did not raise Template::Error"
+ rescue ActionView::Template::Error => e
+ assert_match %r!method.*doesnt_exist!, e.message
+ assert_equal "", e.sub_template_message
+ assert_equal "1", e.line_number
+ assert_equal "1: <%= doesnt_exist %>", e.annoted_source_code.strip
+ assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name
+ end
+
def test_render_object
assert_equal "Hello: david", @view.render(:partial => "test/customer", :object => Customer.new("david"))
end
+ def test_render_object_with_array
+ assert_equal "[1, 2, 3]", @view.render(:partial => "test/object_inspector", :object => [1, 2, 3])
+ end
+
def test_render_partial_collection
assert_equal "Hello: davidHello: mary", @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ])
end
diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb
index c7c33af670..63f792d328 100644
--- a/actionpack/test/template/template_test.rb
+++ b/actionpack/test/template/template_test.rb
@@ -1,9 +1,18 @@
require "abstract_unit"
+require "logger"
class TestERBTemplate < ActiveSupport::TestCase
- ERBHandler = ActionView::Template::Handlers::ERB
+ ERBHandler = ActionView::Template::Handlers::ERB.new
+
+ class LookupContext
+ def disable_cache
+ yield
+ end
+ end
class Context
+ attr_accessor :_template
+
def initialize
@output_buffer = "original"
@_virtual_path = nil
@@ -15,15 +24,18 @@ class TestERBTemplate < ActiveSupport::TestCase
def partial
ActionView::Template.new(
- "<%= @_virtual_path %>",
+ "<%= @_template.virtual_path %>",
"partial",
ERBHandler,
:virtual_path => "partial"
)
end
+ def lookup_context
+ @lookup_context ||= LookupContext.new
+ end
+
def logger
- require "logger"
Logger.new(STDERR)
end
@@ -32,16 +44,16 @@ class TestERBTemplate < ActiveSupport::TestCase
end
end
- def new_template(body = "<%= hello %>", handler = ERBHandler, details = {})
- ActionView::Template.new(body, "hello template", ERBHandler, {:virtual_path => "hello"})
+ def new_template(body = "<%= hello %>", details = {})
+ ActionView::Template.new(body, "hello template", ERBHandler, {:virtual_path => "hello"}.merge!(details))
end
def render(locals = {})
- @template.render(@obj, locals)
+ @template.render(@context, locals)
end
def setup
- @obj = Context.new
+ @context = Context.new
end
def test_basic_template
@@ -49,24 +61,96 @@ class TestERBTemplate < ActiveSupport::TestCase
assert_equal "Hello", render
end
+ def test_template_loses_its_source_after_rendering
+ @template = new_template
+ render
+ assert_nil @template.source
+ end
+
+ def test_template_does_not_lose_its_source_after_rendering_if_it_does_not_have_a_virtual_path
+ @template = new_template("Hello", :virtual_path => nil)
+ render
+ assert_equal "Hello", @template.source
+ end
+
def test_locals
@template = new_template("<%= my_local %>")
+ @template.locals = [:my_local]
assert_equal "I'm a local", render(:my_local => "I'm a local")
end
def test_restores_buffer
@template = new_template
assert_equal "Hello", render
- assert_equal "original", @obj.my_buffer
+ assert_equal "original", @context.my_buffer
end
def test_virtual_path
- @template = new_template("<%= @_virtual_path %>" \
+ @template = new_template("<%= @_template.virtual_path %>" \
"<%= partial.render(self, {}) %>" \
- "<%= @_virtual_path %>")
+ "<%= @_template.virtual_path %>")
assert_equal "hellopartialhello", render
end
+ def test_refresh_with_templates
+ @template = new_template("Hello", :virtual_path => "test/foo")
+ @template.locals = [:key]
+ @context.lookup_context.expects(:find_template).with("foo", "test", false, [:key]).returns("template")
+ assert_equal "template", @template.refresh(@context)
+ end
+
+ def test_refresh_with_partials
+ @template = new_template("Hello", :virtual_path => "test/_foo")
+ @template.locals = [:key]
+ @context.lookup_context.expects(:find_template).with("foo", "test", true, [:key]).returns("partial")
+ assert_equal "partial", @template.refresh(@context)
+ end
+
+ def test_refresh_raises_an_error_without_virtual_path
+ @template = new_template("Hello", :virtual_path => nil)
+ assert_raise RuntimeError do
+ @template.refresh(@context)
+ end
+ end
+
+ def test_template_expire_sets_the_timestamp_to_1970
+ @template = new_template("Hello", :updated_at => Time.utc(2010))
+ assert_equal Time.utc(2010), @template.updated_at
+ @template.expire!
+ assert_equal Time.utc(1970), @template.updated_at
+ end
+
+ def test_template_rerender_renders_a_template_like_self
+ @template = new_template("Hello", :virtual_path => "test/foo_bar")
+ @context.expects(:render).with(:template => "test/foo_bar").returns("template")
+ assert_equal "template", @template.rerender(@context)
+ end
+
+ def test_template_rerender_renders_a_root_template_like_self
+ @template = new_template("Hello", :virtual_path => "foo_bar")
+ @context.expects(:render).with(:template => "foo_bar").returns("template")
+ assert_equal "template", @template.rerender(@context)
+ end
+
+ def test_template_rerender_renders_a_partial_like_self
+ @template = new_template("Hello", :virtual_path => "test/_foo_bar")
+ @context.expects(:render).with(:partial => "test/foo_bar").returns("partial")
+ assert_equal "partial", @template.rerender(@context)
+ end
+
+ def test_template_rerender_renders_a_root_partial_like_self
+ @template = new_template("Hello", :virtual_path => "_foo_bar")
+ @context.expects(:render).with(:partial => "foo_bar").returns("partial")
+ assert_equal "partial", @template.rerender(@context)
+ end
+
+ def test_rerender_raises_an_error_without_virtual_path
+ @template = new_template("Hello", :virtual_path => nil)
+ assert_raise RuntimeError do
+ @template.rerender(@context)
+ end
+ end
+
if "ruby".encoding_aware?
def test_resulting_string_is_utf8
@template = new_template
@@ -101,14 +185,14 @@ class TestERBTemplate < ActiveSupport::TestCase
# inside Rails.
def test_lying_with_magic_comment
assert_raises(ActionView::Template::Error) do
- @template = new_template("# encoding: UTF-8\nhello \xFCmlat")
+ @template = new_template("# encoding: UTF-8\nhello \xFCmlat", :virtual_path => nil)
render
end
end
def test_encoding_can_be_specified_with_magic_comment_in_erb
with_external_encoding Encoding::UTF_8 do
- @template = new_template("<%# encoding: ISO-8859-1 %>hello \xFCmlat")
+ @template = new_template("<%# encoding: ISO-8859-1 %>hello \xFCmlat", :virtual_path => nil)
result = render
assert_equal Encoding::UTF_8, render.encoding
assert_equal "hello \u{fc}mlat", render
@@ -117,7 +201,7 @@ class TestERBTemplate < ActiveSupport::TestCase
def test_error_when_template_isnt_valid_utf8
assert_raises(ActionView::Template::Error, /\xFC/) do
- @template = new_template("hello \xFCmlat")
+ @template = new_template("hello \xFCmlat", :virtual_path => nil)
render
end
end
diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb
index 952719a589..763080550b 100644
--- a/actionpack/test/template/translation_helper_test.rb
+++ b/actionpack/test/template/translation_helper_test.rb
@@ -31,13 +31,13 @@ class TranslationHelperTest < ActiveSupport::TestCase
def test_scoping_by_partial
I18n.expects(:translate).with("test.translation.helper", :raise => true).returns("helper")
- @view = ActionView::Base.new(ActionController::Base.view_paths, {})
+ @view = ::ActionView::Base.new(ActionController::Base.view_paths, {})
assert_equal "helper", @view.render(:file => "test/translation")
end
def test_scoping_by_partial_of_an_array
I18n.expects(:translate).with("test.scoped_translation.foo.bar", :raise => true).returns(["foo", "bar"])
- @view = ActionView::Base.new(ActionController::Base.view_paths, {})
+ @view = ::ActionView::Base.new(ActionController::Base.view_paths, {})
assert_equal "foobar", @view.render(:file => "test/scoped_translation")
end
diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb
index 98276da559..a6fdf806a4 100644
--- a/actionpack/test/template/url_helper_test.rb
+++ b/actionpack/test/template/url_helper_test.rb
@@ -9,7 +9,7 @@ class UrlHelperTest < ActiveSupport::TestCase
# or request.
#
# In those cases, we'll set up a simple mock
- attr_accessor :controller, :request
+ attr_accessor :controller, :request, :_template
routes = ActionDispatch::Routing::RouteSet.new
routes.draw do
@@ -69,6 +69,13 @@ class UrlHelperTest < ActiveSupport::TestCase
)
end
+ def test_button_to_with_javascript_disable_with
+ assert_dom_equal(
+ "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\"><div><input data-disable-with=\"Greeting...\" type=\"submit\" value=\"Hello\" /></div></form>",
+ button_to("Hello", "http://www.example.com", :disable_with => "Greeting...")
+ )
+ end
+
def test_button_to_with_remote_and_javascript_confirm
assert_dom_equal(
"<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\" data-remote=\"true\"><div><input data-confirm=\"Are you sure?\" type=\"submit\" value=\"Hello\" /></div></form>",
@@ -76,6 +83,20 @@ class UrlHelperTest < ActiveSupport::TestCase
)
end
+ def test_button_to_with_remote_and_javascript_disable_with
+ assert_dom_equal(
+ "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\" data-remote=\"true\"><div><input data-disable-with=\"Greeting...\" type=\"submit\" value=\"Hello\" /></div></form>",
+ button_to("Hello", "http://www.example.com", :remote => true, :disable_with => "Greeting...")
+ )
+ end
+
+ def test_button_to_with_remote_and_javascript_confirm_and_javascript_disable_with
+ assert_dom_equal(
+ "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\" data-remote=\"true\"><div><input data-disable-with=\"Greeting...\" data-confirm=\"Are you sure?\" type=\"submit\" value=\"Hello\" /></div></form>",
+ button_to("Hello", "http://www.example.com", :remote => true, :confirm => "Are you sure?", :disable_with => "Greeting...")
+ )
+ end
+
def test_button_to_with_remote_false
assert_dom_equal(
"<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\"><div><input type=\"submit\" value=\"Hello\" /></div></form>",
diff --git a/activemodel/lib/active_model.rb b/activemodel/lib/active_model.rb
index 9b8f843432..be0f24ff92 100644
--- a/activemodel/lib/active_model.rb
+++ b/activemodel/lib/active_model.rb
@@ -24,7 +24,7 @@
activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
require 'active_support'
-
+require 'active_model/version'
module ActiveModel
extend ActiveSupport::Autoload
@@ -45,7 +45,6 @@ module ActiveModel
autoload :Serialization
autoload :TestCase
autoload :Translation
- autoload :VERSION
autoload :Validations
autoload :Validator
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
index 1b5fb55b79..b044caa8d3 100644
--- a/activemodel/lib/active_model/validations.rb
+++ b/activemodel/lib/active_model/validations.rb
@@ -114,7 +114,7 @@ module ActiveModel
# end
#
# def must_be_friends
- # errors.add(:base, ("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
+ # errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
# end
# end
#
diff --git a/activerecord/RUNNING_UNIT_TESTS b/activerecord/RUNNING_UNIT_TESTS
index 324df2c025..18e3936d8a 100644
--- a/activerecord/RUNNING_UNIT_TESTS
+++ b/activerecord/RUNNING_UNIT_TESTS
@@ -31,8 +31,13 @@ That'll run the base suite using the MySQL-Ruby adapter. Some tests rely on the
being initialized - you can initialize the schema with:
rake test_mysql TEST=test/cases/aaa_create_tables_test.rb
+ rake mysql:build_databases
+
+To setup the testing environment for PostgreSQL use this command:
+
+ rake postgresql:build_databases
The incantation for running a particular test looks like this
- ruby -w -I"lib:test:test/connections/native_postgresql" test/cases/datatype_test_postgresql.rb -n test_timestamp_with_zone_values_without_rails_time_zone_support
+ rake test TEST=test/cases/datatype_test_postgresql.rb TESTOPTS="-n test_timestamp_with_zone_values_without_rails_time_zone_support"
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
index f692e5ac89..c80bce2849 100644
--- a/activerecord/lib/active_record.rb
+++ b/activerecord/lib/active_record.rb
@@ -33,12 +33,12 @@ require 'active_support/i18n'
require 'active_model'
require 'arel'
+require 'active_record/version'
+
module ActiveRecord
extend ActiveSupport::Autoload
eager_autoload do
- autoload :VERSION
-
autoload :ActiveRecordError, 'active_record/errors'
autoload :ConnectionNotEstablished, 'active_record/errors'
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index ff6be4ff19..78b3507dd9 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -423,7 +423,7 @@ module ActiveRecord #:nodoc:
class << self # Class methods
delegate :find, :first, :last, :all, :destroy, :destroy_all, :exists?, :delete, :delete_all, :update, :update_all, :to => :scoped
delegate :find_each, :find_in_batches, :to => :scoped
- delegate :select, :group, :order, :reorder, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped
+ delegate :select, :group, :order, :except, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped
delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped
# Executes a custom SQL query against your database and returns all the results. The results will
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
index 37e584a629..ca9314ec99 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -73,12 +73,7 @@ module ActiveRecord
# The mutex used to synchronize pool access
@connection_mutex = Monitor.new
@queue = @connection_mutex.new_cond
-
- # default 5 second timeout unless on ruby 1.9
- @timeout =
- if RUBY_VERSION < '1.9'
- spec.config[:wait_timeout] || 5
- end
+ @timeout = spec.config[:wait_timeout] || 5
# default max pool size to 5
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
@@ -161,7 +156,6 @@ module ActiveRecord
keys = @reserved_connections.keys - Thread.list.find_all { |t|
t.alive?
}.map { |thread| thread.object_id }
-
keys.each do |key|
checkin @reserved_connections[key]
@reserved_connections.delete(key)
@@ -194,16 +188,18 @@ module ActiveRecord
checkout_new_connection
end
return conn if conn
- # No connections available; wait for one
- if @queue.wait(@timeout)
+
+ @queue.wait(@timeout)
+
+ if(@checked_out.size < @connections.size)
next
else
- # try looting dead threads
clear_stale_cached_connections!
if @size == @checked_out.size
raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}. The max pool size is currently #{@size}; consider increasing it."
end
end
+
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
index e2b3773a99..a7a12faac2 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
@@ -10,28 +10,31 @@ module ActiveRecord
return value.quoted_id if value.respond_to?(:quoted_id)
case value
- when String, ActiveSupport::Multibyte::Chars
- value = value.to_s
- if column && column.type == :binary && column.class.respond_to?(:string_to_binary)
- "'#{quote_string(column.class.string_to_binary(value))}'" # ' (for ruby-mode)
- elsif column && [:integer, :float].include?(column.type)
- value = column.type == :integer ? value.to_i : value.to_f
- value.to_s
- else
- "'#{quote_string(value)}'" # ' (for ruby-mode)
- end
- when NilClass then "NULL"
- when TrueClass then (column && column.type == :integer ? '1' : quoted_true)
- when FalseClass then (column && column.type == :integer ? '0' : quoted_false)
- when Float, Fixnum, Bignum then value.to_s
- # BigDecimals need to be output in a non-normalized form and quoted.
- when BigDecimal then value.to_s('F')
+ when String, ActiveSupport::Multibyte::Chars
+ value = value.to_s
+ return "'#{quote_string(value)}'" unless column
+
+ case column.type
+ when :binary then "'#{quote_string(column.string_to_binary(value))}'"
+ when :integer then value.to_i.to_s
+ when :float then value.to_f.to_s
+ else
+ "'#{quote_string(value)}'"
+ end
+
+ when true, false
+ if column && column.type == :integer
+ value ? '1' : '0'
else
- if value.acts_like?(:date) || value.acts_like?(:time)
- "'#{quoted_date(value)}'"
- else
- "'#{quote_string(value.to_s)}'"
- end
+ value ? quoted_true : quoted_false
+ end
+ # BigDecimals need to be put in a non-normalized form and quoted.
+ when nil then "NULL"
+ when BigDecimal then value.to_s('F')
+ when Numeric then value.to_s
+ when Date, Time then "'#{quoted_date(value)}'"
+ else
+ "'#{quote_string(value.to_s)}'"
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
index 6480aeb171..60ccf9edf3 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -114,6 +114,11 @@ module ActiveRecord
type_cast(default)
end
+ # Used to convert from Strings to BLOBs
+ def string_to_binary(value)
+ self.class.string_to_binary(value)
+ end
+
class << self
# Used to convert from Strings to BLOBs
def string_to_binary(value)
@@ -268,6 +273,10 @@ module ActiveRecord
# for generating a number of table creation or table changing SQL statements.
class ColumnDefinition < Struct.new(:base, :name, :type, :limit, :precision, :scale, :default, :null) #:nodoc:
+ def string_to_binary(value)
+ value
+ end
+
def sql_type
base.type_to_sql(type.to_sym, limit, precision, scale) rescue type
end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
index e7f7b37b27..a4b336dfaf 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -132,7 +132,7 @@ module ActiveRecord
cattr_accessor :emulate_booleans
self.emulate_booleans = true
- ADAPTER_NAME = 'MySQL'.freeze
+ ADAPTER_NAME = 'MySQL'
LOST_CONNECTION_ERROR_MESSAGES = [
"Server shutdown in progress",
@@ -140,10 +140,10 @@ module ActiveRecord
"Lost connection to MySQL server during query",
"MySQL server has gone away" ]
- QUOTED_TRUE, QUOTED_FALSE = '1'.freeze, '0'.freeze
+ QUOTED_TRUE, QUOTED_FALSE = '1', '0'
NATIVE_DATABASE_TYPES = {
- :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY".freeze,
+ :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY",
:string => { :name => "varchar", :limit => 255 },
:text => { :name => "text" },
:integer => { :name => "int", :limit => 4 },
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index 5f14284615..dce9e99d27 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -180,8 +180,6 @@ module ActiveRecord
# <encoding></tt> call on the connection.
# * <tt>:min_messages</tt> - An optional client min messages that is used in a
# <tt>SET client_min_messages TO <min_messages></tt> call on the connection.
- # * <tt>:allow_concurrency</tt> - If true, use async query methods so Ruby threads don't deadlock;
- # otherwise, use blocking query methods.
class PostgreSQLAdapter < AbstractAdapter
class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
def xml(*args)
@@ -930,7 +928,7 @@ module ActiveRecord
PGconn.translate_results = false if PGconn.respond_to?(:translate_results=)
# Ignore async_exec and async_query when using postgres-pr.
- @async = @config[:allow_concurrency] && @connection.respond_to?(:async_exec)
+ @async = @connection.respond_to?(:async_exec)
# Money type has a fixed precision of 10 in PostgreSQL 8.2 and below, and as of
# PostgreSQL 8.3 it has a fixed precision of 19. PostgreSQLColumn.extract_precision
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index 9ac18f9939..a4c09b654a 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -384,23 +384,32 @@ module ActiveRecord
end
end
- def copy(destination, sources)
+ def copy(destination, sources, options = {})
copied = []
- sources.each do |scope, path|
- destination_migrations = ActiveRecord::Migrator.migrations(destination)
+ destination_migrations = ActiveRecord::Migrator.migrations(destination)
+ last = destination_migrations.last
+ sources.each do |name, path|
source_migrations = ActiveRecord::Migrator.migrations(path)
- last = destination_migrations.last
source_migrations.each do |migration|
- next if destination_migrations.any? { |m| m.name == migration.name && m.scope == scope.to_s }
+ source = File.read(migration.filename)
+ source = "# This migration comes from #{name} (originally #{migration.version})\n#{source}"
+
+ if duplicate = destination_migrations.detect { |m| m.name == migration.name }
+ options[:on_skip].call(name, migration) if File.read(duplicate.filename) != source && options[:on_skip]
+ next
+ end
migration.version = next_migration_number(last ? last.version + 1 : 0).to_i
+ new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.rb")
+ old_path, migration.filename = migration.filename, new_path
last = migration
- new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{scope}.rb")
- FileUtils.cp(migration.filename, new_path)
- copied << new_path
+ FileUtils.cp(old_path, migration.filename)
+ copied << migration
+ options[:on_copy].call(name, migration, old_path) if options[:on_copy]
+ destination_migrations << migration
end
end
@@ -419,13 +428,17 @@ module ActiveRecord
# MigrationProxy is used to defer loading of the actual migration classes
# until they are needed
- class MigrationProxy < Struct.new(:name, :version, :filename, :scope)
+ class MigrationProxy < Struct.new(:name, :version, :filename)
- def initialize(name, version, filename, scope)
+ def initialize(name, version, filename)
super
@migration = nil
end
+ def basename
+ File.basename(filename)
+ end
+
delegate :migrate, :announce, :write, :to=>:migration
private
@@ -510,18 +523,18 @@ module ActiveRecord
seen = Hash.new false
migrations = files.map do |file|
- version, name, scope = file.scan(/([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?.rb/).first
+ version, name = file.scan(/([0-9]+)_([_a-z0-9]*).rb/).first
raise IllegalMigrationNameError.new(file) unless version
version = version.to_i
name = name.camelize
raise DuplicateMigrationVersionError.new(version) if seen[version]
- raise DuplicateMigrationNameError.new(name) if seen[[name, scope]]
+ raise DuplicateMigrationNameError.new(name) if seen[name]
- seen[version] = seen[[name, scope]] = true
+ seen[version] = seen[name] = true
- MigrationProxy.new(name, version, file, scope)
+ MigrationProxy.new(name, version, file)
end
migrations.sort_by(&:version)
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 58c705c8b2..1fbc8a1d32 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -2,28 +2,7 @@ namespace :db do
task :load_config => :rails_env do
require 'active_record'
ActiveRecord::Base.configurations = Rails.application.config.database_configuration
- ActiveRecord::Migrator.migrations_path = Rails.application.config.paths.db.migrate.to_a.first
- end
-
- task :copy_migrations => :load_config do
- to_load = ENV["FROM"].blank? ? :all : ENV["FROM"].split(",").map {|n| n.strip }
- railties = {}
- Rails.application.railties.all do |railtie|
- next unless to_load == :all || to_load.include?(railtie.railtie_name)
-
- if railtie.config.respond_to?(:paths) && railtie.config.paths.db
- railties[railtie.railtie_name] = railtie.config.paths.db.migrate.to_a.first
- end
- end
-
- copied = ActiveRecord::Migration.copy(ActiveRecord::Migrator.migrations_path, railties)
-
- if copied.blank?
- puts "No migrations were copied, project is up to date."
- else
- puts "The following migrations were copied:"
- puts copied.map{ |path| File.basename(path) }.join("\n")
- end
+ ActiveRecord::Migrator.migrations_path = Rails.application.paths["db/migrate"].first
end
namespace :create do
@@ -501,8 +480,31 @@ namespace :db do
end
namespace :railties do
- desc "Copies missing migrations from Railties (e.g. plugins, engines). You can specify Railties to use with FROM=railtie1,railtie2"
- task :copy_migrations => 'db:copy_migrations'
+ namespace :install do
+ # desc "Copies missing migrations from Railties (e.g. plugins, engines). You can specify Railties to use with FROM=railtie1,railtie2"
+ task :migrations => :"db:load_config" do
+ to_load = ENV["FROM"].blank? ? :all : ENV["FROM"].split(",").map {|n| n.strip }
+ railties = {}
+ Rails.application.railties.all do |railtie|
+ next unless to_load == :all || to_load.include?(railtie.railtie_name)
+
+ if railtie.respond_to?(:paths) && (path = railtie.paths["db/migrate"].first)
+ railties[railtie.railtie_name] = path
+ end
+ end
+
+ on_skip = Proc.new do |name, migration|
+ puts "NOTE: Migration #{migration.basename} from #{name} has been skipped. Migration with the same name already exists."
+ end
+
+ on_copy = Proc.new do |name, migration, old_path|
+ puts "Copied migration #{migration.basename} from #{name}"
+ end
+
+ ActiveRecord::Migration.copy( ActiveRecord::Migrator.migrations_path, railties,
+ :on_skip => on_skip, :on_copy => on_copy)
+ end
+ end
end
task 'test:prepare' => 'db:test:prepare'
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index d79ef78b4d..6bf698fe97 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -177,7 +177,7 @@ module ActiveRecord
distinct = options[:distinct] || distinct
if @group_values.any?
- execute_grouped_calculation(operation, column_name)
+ execute_grouped_calculation(operation, column_name, distinct)
else
execute_simple_calculation(operation, column_name, distinct)
end
@@ -191,19 +191,23 @@ module ActiveRecord
end
end
+ def operation_over_aggregate_column(column, operation, distinct)
+ operation == 'count' ? column.count(distinct) : column.send(operation)
+ end
+
def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
column = aggregate_column(column_name)
# Postgresql doesn't like ORDER BY when there are no GROUP BY
relation = except(:order)
- select_value = operation == 'count' ? column.count(distinct) : column.send(operation)
+ select_value = operation_over_aggregate_column(column, operation, distinct)
relation.select_values = [select_value]
type_cast_calculated_value(@klass.connection.select_value(relation.to_sql), column_for(column_name), operation)
end
- def execute_grouped_calculation(operation, column_name) #:nodoc:
+ def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
group_attr = @group_values.first
association = @klass.reflect_on_association(group_attr.to_sym)
associated = association && association.macro == :belongs_to # only count belongs_to associations
@@ -221,7 +225,7 @@ module ActiveRecord
relation = except(:group).group(group)
relation.select_values = [
- aggregate_column(column_name).send(operation).as(aggregate_alias),
+ operation_over_aggregate_column(aggregate_column(column_name), operation, distinct).as(aggregate_alias),
"#{group_field} AS #{group_alias}"
]
@@ -273,7 +277,7 @@ module ActiveRecord
else type_cast_using_column(value, column)
end
else
- value
+ type_cast_using_column(value, column)
end
end
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 5034caf084..b763e22ec6 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -291,8 +291,8 @@ module ActiveRecord
record = where(primary_key.eq(id)).first
unless record
- conditions = arel.wheres.map { |x| x.value }.join(', ')
- conditions = " [WHERE #{conditions}]" if conditions.present?
+ conditions = arel.where_sql
+ conditions = " [#{conditions}]" if conditions
raise RecordNotFound, "Couldn't find #{@klass.name} with ID=#{id}#{conditions}"
end
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index f314ff861f..59ce76ea42 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -6,7 +6,7 @@ module ActiveRecord
extend ActiveSupport::Concern
attr_accessor :includes_values, :eager_load_values, :preload_values,
- :select_values, :group_values, :order_values, :reorder_flag, :joins_values, :where_values, :having_values,
+ :select_values, :group_values, :order_values, :joins_values, :where_values, :having_values,
:limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value, :from_value
def includes(*args)
@@ -53,15 +53,6 @@ module ActiveRecord
relation
end
- def reorder(*args)
- relation = clone
- unless args.blank?
- relation.order_values = args
- relation.reorder_flag = true
- end
- relation
- end
-
def joins(*args)
relation = clone
diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb
index 9ecdb99bee..dcddc3dac4 100644
--- a/activerecord/lib/active_record/relation/spawn_methods.rb
+++ b/activerecord/lib/active_record/relation/spawn_methods.rb
@@ -19,20 +19,11 @@ module ActiveRecord
end
end
- (Relation::MULTI_VALUE_METHODS - [:joins, :where, :order]).each do |method|
+ (Relation::MULTI_VALUE_METHODS - [:joins, :where]).each do |method|
value = r.send(:"#{method}_values")
merged_relation.send(:"#{method}_values=", merged_relation.send(:"#{method}_values") + value) if value.present?
end
- order_value = r.order_values
- if order_value.present?
- if r.reorder_flag
- merged_relation.order_values = order_value
- else
- merged_relation.order_values = merged_relation.order_values + order_value
- end
- end
-
merged_relation = merged_relation.joins(r.joins_values)
merged_wheres = @where_values
diff --git a/activerecord/lib/active_record/serialization.rb b/activerecord/lib/active_record/serialization.rb
index 398eb1534a..2bde06f562 100644
--- a/activerecord/lib/active_record/serialization.rb
+++ b/activerecord/lib/active_record/serialization.rb
@@ -22,7 +22,7 @@ module ActiveRecord #:nodoc:
end
private
- # Add associations specified via the <tt>:includes</tt> option.
+ # Add associations specified via the <tt>:include</tt> option.
#
# Expects a block that takes as arguments:
# +association+ - name of the association
diff --git a/activerecord/lib/active_record/test_case.rb b/activerecord/lib/active_record/test_case.rb
index 31b5a8651b..014a900c71 100644
--- a/activerecord/lib/active_record/test_case.rb
+++ b/activerecord/lib/active_record/test_case.rb
@@ -36,21 +36,6 @@ module ActiveRecord
assert_queries(0, &block)
end
- def self.use_concurrent_connections
- setup :connection_allow_concurrency_setup
- teardown :connection_allow_concurrency_teardown
- end
-
- def connection_allow_concurrency_setup
- @connection = ActiveRecord::Base.remove_connection
- ActiveRecord::Base.establish_connection(@connection.merge({:allow_concurrency => true}))
- end
-
- def connection_allow_concurrency_teardown
- ActiveRecord::Base.clear_all_connections!
- ActiveRecord::Base.establish_connection(@connection)
- end
-
def with_kcode(kcode)
if RUBY_VERSION < '1.9'
orig_kcode, $KCODE = $KCODE, kcode
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 7ec40906d4..61fbf01a50 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -346,4 +346,13 @@ class CalculationsTest < ActiveRecord::TestCase
def test_from_option_with_table_different_than_class
assert_equal Account.count(:all), Company.count(:all, :from => 'accounts')
end
+
+ def test_distinct_is_honored_when_used_with_count_operation_after_group
+ # Count the number of authors for approved topics
+ approved_topics_count = Topic.group(:approved).count(:author_name)[true]
+ assert_equal approved_topics_count, 3
+ # Count the number of distinct authors for approved Topics
+ distinct_authors_for_approved_count = Topic.group(:approved).count(:author_name, :distinct => true)[true]
+ assert_equal distinct_authors_for_approved_count, 2
+ end
end
diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb
index 82b3c36ed2..f0ec5c751c 100644
--- a/activerecord/test/cases/connection_pool_test.rb
+++ b/activerecord/test/cases/connection_pool_test.rb
@@ -26,6 +26,35 @@ module ActiveRecord
"threads should have been removed")
assert_equal pool.checkins.length, threads.length
end
+
+ def test_checkout_behaviour
+ pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
+ connection = pool.connection
+ assert_not_nil connection
+ threads = []
+ 4.times do |i|
+ threads << Thread.new(i) do |pool_count|
+ connection = pool.connection
+ assert_not_nil connection
+ end
+ end
+
+ threads.each {|t| t.join}
+
+ Thread.new do
+ threads.each do |t|
+ thread_ids = pool.instance_variable_get(:@reserved_connections).keys
+ assert thread_ids.include?(t.object_id)
+ end
+
+ pool.connection
+ threads.each do |t|
+ thread_ids = pool.instance_variable_get(:@reserved_connections).keys
+ assert !thread_ids.include?(t.object_id)
+ end
+ end.join()
+
+ end
end
end
end
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index e7126964cd..4ddcdc010b 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -257,6 +257,7 @@ unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
fixtures :people, :readers
def setup
+ Person.connection_pool.clear_reloadable_connections!
# Avoid introspection queries during tests.
Person.columns; Reader.columns
end
@@ -306,8 +307,6 @@ unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
end
if current_adapter?(:PostgreSQLAdapter, :OracleAdapter)
- use_concurrent_connections
-
def test_no_locks_no_wait
first, second = duel { Person.find 1 }
assert first.end > second.end
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index 6e8ee95613..ef949300b0 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -1910,9 +1910,9 @@ if ActiveRecord::Base.connection.supports_migrations?
@existing_migrations = Dir[@migrations_path + "/*.rb"]
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"})
- assert File.exists?(@migrations_path + "/4_people_have_hobbies.bukkits.rb")
- assert File.exists?(@migrations_path + "/5_people_have_descriptions.bukkits.rb")
- assert_equal [@migrations_path + "/4_people_have_hobbies.bukkits.rb", @migrations_path + "/5_people_have_descriptions.bukkits.rb"], copied
+ assert File.exists?(@migrations_path + "/4_people_have_hobbies.rb")
+ assert File.exists?(@migrations_path + "/5_people_have_descriptions.rb")
+ assert_equal [@migrations_path + "/4_people_have_hobbies.rb", @migrations_path + "/5_people_have_descriptions.rb"], copied.map(&:filename)
files_count = Dir[@migrations_path + "/*.rb"].length
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"})
@@ -1928,12 +1928,13 @@ if ActiveRecord::Base.connection.supports_migrations?
@existing_migrations = Dir[@migrations_path + "/*.rb"]
sources = ActiveSupport::OrderedHash.new
- sources[:bukkits] = sources[:omg] = MIGRATIONS_ROOT + "/to_copy"
+ sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy"
+ sources[:omg] = MIGRATIONS_ROOT + "/to_copy2"
ActiveRecord::Migration.copy(@migrations_path, sources)
- assert File.exists?(@migrations_path + "/4_people_have_hobbies.omg.rb")
- assert File.exists?(@migrations_path + "/5_people_have_descriptions.omg.rb")
- assert File.exists?(@migrations_path + "/6_people_have_hobbies.bukkits.rb")
- assert File.exists?(@migrations_path + "/7_people_have_descriptions.bukkits.rb")
+ assert File.exists?(@migrations_path + "/4_people_have_hobbies.rb")
+ assert File.exists?(@migrations_path + "/5_people_have_descriptions.rb")
+ assert File.exists?(@migrations_path + "/6_create_articles.rb")
+ assert File.exists?(@migrations_path + "/7_create_comments.rb")
files_count = Dir[@migrations_path + "/*.rb"].length
ActiveRecord::Migration.copy(@migrations_path, sources)
@@ -1948,11 +1949,11 @@ if ActiveRecord::Base.connection.supports_migrations?
Time.travel_to(created_at = Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
- assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
- assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
- expected = [@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb",
- @migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb"]
- assert_equal expected, copied
+ assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
+ expected = [@migrations_path + "/20100726101010_people_have_hobbies.rb",
+ @migrations_path + "/20100726101011_people_have_descriptions.rb"]
+ assert_equal expected, copied.map(&:filename)
files_count = Dir[@migrations_path + "/*.rb"].length
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
@@ -1968,14 +1969,15 @@ if ActiveRecord::Base.connection.supports_migrations?
@existing_migrations = Dir[@migrations_path + "/*.rb"]
sources = ActiveSupport::OrderedHash.new
- sources[:bukkits] = sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_timestamps"
+ sources[:bukkits] = MIGRATIONS_ROOT + "/to_copy_with_timestamps"
+ sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_timestamps2"
Time.travel_to(created_at = Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, sources)
- assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.omg.rb")
- assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.omg.rb")
- assert File.exists?(@migrations_path + "/20100726101012_people_have_hobbies.bukkits.rb")
- assert File.exists?(@migrations_path + "/20100726101013_people_have_descriptions.bukkits.rb")
+ assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
+ assert File.exists?(@migrations_path + "/20100726101012_create_articles.rb")
+ assert File.exists?(@migrations_path + "/20100726101013_create_comments.rb")
assert_equal 4, copied.length
files_count = Dir[@migrations_path + "/*.rb"].length
@@ -1992,8 +1994,8 @@ if ActiveRecord::Base.connection.supports_migrations?
Time.travel_to(created_at = Time.utc(2010, 2, 20, 10, 10, 10)) do
ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
- assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.bukkits.rb")
- assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.bukkits.rb")
+ assert File.exists?(@migrations_path + "/20100301010102_people_have_hobbies.rb")
+ assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.rb")
files_count = Dir[@migrations_path + "/*.rb"].length
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
@@ -2004,14 +2006,32 @@ if ActiveRecord::Base.connection.supports_migrations?
clear
end
+ def test_skipping_migrations
+ @migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
+ @existing_migrations = Dir[@migrations_path + "/*.rb"]
+
+ sources = ActiveSupport::OrderedHash.new
+ sources[:bukkits] = sources[:omg] = MIGRATIONS_ROOT + "/to_copy_with_timestamps"
+
+ skipped = []
+ on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" }
+ copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
+ assert_equal 2, copied.length
+
+ assert_equal 2, skipped.length
+ assert_equal ["bukkits PeopleHaveHobbies", "bukkits PeopleHaveDescriptions"], skipped
+ ensure
+ clear
+ end
+
def test_copying_migrations_to_empty_directory
@migrations_path = MIGRATIONS_ROOT + "/empty"
@existing_migrations = []
Time.travel_to(created_at = Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
- assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
- assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
+ assert File.exists?(@migrations_path + "/20100726101010_people_have_hobbies.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
assert_equal 2, copied.length
end
ensure
diff --git a/activerecord/test/cases/quoting_test.rb b/activerecord/test/cases/quoting_test.rb
new file mode 100644
index 0000000000..2ef5b5a800
--- /dev/null
+++ b/activerecord/test/cases/quoting_test.rb
@@ -0,0 +1,220 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class QuotingTest < ActiveRecord::TestCase
+ class FakeColumn < ActiveRecord::ConnectionAdapters::Column
+ attr_accessor :type
+
+ def initialize type
+ @type = type
+ end
+ end
+
+ def setup
+ @quoter = Class.new { include Quoting }.new
+ end
+
+ def test_quoted_true
+ assert_equal "'t'", @quoter.quoted_true
+ end
+
+ def test_quoted_false
+ assert_equal "'f'", @quoter.quoted_false
+ end
+
+ def test_quote_column_name
+ assert_equal "foo", @quoter.quote_column_name('foo')
+ end
+
+ def test_quote_table_name
+ assert_equal "foo", @quoter.quote_table_name('foo')
+ end
+
+ def test_quote_table_name_calls_quote_column_name
+ @quoter.extend(Module.new {
+ def quote_column_name(string)
+ 'lol'
+ end
+ })
+ assert_equal 'lol', @quoter.quote_table_name('foo')
+ end
+
+ def test_quote_string
+ assert_equal "''", @quoter.quote_string("'")
+ assert_equal "\\\\", @quoter.quote_string("\\")
+ assert_equal "hi''i", @quoter.quote_string("hi'i")
+ assert_equal "hi\\\\i", @quoter.quote_string("hi\\i")
+ end
+
+ def test_quoted_date
+ t = Date.today
+ assert_equal t.to_s(:db), @quoter.quoted_date(t)
+ end
+
+ def test_quoted_time_utc
+ before = ActiveRecord::Base.default_timezone
+ ActiveRecord::Base.default_timezone = :utc
+ t = Time.now
+ assert_equal t.getutc.to_s(:db), @quoter.quoted_date(t)
+ ensure
+ ActiveRecord::Base.default_timezone = before
+ end
+
+ def test_quoted_time_local
+ before = ActiveRecord::Base.default_timezone
+ ActiveRecord::Base.default_timezone = :local
+ t = Time.now
+ assert_equal t.getlocal.to_s(:db), @quoter.quoted_date(t)
+ ensure
+ ActiveRecord::Base.default_timezone = before
+ end
+
+ def test_quoted_time_crazy
+ before = ActiveRecord::Base.default_timezone
+ ActiveRecord::Base.default_timezone = :asdfasdf
+ t = Time.now
+ assert_equal t.getlocal.to_s(:db), @quoter.quoted_date(t)
+ ensure
+ ActiveRecord::Base.default_timezone = before
+ end
+
+ def test_quoted_datetime_utc
+ before = ActiveRecord::Base.default_timezone
+ ActiveRecord::Base.default_timezone = :utc
+ t = DateTime.now
+ assert_equal t.getutc.to_s(:db), @quoter.quoted_date(t)
+ ensure
+ ActiveRecord::Base.default_timezone = before
+ end
+
+ ###
+ # DateTime doesn't define getlocal, so make sure it does nothing
+ def test_quoted_datetime_local
+ before = ActiveRecord::Base.default_timezone
+ ActiveRecord::Base.default_timezone = :local
+ t = DateTime.now
+ assert_equal t.to_s(:db), @quoter.quoted_date(t)
+ ensure
+ ActiveRecord::Base.default_timezone = before
+ end
+
+ def test_quote_with_quoted_id
+ assert_equal 1, @quoter.quote(Struct.new(:quoted_id).new(1), nil)
+ assert_equal 1, @quoter.quote(Struct.new(:quoted_id).new(1), 'foo')
+ end
+
+ def test_quote_nil
+ assert_equal 'NULL', @quoter.quote(nil, nil)
+ assert_equal 'NULL', @quoter.quote(nil, 'foo')
+ end
+
+ def test_quote_true
+ assert_equal @quoter.quoted_true, @quoter.quote(true, nil)
+ assert_equal '1', @quoter.quote(true, Struct.new(:type).new(:integer))
+ end
+
+ def test_quote_false
+ assert_equal @quoter.quoted_false, @quoter.quote(false, nil)
+ assert_equal '0', @quoter.quote(false, Struct.new(:type).new(:integer))
+ end
+
+ def test_quote_float
+ float = 1.2
+ assert_equal float.to_s, @quoter.quote(float, nil)
+ assert_equal float.to_s, @quoter.quote(float, Object.new)
+ end
+
+ def test_quote_fixnum
+ fixnum = 1
+ assert_equal fixnum.to_s, @quoter.quote(fixnum, nil)
+ assert_equal fixnum.to_s, @quoter.quote(fixnum, Object.new)
+ end
+
+ def test_quote_bignum
+ bignum = 1 << 100
+ assert_equal bignum.to_s, @quoter.quote(bignum, nil)
+ assert_equal bignum.to_s, @quoter.quote(bignum, Object.new)
+ end
+
+ def test_quote_bigdecimal
+ bigdec = BigDecimal.new((1 << 100).to_s)
+ assert_equal bigdec.to_s('F'), @quoter.quote(bigdec, nil)
+ assert_equal bigdec.to_s('F'), @quoter.quote(bigdec, Object.new)
+ end
+
+ def test_dates_and_times
+ @quoter.extend(Module.new { def quoted_date(value) 'lol' end })
+ assert_equal "'lol'", @quoter.quote(Date.today, nil)
+ assert_equal "'lol'", @quoter.quote(Date.today, Object.new)
+ assert_equal "'lol'", @quoter.quote(Time.now, nil)
+ assert_equal "'lol'", @quoter.quote(Time.now, Object.new)
+ assert_equal "'lol'", @quoter.quote(DateTime.now, nil)
+ assert_equal "'lol'", @quoter.quote(DateTime.now, Object.new)
+ end
+
+ def test_crazy_object
+ crazy = Class.new { def to_s; 'lol' end }.new
+ assert_equal "'lol'", @quoter.quote(crazy, nil)
+ assert_equal "'lol'", @quoter.quote(crazy, Object.new)
+ end
+
+ def test_crazy_object_calls_quote_string
+ crazy = Class.new { def to_s; 'lo\l' end }.new
+ assert_equal "'lo\\\\l'", @quoter.quote(crazy, nil)
+ assert_equal "'lo\\\\l'", @quoter.quote(crazy, Object.new)
+ end
+
+ def test_quote_string_no_column
+ assert_equal "'lo\\\\l'", @quoter.quote('lo\l', nil)
+ end
+
+ def test_quote_as_mb_chars_no_column
+ string = ActiveSupport::Multibyte::Chars.new('lo\l')
+ assert_equal "'lo\\\\l'", @quoter.quote(string, nil)
+ end
+
+ def test_quote_string_int_column
+ assert_equal "1", @quoter.quote('1', FakeColumn.new(:integer))
+ assert_equal "1", @quoter.quote('1.2', FakeColumn.new(:integer))
+ end
+
+ def test_quote_string_float_column
+ assert_equal "1.0", @quoter.quote('1', FakeColumn.new(:float))
+ assert_equal "1.2", @quoter.quote('1.2', FakeColumn.new(:float))
+ end
+
+ def test_quote_as_mb_chars_binary_column
+ string = ActiveSupport::Multibyte::Chars.new('lo\l')
+ assert_equal "'lo\\\\l'", @quoter.quote(string, FakeColumn.new(:binary))
+ end
+
+ def test_quote_binary_without_string_to_binary
+ assert_equal "'lo\\\\l'", @quoter.quote('lo\l', FakeColumn.new(:binary))
+ end
+
+ def test_quote_binary_with_string_to_binary
+ col = Class.new(FakeColumn) {
+ def string_to_binary(value)
+ 'foo'
+ end
+ }.new(:binary)
+ assert_equal "'foo'", @quoter.quote('lo\l', col)
+ end
+
+ def test_quote_as_mb_chars_binary_column_with_string_to_binary
+ col = Class.new(FakeColumn) {
+ def string_to_binary(value)
+ 'foo'
+ end
+ }.new(:binary)
+ string = ActiveSupport::Multibyte::Chars.new('lo\l')
+ assert_equal "'foo'", @quoter.quote(string, col)
+ end
+
+ def test_string_with_crazy_column
+ assert_equal "'lo\\\\l'", @quoter.quote('lo\l', FakeColumn.new(:foo))
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb
index 090e6c8bc9..64365c1d75 100644
--- a/activerecord/test/cases/relation_scoping_test.rb
+++ b/activerecord/test/cases/relation_scoping_test.rb
@@ -384,18 +384,12 @@ class DefaultScopingTest < ActiveRecord::TestCase
assert_equal expected, received
end
- def test_reorder_overrides_default_scope_order
+ def test_except_and_order_overrides_default_scope_order
expected = Developer.order('name DESC').collect { |dev| dev.name }
- received = DeveloperOrderedBySalary.reorder('name DESC').collect { |dev| dev.name }
+ received = DeveloperOrderedBySalary.except(:order).order('name DESC').collect { |dev| dev.name }
assert_equal expected, received
end
- def test_reordered_scope_overrides_default_scope_order
- not_expected = DeveloperOrderedBySalary.first # Jamis -> name DESC
- received = DeveloperOrderedBySalary.reordered_by_name.first # David -> name
- assert not_expected.id != received.id
- end
-
def test_nested_exclusive_scope
expected = Developer.find(:all, :limit => 100).collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.send(:with_exclusive_scope, :find => { :limit => 100 }) do
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index fec5e6731f..df4e84ca29 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -135,12 +135,6 @@ class RelationTest < ActiveRecord::TestCase
assert_equal topics(:fourth).title, topics.first.title
end
- def test_finding_with_reorder
- topics = Topic.order('author_name').order('title').reorder('id')
- assert_equal 4, topics.to_a.size
- assert_equal topics(:first).title, topics.first.title
- end
-
def test_finding_with_order_and_take
entrants = Entrant.order("id ASC").limit(2).to_a
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index 9255190613..8385286fd0 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -529,8 +529,6 @@ end if Topic.connection.supports_savepoints?
if current_adapter?(:PostgreSQLAdapter)
class ConcurrentTransactionTest < TransactionTest
- use_concurrent_connections
-
# This will cause transactions to overlap and fail unless they are performed on
# separate database connections.
def test_transaction_per_thread
diff --git a/activerecord/test/migrations/to_copy2/1_create_articles.rb b/activerecord/test/migrations/to_copy2/1_create_articles.rb
new file mode 100644
index 0000000000..0f048d90f7
--- /dev/null
+++ b/activerecord/test/migrations/to_copy2/1_create_articles.rb
@@ -0,0 +1,7 @@
+class CreateArticles < ActiveRecord::Migration
+ def self.up
+ end
+
+ def self.down
+ end
+end
diff --git a/activerecord/test/migrations/to_copy2/2_create_comments.rb b/activerecord/test/migrations/to_copy2/2_create_comments.rb
new file mode 100644
index 0000000000..0f048d90f7
--- /dev/null
+++ b/activerecord/test/migrations/to_copy2/2_create_comments.rb
@@ -0,0 +1,7 @@
+class CreateArticles < ActiveRecord::Migration
+ def self.up
+ end
+
+ def self.down
+ end
+end
diff --git a/activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb
new file mode 100644
index 0000000000..0f048d90f7
--- /dev/null
+++ b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb
@@ -0,0 +1,7 @@
+class CreateArticles < ActiveRecord::Migration
+ def self.up
+ end
+
+ def self.down
+ end
+end
diff --git a/activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb
new file mode 100644
index 0000000000..2b048edbb5
--- /dev/null
+++ b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb
@@ -0,0 +1,7 @@
+class CreateComments < ActiveRecord::Migration
+ def self.up
+ end
+
+ def self.down
+ end
+end
diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb
index 947583af76..32d060cf09 100644
--- a/activerecord/test/models/developer.rb
+++ b/activerecord/test/models/developer.rb
@@ -88,7 +88,6 @@ class DeveloperOrderedBySalary < ActiveRecord::Base
self.table_name = 'developers'
default_scope :order => 'salary DESC'
scope :by_name, order('name DESC')
- scope :reordered_by_name, reorder('name')
def self.all_ordered_by_name
with_scope(:find => { :order => 'name DESC' }) do
diff --git a/activeresource/lib/active_resource.rb b/activeresource/lib/active_resource.rb
index 3e4a1dd4a1..186865f811 100644
--- a/activeresource/lib/active_resource.rb
+++ b/activeresource/lib/active_resource.rb
@@ -29,6 +29,7 @@ $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include
require 'active_support'
require 'active_model'
+require 'active_resource/version'
module ActiveResource
extend ActiveSupport::Autoload
diff --git a/activeresource/lib/active_resource/http_mock.rb b/activeresource/lib/active_resource/http_mock.rb
index ddd3fb1f5d..9aefde7c30 100644
--- a/activeresource/lib/active_resource/http_mock.rb
+++ b/activeresource/lib/active_resource/http_mock.rb
@@ -100,11 +100,11 @@ module ActiveResource
# Accepts a block which declares a set of requests and responses for the HttpMock to respond to in
# the following format:
- #
+ #
# mock.http_method(path, request_headers = {}, body = nil, status = 200, response_headers = {})
- #
+ #
# === Example
- #
+ #
# @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
# ActiveResource::HttpMock.respond_to do |mock|
# mock.post "/people.xml", {}, @matz, 201, "Location" => "/people/1.xml"
@@ -112,65 +112,76 @@ module ActiveResource
# mock.put "/people/1.xml", {}, nil, 204
# mock.delete "/people/1.xml", {}, nil, 200
# end
- #
+ #
# Alternatively, accepts a hash of <tt>{Request => Response}</tt> pairs allowing you to generate
# these the following format:
- #
+ #
# ActiveResource::Request.new(method, path, body, request_headers)
# ActiveResource::Response.new(body, status, response_headers)
- #
+ #
# === Example
- #
+ #
# Request.new(:#{method}, path, nil, request_headers)
- #
+ #
# @matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
#
# create_matz = ActiveResource::Request.new(:post, '/people.xml', @matz, {})
# created_response = ActiveResource::Response.new("", 201, {"Location" => "/people/1.xml"})
# get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil)
# ok_response = ActiveResource::Response.new("", 200, {})
- #
+ #
# pairs = {create_matz => created_response, get_matz => ok_response}
- #
+ #
# ActiveResource::HttpMock.respond_to(pairs)
#
# Note, by default, every time you call +respond_to+, any previous request and response pairs stored
# in HttpMock will be deleted giving you a clean slate to work on.
- #
+ #
# If you want to override this behaviour, pass in +false+ as the last argument to +respond_to+
- #
+ #
# === Example
- #
+ #
# ActiveResource::HttpMock.respond_to do |mock|
# mock.send(:get, "/people/1", {}, "XML1")
# end
# ActiveResource::HttpMock.responses.length #=> 1
- #
+ #
# ActiveResource::HttpMock.respond_to(false) do |mock|
# mock.send(:get, "/people/2", {}, "XML2")
# end
# ActiveResource::HttpMock.responses.length #=> 2
- #
+ #
# This also works with passing in generated pairs of requests and responses, again, just pass in false
# as the last argument:
- #
+ #
# === Example
- #
+ #
# ActiveResource::HttpMock.respond_to do |mock|
# mock.send(:get, "/people/1", {}, "XML1")
# end
# ActiveResource::HttpMock.responses.length #=> 1
- #
+ #
# get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil)
# ok_response = ActiveResource::Response.new("", 200, {})
- #
+ #
# pairs = {get_matz => ok_response}
#
# ActiveResource::HttpMock.respond_to(pairs, false)
# ActiveResource::HttpMock.responses.length #=> 2
+ #
+ # # If you add a response with an existing request, it will be replaced
+ #
+ # fail_response = ActiveResource::Response.new("", 404, {})
+ # pairs = {get_matz => fail_response}
+ #
+ # ActiveResource::HttpMock.respond_to(pairs, false)
+ # ActiveResource::HttpMock.responses.length #=> 2
+ #
def respond_to(*args) #:yields: mock
pairs = args.first || {}
reset! if args.last.class != FalseClass
+
+ delete_responses_to_replace pairs.to_a
responses.concat pairs.to_a
if block_given?
yield Responder.new(responses)
@@ -179,6 +190,13 @@ module ActiveResource
end
end
+ def delete_responses_to_replace(new_responses)
+ new_responses.each{|nr|
+ request_to_remove = nr[0]
+ @@responses = responses.delete_if{|r| r[0] == request_to_remove}
+ }
+ end
+
# Deletes all logged requests and responses.
def reset!
requests.clear
diff --git a/activeresource/test/cases/http_mock_test.rb b/activeresource/test/cases/http_mock_test.rb
index d90d1e01b8..82b5e60c77 100644
--- a/activeresource/test/cases/http_mock_test.rb
+++ b/activeresource/test/cases/http_mock_test.rb
@@ -69,19 +69,19 @@ class HttpMockTest < ActiveSupport::TestCase
request(method, "/people/1", FORMAT_HEADER[method] => "application/json")
end
end
-
+
end
test "allows you to send in pairs directly to the respond_to method" do
matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
-
+
create_matz = ActiveResource::Request.new(:post, '/people.xml', matz, {})
created_response = ActiveResource::Response.new("", 201, {"Location" => "/people/1.xml"})
get_matz = ActiveResource::Request.new(:get, '/people/1.xml', nil)
ok_response = ActiveResource::Response.new(matz, 200, {})
-
+
pairs = {create_matz => created_response, get_matz => ok_response}
-
+
ActiveResource::HttpMock.respond_to(pairs)
assert_equal 2, ActiveResource::HttpMock.responses.length
assert_equal "", ActiveResource::HttpMock.responses.assoc(create_matz)[1].body
@@ -140,6 +140,34 @@ class HttpMockTest < ActiveSupport::TestCase
assert_equal 2, ActiveResource::HttpMock.responses.length
end
+ test "allows you to replace the existing reponse with the same request" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ matz = { :id => 1, :name => "Matz" }.to_xml(:root => "person")
+ get_matz = ActiveResource::Request.new(:get, '/people/1', nil)
+ ok_response = ActiveResource::Response.new(matz, 200, {})
+
+ ActiveResource::HttpMock.respond_to({get_matz => ok_response}, false)
+
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+ end
+
+ test "do not replace the response with the same path but different method" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ put_matz = ActiveResource::Request.new(:put, '/people/1', nil)
+ ok_response = ActiveResource::Response.new("", 200, {})
+
+ ActiveResource::HttpMock.respond_to({put_matz => ok_response}, false)
+ assert_equal 2, ActiveResource::HttpMock.responses.length
+ end
+
def request(method, path, headers = {}, body = nil)
if [:put, :post].include? method
@http.send(method, path, body, headers)
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index ba91e8bba3..6b87774978 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -35,6 +35,7 @@ module ActiveSupport
end
require "active_support/dependencies/autoload"
+require "active_support/version"
module ActiveSupport
extend ActiveSupport::Autoload
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
index 9eee3fc5e3..45263d482f 100644
--- a/activesupport/lib/active_support/cache/mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -1,7 +1,7 @@
begin
require 'memcache'
rescue LoadError => e
- $stderr.puts "You don't have memcache installed in your application. Please add it to your Gemfile and run bundle install"
+ $stderr.puts "You don't have memcache-client installed in your application. Please add it to your Gemfile and run bundle install"
raise e
end
require 'digest/md5'
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 0c1d46c7ec..8f8def5922 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -459,12 +459,12 @@ module ActiveSupport
#
# becomes
#
- # dispatch_callback :before, :authenticate, :per_key => {:unless => proc {|c| c.action_name == "index"}}
+ # set_callback :process_action, :before, :authenticate, :per_key => {:unless => proc {|c| c.action_name == "index"}}
#
# Per-Key conditions are evaluated only once per use of a given key.
# In the case of the above example, you would do:
#
- # run_callbacks(:dispatch, action_name) { ... dispatch stuff ... }
+ # run_callbacks(:process_action, action_name) { ... dispatch stuff ... }
#
# In that case, each action_name would get its own compiled callback
# method that took into consideration the per_key conditions. This
diff --git a/activesupport/lib/active_support/core_ext/logger.rb b/activesupport/lib/active_support/core_ext/logger.rb
index a1c351bfd9..e63a0a9ed9 100644
--- a/activesupport/lib/active_support/core_ext/logger.rb
+++ b/activesupport/lib/active_support/core_ext/logger.rb
@@ -4,18 +4,17 @@ require 'active_support/core_ext/class/attribute_accessors'
class Logger #:nodoc:
def self.define_around_helper(level)
module_eval <<-end_eval, __FILE__, __LINE__ + 1
- def around_#{level}(before_message, after_message, &block) # def around_debug(before_message, after_message, &block)
- self.#{level}(before_message) # self.debug(before_message)
- return_value = block.call(self) # return_value = block.call(self)
- self.#{level}(after_message) # self.debug(after_message)
- return return_value # return return_value
- end # end
+ def around_#{level}(before_message, after_message) # def around_debug(before_message, after_message, &block)
+ self.#{level}(before_message) # self.debug(before_message)
+ return_value = yield(self) # return_value = yield(self)
+ self.#{level}(after_message) # self.debug(after_message)
+ return_value # return_value
+ end # end
end_eval
end
[:debug, :info, :error, :fatal].each {|level| define_around_helper(level) }
end
-
require 'logger'
# Extensions to the built-in Ruby logger.
@@ -65,11 +64,11 @@ class Logger
formatter.datetime_format if formatter.respond_to?(:datetime_format)
end
- alias :old_formatter :formatter if method_defined?(:formatter)
- # Get the current formatter. The default formatter is a SimpleFormatter which only
- # displays the log message
- def formatter
- @formatter ||= SimpleFormatter.new
+ alias :old_initialize :initialize
+ # Overwrite initialize to set a default formatter.
+ def initialize(*args)
+ old_initialize(*args)
+ self.formatter = SimpleFormatter.new
end
# Simple formatter which only displays the message.
@@ -79,30 +78,4 @@ class Logger
"#{String === msg ? msg : msg.inspect}\n"
end
end
-
- private
- alias old_format_message format_message
-
- # Ruby 1.8.3 transposed the msg and progname arguments to format_message.
- # We can't test RUBY_VERSION because some distributions don't keep Ruby
- # and its standard library in sync, leading to installations of Ruby 1.8.2
- # with Logger from 1.8.3 and vice versa.
- if method_defined?(:formatter=)
- def format_message(severity, timestamp, progname, msg)
- formatter.call(severity, timestamp, progname, msg)
- end
- else
- def format_message(severity, timestamp, msg, progname)
- formatter.call(severity, timestamp, progname, msg)
- end
-
- attr_writer :formatter
- public :formatter=
-
- alias old_format_datetime format_datetime
- def format_datetime(datetime) datetime end
-
- alias old_msg2str msg2str
- def msg2str(msg) msg end
- end
end
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb
index e8215bc566..c406dd3c2e 100644
--- a/activesupport/lib/active_support/hash_with_indifferent_access.rb
+++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb
@@ -45,6 +45,8 @@ module ActiveSupport
regular_writer(convert_key(key), convert_value(value))
end
+ alias_method :store, :[]=
+
# Updates the instantized hash with values from the second:
#
# hash_1 = HashWithIndifferentAccess.new
diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb
index dfc3f01fa2..4adfaecd4a 100644
--- a/activesupport/lib/active_support/ordered_hash.rb
+++ b/activesupport/lib/active_support/ordered_hash.rb
@@ -79,15 +79,12 @@ module ActiveSupport
end
def []=(key, value)
- @keys << key if !has_key?(key)
+ @keys << key unless has_key?(key)
super
end
def delete(key)
- if has_key? key
- index = @keys.index(key)
- @keys.delete_at index
- end
+ @keys.delete key if has_key? key
super
end
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index 0f35eb9e78..545fed2684 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -316,6 +316,16 @@ class HashExtTest < Test::Unit::TestCase
assert_equal expected, hash_1
end
+ def test_store_on_indifferent_access
+ hash = HashWithIndifferentAccess.new
+ hash.store(:test1, 1)
+ hash.store('test1', 11)
+ hash[:test2] = 2
+ hash['test2'] = 22
+ expected = { "test1" => 11, "test2" => 22 }
+ assert_equal expected, hash
+ end
+
def test_reverse_merge
defaults = { :a => "x", :b => "y", :c => 10 }.freeze
options = { :a => 1, :b => 2 }
diff --git a/railties/CHANGELOG b/railties/CHANGELOG
index d2a4add375..5dd3a5108c 100644
--- a/railties/CHANGELOG
+++ b/railties/CHANGELOG
@@ -1,6 +1,10 @@
*Rails 3.1.0 (unreleased)*
-* Added Rack::Cache to the default middleware stack
+* Added -j parameter with jquery/prototype as options. Now you can create your apps with jQuery using `rails new myapp -j jquery`. The default is still Prototype. [siong1987]
+
+* Added Rack::Etag and Rack::ConditionalGet to the default middleware stack [José Valim]
+
+* Added Rack::Cache to the default middleware stack [Yehuda Katz and Carl Lerche]
* Engine is now rack application [Piotr Sarnacki]
diff --git a/railties/Rakefile b/railties/Rakefile
index 9ef6637c1e..9504661c0e 100644
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -45,8 +45,9 @@ task :generate_guides do
ruby "guides/rails_guides.rb"
end
-task :update_prototype_ujs do
- system "curl http://github.com/rails/prototype-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/rails.js"
+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"
end
# Validate guides -------------------------------------------------------------------------
diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile
index ac9052786e..34afebcae4 100644
--- a/railties/guides/source/action_mailer_basics.textile
+++ b/railties/guides/source/action_mailer_basics.textile
@@ -27,7 +27,7 @@ invoke test_unit
create test/functional/user_mailer_test.rb
</shell>
-So we got the mailer, the fixtures, and the tests.
+So we got the mailer, the views, and the tests.
h5. Edit the Mailer
@@ -198,7 +198,7 @@ Adding attachments has been simplified in Action Mailer 3.0.
attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
</ruby>
-NOTE: Mail will automatically Base64 encode an attachment, if you want something different, pre encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method.
+NOTE: Mail will automatically Base64 encode an attachment, if you want something different, pre-encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method.
* Pass the file name and specify headers and content and Action Mailer and Mail will use the settings you pass in.
@@ -247,7 +247,7 @@ h5. Sending Email To Multiple Recipients
It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The <tt>to:</tt> key however expects a string so you have join the list of recipients using a comma.
<ruby>
- Class AdminMailer < ActionMailer::Base
+ class AdminMailer < ActionMailer::Base
default :to => Admin.all.map(&:email).join(", "),
:from => "notification@example.com"
@@ -403,7 +403,7 @@ The above will send a multipart email with an attachment, properly nested with t
h3. Receiving Emails
-Receiving and parsing emails with Action Mailer can be a rather complex endeavour. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that. So, to receive emails in your Rails app you'll need:
+Receiving and parsing emails with Action Mailer can be a rather complex endeavour. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that. So, to receive emails in your Rails app you'll need to:
* Implement a +receive+ method in your mailer.
@@ -441,9 +441,9 @@ h3. Action Mailer Configuration
The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...)
|template_root|Determines the base from which template references will be made.|
-|logger|the logger is used for generating information on the mailing run if available. Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.|
-|smtp_settings|Allows detailed configuration for :smtp delivery method: :address - Allows you to use a remote mail server. Just change it from its default "localhost" setting. :port - On the off chance that your mail server doesn't run on port 25, you can change it. :domain - If you need to specify a HELO domain, you can do it here. :user_name - If your mail server requires authentication, set the username in this setting. :password - If your mail server requires authentication, set the password in this setting. :authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5.|
-|sendmail_settings|Allows you to override options for the :sendmail delivery method. :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail. :arguments - The command line arguments. Defaults to -i -t.|
+|logger|The logger is used for generating information on the mailing run if available. Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.|
+|smtp_settings|Allows detailed configuration for :smtp delivery method:<ul><li>:address - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li>:port - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li>:domain - If you need to specify a HELO domain, you can do it here.</li><li>:user_name - If your mail server requires authentication, set the username in this setting.</li><li>:password - If your mail server requires authentication, set the password in this setting.</li><li>:authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5.</li></ul>|
+|sendmail_settings|Allows you to override options for the :sendmail delivery method.<ul><li>:location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail.</li><li>:arguments - The command line arguments to be passed to sendmail. Defaults to -i -t.</li></ul>|
|raise_delivery_errors|Whether or not errors should be raised if the email fails to be delivered.|
|delivery_method|Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.|
|perform_deliveries|Determines whether deliver_* methods are actually carried out. By default they are, but this can be turned off to help functional testing.|
@@ -509,3 +509,5 @@ In the test we send the email and store the returned object in the +email+ varia
h3. Changelog
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/25
+
+* September 30, 2010: Fixed typos and reformatted Action Mailer configuration table for better understanding. "Jaime Iniesta":http://jaimeiniesta.com
diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile
index 843dfe530d..0e1a352ebd 100644
--- a/railties/guides/source/action_view_overview.textile
+++ b/railties/guides/source/action_view_overview.textile
@@ -253,9 +253,6 @@ javascript_include_tag :monkey # =>
<script type="text/javascript" src="/javascripts/tail.js"></script>
</ruby>
-h5. register_javascript_include_default
-
-Register one or more additional JavaScript files to be included when +javascript_include_tag :defaults+ is called. This method is typically intended to be called from plugin initialization to register additional +.js+ files that the plugin installed in +public/javascripts+.
h5. register_stylesheet_expansion
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile
index 9eae712a93..acb9c2c487 100644
--- a/railties/guides/source/getting_started.textile
+++ b/railties/guides/source/getting_started.textile
@@ -110,7 +110,7 @@ Active Resource provides a framework for managing the connection between busines
h5. Active Support
-Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in the Rails, both by the core code and by your applications.
+Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in Rails, both by the core code and by your applications.
h5. Railties
@@ -175,7 +175,7 @@ In any case, Rails will create a folder in your working directory called <tt>blo
|_.File/Folder|_.Purpose|
|Gemfile|This file allows you to specify what gem dependencies are needed for your Rails application.|
-|README.rdoc|This is a brief instruction manual for your application. Use it to tell others what your application does, how to set it up, and so on.|
+|README|This is a brief instruction manual for your application. Use it to tell others what your application does, how to set it up, and so on.|
|Rakefile|This file contains batch jobs that can be run from the terminal.|
|app/|Contains the controllers, models, and views for your application. You'll focus on this folder for the remainder of this guide.|
|config/|Configure your application's runtime rules, routes, database, and more.|
@@ -195,7 +195,7 @@ h4. Installing the Required Gems
Rails applications manage gem dependencies with "Bundler":http://gembundler.com/v1.0/index.html by default. As we don't need any other gems beyond the ones in the generated +Gemfile+ we can directly run
<shell>
-bundle install
+# bundle install
</shell>
to have them ready.
@@ -316,7 +316,7 @@ The first step to doing this is to delete the default page from your application
$ rm public/index.html
</shell>
-We need to do this as Rails will deliver any static file in the +public+ directory in preference to any dynamic contact we generate from the controllers.
+We need to do this as Rails will deliver any static file in the +public+ directory in preference to any dynamic content we generate from the controllers.
Now, you have to tell Rails where your actual home page is located. Open the file +config/routes.rb+ in your editor. This is your application's _routing file_ which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. This file contains many sample routes on commented lines, and one of them actually shows you how to connect the root of your site to a specific controller and action. Find the line beginning with +root :to+, uncomment it and change it like the following:
@@ -352,7 +352,7 @@ NOTE. While scaffolding will get you up and running quickly, the "one size fits
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:
|_.File |_.Purpose|
-|db/migrate/20100207214725_create_posts.rb.rb |Migration to create the posts table in your database (your name will include a different timestamp)|
+|db/migrate/20100207214725_create_posts.rb |Migration to create the posts table in your database (your name will include a different timestamp)|
|app/models/post.rb |The Post model|
|test/fixtures/posts.yml |Dummy posts for use in testing|
|app/controllers/posts_controller.rb |The Posts controller|
@@ -727,7 +727,6 @@ After finding the requested post, Rails uses the +edit.html.erb+ view to display
<%= link_to 'Show', @post %> |
<%= link_to 'Back', posts_path %>
-<% end %>
</erb>
Again, as with the +new+ action, the +edit+ action is using the +form+ partial, this time however, the form will do a PUT action to the PostsController and the submit button will display "Update Post"
diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile
index 599ddccdd6..3e02bc0158 100644
--- a/railties/guides/source/initialization.textile
+++ b/railties/guides/source/initialization.textile
@@ -3070,7 +3070,7 @@ The +Rails::Plugin::Configuration+ class may be a bit difficult to find at first
<ruby>
module Rails
- class Plugin < Railtie
+ class Plugin < Engine
...
end
end
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
index 7d4fb69d3b..a8a8ee58ec 100644
--- a/railties/guides/source/routing.textile
+++ b/railties/guides/source/routing.textile
@@ -91,7 +91,7 @@ Creating a resourceful route will also expose a number of helpers to the control
* +photos_path+ returns +/photos+
* +new_photo_path+ returns +/photos/new+
-* +edit_photo_path+ returns +/photos/:id/edit+
+* +edit_photo_path(id)+ returns +/photos/:id/edit+ (for instance, +edit_photo_path(10)+ returns +/photos/10/edit+)
* +photo_path(id)+ returns +/photos/:id+ (for instance, +photo_path(10)+ returns +/photos/10+)
Each of these helpers has a corresponding +_url+ helper (such as +photos_url+) which returns the same path prefixed with the current host, port and path prefix.
diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb
index 3663910281..cca0891835 100644
--- a/railties/lib/rails.rb
+++ b/railties/lib/rails.rb
@@ -92,7 +92,7 @@ module Rails
end
def public_path
- application && application.paths.public.to_a.first
+ application && application.paths["public"].first
end
end
end
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index 075e3c5692..d13356ab4d 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -72,7 +72,7 @@ module Rails
end
def require_environment! #:nodoc:
- environment = paths.config.environment.to_a.first
+ environment = paths["config/environment"].existent.first
require environment if environment
end
@@ -128,10 +128,9 @@ module Rails
end
def initializers
- initializers = Bootstrap.initializers_for(self)
- initializers += super
- initializers += Finisher.initializers_for(self)
- initializers
+ Bootstrap.initializers_for(self) +
+ super +
+ Finisher.initializers_for(self)
end
def config
diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb
index e39b3bc705..213aa0768a 100644
--- a/railties/lib/rails/application/bootstrap.rb
+++ b/railties/lib/rails/application/bootstrap.rb
@@ -23,7 +23,7 @@ module Rails
# Initialize the logger early in the stack in case we need to log some deprecation.
initializer :initialize_logger do
Rails.logger ||= config.logger || begin
- path = config.paths.log.to_a.first
+ path = config.paths["log"].first
logger = ActiveSupport::BufferedLogger.new(path)
logger.level = ActiveSupport::BufferedLogger.const_get(config.log_level.to_s.upcase)
logger.auto_flushing = false if Rails.env.production?
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index f902c3ded2..3505388479 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -9,7 +9,7 @@ module Rails
:filter_parameters, :log_level, :logger,
:preload_frameworks, :reload_plugins,
:secret_token, :serve_static_assets, :session_options,
- :time_zone, :whiny_nils
+ :time_zone, :whiny_nils, :helpers_paths
def initialize(*)
super
@@ -17,6 +17,7 @@ module Rails
@allow_concurrency = false
@consider_all_requests_local = false
@filter_parameters = []
+ @helpers_paths = []
@dependency_loading = true
@serve_static_assets = true
@session_store = :cookie_store
@@ -60,13 +61,12 @@ module Rails
def paths
@paths ||= begin
paths = super
- paths.config.database "config/database.yml"
- paths.config.environment "config/environment.rb"
- paths.lib.templates "lib/templates"
- paths.log "log/#{Rails.env}.log"
- paths.tmp "tmp"
- paths.tmp.cache "tmp/cache"
-
+ paths.add "config/database", :with => "config/database.yml"
+ paths.add "config/environment", :with => "config/environment.rb"
+ paths.add "lib/templates"
+ paths.add "log", :with => "log/#{Rails.env}.log"
+ paths.add "tmp"
+ paths.add "tmp/cache"
paths
end
end
@@ -88,7 +88,7 @@ module Rails
# YAML::load.
def database_configuration
require 'erb'
- YAML::load(ERB.new(IO.read(paths.config.database.to_a.first)).result)
+ YAML::load(ERB.new(IO.read(paths["config/database"].first)).result)
end
def cache_store
diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb
index b95df467c7..e3342be7ee 100644
--- a/railties/lib/rails/application/finisher.rb
+++ b/railties/lib/rails/application/finisher.rb
@@ -4,7 +4,7 @@ module Rails
include Initializable
initializer :add_generator_templates do
- config.generators.templates.unshift(*paths.lib.templates.to_a)
+ config.generators.templates.unshift(*paths["lib/templates"].existent)
end
initializer :ensure_autoload_once_paths_as_subset do
diff --git a/railties/lib/rails/application/routes_reloader.rb b/railties/lib/rails/application/routes_reloader.rb
index 6da903c1ac..1d1f5e1b06 100644
--- a/railties/lib/rails/application/routes_reloader.rb
+++ b/railties/lib/rails/application/routes_reloader.rb
@@ -1,17 +1,15 @@
module Rails
class Application
class RoutesReloader < ::ActiveSupport::FileUpdateChecker
+ attr_reader :route_sets
+
def initialize
super([]) { reload! }
- end
-
- def blocks
- @blocks ||= {}
+ @route_sets = []
end
def reload!
clear!
- load_blocks
load_paths
finalize!
ensure
@@ -21,37 +19,27 @@ module Rails
protected
def clear!
- routers.each do |routes|
+ route_sets.each do |routes|
routes.disable_clear_and_finalize = true
routes.clear!
end
end
- def load_blocks
- blocks.each do |routes, block|
- routes.draw(&block) if block
- end
- end
-
def load_paths
paths.each { |path| load(path) }
end
def finalize!
- routers.each do |routes|
+ route_sets.each do |routes|
ActiveSupport.on_load(:action_controller) { routes.finalize! }
end
end
def revert
- routers.each do |routes|
+ route_sets.each do |routes|
routes.disable_clear_and_finalize = false
end
end
-
- def routers
- blocks.keys
- end
end
end
end
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index 3981e8dfd5..25ca8c4758 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -17,7 +17,7 @@ module Rails
# In Rails versions before to 3.0, your gems automatically behaved as Engine, 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 with how we spceify a Railtie):
+ # lib folder (similar to how we specify a Railtie):
#
# # lib/my_engine.rb
# module MyEngine
@@ -77,30 +77,30 @@ module Rails
# you need to do is:
#
# class MyEngine < Rails::Engine
- # paths.app.controllers = "lib/controllers"
+ # paths["app/controllers"] = "lib/controllers"
# end
#
# You can also have your controllers being loaded from both "app/controllers" and
# "lib/controllers":
#
# class MyEngine < Rails::Engine
- # paths.app.controllers << "lib/controllers"
+ # paths["app/controllers"] << "lib/controllers"
# end
#
# The available paths in an Engine are:
#
# class MyEngine < Rails::Engine
- # paths.app = "app"
- # paths.app.controllers = "app/controllers"
- # paths.app.helpers = "app/helpers"
- # paths.app.models = "app/models"
- # paths.app.views = "app/views"
- # paths.lib = "lib"
- # paths.lib.tasks = "lib/tasks"
- # paths.config = "config"
- # paths.config.initializers = "config/initializers"
- # paths.config.locales = "config/locales"
- # paths.config.routes = "config/routes.rb"
+ # paths["app"] #=> ["app"]
+ # paths["app/controllers"] #=> ["app/controllers"]
+ # paths["app/helpers"] #=> ["app/helpers"]
+ # paths["app/models"] #=> ["app/models"]
+ # paths["app/views"] #=> ["app/views"]
+ # paths["lib"] #=> ["lib"]
+ # paths["lib/tasks"] #=> ["lib/tasks"]
+ # paths["config"] #=> ["config"]
+ # paths["config/initializers"] #=> ["config/initializers"]
+ # paths["config/locales"] #=> ["config/locales"]
+ # paths["config/routes"] #=> ["config/routes.rb"]
# end
#
# Your Application class adds a couple more paths to this set. And as in your Application,
@@ -185,19 +185,18 @@ module Rails
# == 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 served.
+ # while you develop your application, but when you want to deploy it, assets from engine will not be
+ # served by default. You should choose one of the two following strategies:
#
- # You can fix it in one of two ways:
# * enable serving static files by setting config.serve_static_assets to true
- # * symlink engines' public directories in application's public directory by running
- # `rake railties:create_symlinks`
+ # * copy engine's public files to application's public folder with rake ENGINE_NAME:install:assets, for example
+ # rake my_engine:install:assets
#
# == Engine name
#
- # There are some places where engine's name is used.
+ # 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
- # * migrations: when you copy engine's migrations, they will be decorated with suffix based on engine_name, for example:
- # 2010010203121314_create_users.my_engine.rb
+ # * some of the rake tasks are based on engine name, e.g. my_engine:install:migrations, my_engine:install:assets
#
# 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:
@@ -210,15 +209,17 @@ module Rails
#
# == Namespaced Engine
#
- # Normally, when you create controllers, helpers and models inside engine, they are treated
- # as they would be created inside application. One of the cosequences of that is including
- # application's helpers and url_helpers inside controller. Sometimes, especially when your
- # engine provides its own routes, you don't want that. To isolate engine's stuff from application
- # you can use namespace method:
+ # 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.
+ #
+ # 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
+ # you to pass a module where all your controllers, helpers and models should be nested to:
#
# module MyEngine
# class Engine < Rails::Engine
- # namespace MyEngine
+ # isolate_namespace MyEngine
# end
# end
#
@@ -235,15 +236,21 @@ module Rails
# url_helpers from MyEngine::Engine.routes.
#
# The next thing that changes in isolated engine is routes behaviour. Normally, when you namespace
- # your controllers, you need to use scope or namespace method in routes. With isolated engine,
- # the namespace is applied by default, so you can ignore it in routes. Further more, you don't need
- # to use longer url helpers like "my_engine_articles_path". As the prefix is not set you can just use
- # articles_path as you would normally do.
+ # your controllers, you also need to do namespace all your routes. With 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 most of the places,
- # like url helpers or form fields.
+ # use the prefix "my_engine". In isolated engine, the prefix will be ommited in url helpers and
+ # form fields for convenience.
#
# polymorphic_url(MyEngine::Article.new) #=> "articles_path"
#
@@ -251,16 +258,15 @@ module Rails
# text_field :title #=> <input type="text" name="article[title]" id="article_title" />
# end
#
- #
- # Additionaly namespaced engine will set its name according to namespace, so in that case:
- # MyEngine::Engine.engine_name #=> "my_engine" and it will set MyEngine.table_name_prefix
- # to "my_engine_".
+ # Additionaly isolated engine will set its name according to namespace, so
+ # MyEngine::Engine.engine_name #=> "my_engine". It will also set MyEngine.table_name_prefix
+ # to "my_engine_", changing MyEngine::Article model to use my_engine_article table.
#
# == Using Engine's routes outside Engine
#
- # Since you can mount engine inside application's routes now, you do not have direct access to engine's
- # url_helpers inside application. When you mount Engine in application's routes special helper is
- # created to allow doing that. Consider such scenario:
+ # 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:
#
# # APP/config/routes.rb
# MyApplication::Application.routes.draw do
@@ -268,7 +274,7 @@ module Rails
# match "/foo" => "foo#index"
# end
#
- # Now, you can use my_engine helper:
+ # Now, you can use my_engine helper inside your application:
#
# class FooController < ApplicationController
# def index
@@ -276,24 +282,27 @@ module Rails
# end
# end
#
- # There is also 'app' helper that gives you access to application's routes inside Engine:
+ # There is also 'main_app' helper that gives you access to application's routes inside Engine:
#
# module MyEngine
# class BarController
- # app.foo_path #=> /foo
+ # def index
+ # main_app.foo_path #=> /foo
+ # end
# end
# end
#
- # Note that :as option takes engine_name as default, so most of the time you can ommit it.
+ # Note that the :as option given to mount takes the engine_name as default, so most of the time
+ # you can simply ommit it.
#
- # If you want to generate url to engine's route using polymorphic_url, you can also use that helpers.
- #
- # Let's say that you want to create a form pointing to one of the engine's routes. All you need to do
- # is passing helper as the first element in array with attributes for url:
+ # Finally, if you want to generate url to engine's route using polymorphic_url, 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])
#
- # This code will use my_engine.user_path(@user) to generate proper route.
+ # This code will use my_engine.user_path(@user) to generate the proper route.
#
# == Migrations & seed data
#
@@ -303,7 +312,11 @@ module Rails
# To use engine's migrations in application you can use rake task, which copies them to
# application's dir:
#
- # rake railties:copy_migrations
+ # 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
+ # 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.
@@ -315,7 +328,7 @@ module Rails
autoload :Configuration, "rails/engine/configuration"
class << self
- attr_accessor :called_from, :namespaced
+ attr_accessor :called_from, :isolated
alias :engine_name :railtie_name
def inherited(base)
@@ -350,12 +363,12 @@ module Rails
@endpoint
end
- def namespace(mod)
+ def isolate_namespace(mod)
engine_name(generate_railtie_name(mod))
name = engine_name
self.routes.default_scope = {:module => name}
- self.namespaced = true
+ self.isolated = true
unless mod.respond_to?(:_railtie)
_railtie = self
@@ -371,17 +384,17 @@ module Rails
end
end
- def namespaced?
- !!namespaced
+ def isolated?
+ !!isolated
end
end
delegate :middleware, :root, :paths, :to => :config
- delegate :engine_name, :namespaced?, :to => "self.class"
+ delegate :engine_name, :isolated?, :to => "self.class"
def load_tasks
super
- config.paths.lib.tasks.to_a.sort.each { |ext| load(ext) }
+ paths["lib/tasks"].existent.sort.each { |ext| load(ext) }
end
def eager_load!
@@ -419,9 +432,9 @@ module Rails
}
end
- def routes(&block)
+ def routes
@routes ||= ActionDispatch::Routing::RouteSet.new
- self.routes_draw_block = block if block_given?
+ @routes.append(&Proc.new) if block_given?
@routes
end
@@ -441,7 +454,7 @@ module Rails
#
# Blog::Engine.load_seed
def load_seed
- seed_file = config.paths.db.seeds.to_a.first
+ seed_file = paths["db/seeds"].existent.first
load(seed_file) if File.exist?(seed_file)
end
@@ -469,20 +482,22 @@ module Rails
end
initializer :add_routing_paths do |app|
- app.routes_reloader.blocks[routes] = routes_draw_block
- paths.config.routes.to_a.each do |route|
- app.routes_reloader.paths.unshift(route) if File.exists?(route)
+ paths = self.paths["config/routes"].existent
+
+ if routes? || paths.any?
+ app.routes_reloader.paths.unshift(*paths)
+ app.routes_reloader.route_sets << routes
end
end
# I18n load paths are a special case since the ones added
# later have higher priority.
initializer :add_locales do
- config.i18n.railties_load_path.concat(paths.config.locales.to_a)
+ config.i18n.railties_load_path.concat(paths["config/locales"].existent)
end
initializer :add_view_paths do
- views = paths.app.views.to_a
+ views = paths["app/views"].existent
unless views.empty?
ActiveSupport.on_load(:action_controller){ prepend_view_path(views) }
ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) }
@@ -490,28 +505,27 @@ module Rails
end
initializer :load_environment_config, :before => :load_environment_hook do
- environment = config.paths.config.environments.to_a.first
+ environment = paths["config/environments"].existent.first
require environment if environment
end
initializer :append_asset_paths do
- config.asset_path ||= "/#{engine_name}%s"
+ config.asset_path ||= "/#{railtie_name}%s"
- public_path = config.paths.public.to_a.first
+ public_path = paths["public"].first
if config.compiled_asset_path && File.exist?(public_path)
config.static_asset_paths[config.compiled_asset_path] = public_path
end
end
- initializer :prepend_helpers_path do
- unless namespaced?
- config.helpers_paths = [] unless config.respond_to?(:helpers_paths)
- config.helpers_paths = config.paths.app.helpers.to_a + config.helpers_paths
+ initializer :prepend_helpers_path do |app|
+ if !isolated? || (app == self)
+ app.config.helpers_paths.unshift(*paths["app/helpers"].existent)
end
end
initializer :load_config_initializers do
- paths.config.initializers.to_a.sort.each do |initializer|
+ config.paths["config/initializers"].existent.sort.each do |initializer|
load(initializer)
end
end
@@ -521,8 +535,38 @@ module Rails
# consistently executed after all the initializers above across all engines.
end
+ rake_tasks do
+ next if self.is_a?(Rails::Application)
+
+ namespace railtie_name do
+ desc "Shortcut for running both rake #{railtie_name}:install:migrations and #{railtie_name}:install:assets"
+ task :install do
+ Rake::Task["#{railtie_name}:install:migrations"].invoke
+ Rake::Task["#{railtie_name}:install:assets"].invoke
+ end
+
+ namespace :install do
+ # TODO Add assets copying to this list
+ # TODO Skip this if there is no paths["db/migrate"] for the engine
+ desc "Copy migrations from #{railtie_name} to application"
+ task :migrations do
+ ENV["FROM"] = railtie_name
+ Rake::Task["railties:install:migrations"].invoke
+ end
+
+ desc "Copy assets from #{railtie_name} to application"
+ task :assets do
+ ENV["FROM"] = railtie_name
+ Rake::Task["railties:install:assets"].invoke
+ end
+ end
+ end
+ end
+
protected
- attr_accessor :routes_draw_block
+ def routes?
+ defined?(@routes)
+ end
def find_root_with_flag(flag, default=nil)
root_path = self.class.called_from
diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb
index b69c0e1c53..7a07dcad7d 100644
--- a/railties/lib/rails/engine/configuration.rb
+++ b/railties/lib/rails/engine/configuration.rb
@@ -10,7 +10,6 @@ module Rails
def initialize(root=nil)
super()
@root = root
- @helpers_paths = []
end
# Returns the middleware stack for the engine.
@@ -39,27 +38,27 @@ module Rails
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"
- paths.lib "lib", :load_path => true
- paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
- 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.config.environments "config/environments", :glob => "#{Rails.env}.rb"
- paths.public "public"
- paths.public.javascripts "public/javascripts"
- paths.public.stylesheets "public/stylesheets"
- paths.vendor "vendor", :load_path => true
- paths.vendor.plugins "vendor/plugins"
- paths.db "db"
- paths.db.migrate "db/migrate"
- paths.db.seeds "db/seeds.rb"
+ paths.add "app", :eager_load => true, :glob => "*"
+ paths.add "app/controllers", :eager_load => true
+ paths.add "app/helpers", :eager_load => true
+ paths.add "app/models", :eager_load => true
+ paths.add "app/mailers", :eager_load => true
+ paths.add "app/views"
+ paths.add "lib", :load_path => true
+ paths.add "lib/tasks", :glob => "**/*.rake"
+ paths.add "config"
+ paths.add "config/environments", :glob => "#{Rails.env}.rb"
+ paths.add "config/initializers", :glob => "**/*.rb"
+ paths.add "config/locales", :glob => "*.{rb,yml}"
+ paths.add "config/routes", :with => "config/routes.rb"
+ paths.add "db"
+ paths.add "db/migrate"
+ paths.add "db/seeds", :with => "db/seeds.rb"
+ paths.add "public"
+ paths.add "public/javascripts"
+ paths.add "public/stylesheets"
+ paths.add "vendor", :load_path => true
+ paths.add "vendor/plugins"
paths
end
end
diff --git a/railties/lib/rails/engine/railties.rb b/railties/lib/rails/engine/railties.rb
index 389a7602c6..e91bdbf1e5 100644
--- a/railties/lib/rails/engine/railties.rb
+++ b/railties/lib/rails/engine/railties.rb
@@ -15,7 +15,7 @@ module Rails
def plugins
@plugins ||= begin
plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym }
- Plugin.all(plugin_names, @config.paths.vendor.plugins)
+ Plugin.all(plugin_names, @config.paths["vendor/plugins"].existent)
end
end
end
diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb
index 8f0d5ffff4..378c07cb0e 100644
--- a/railties/lib/rails/generators/actions.rb
+++ b/railties/lib/rails/generators/actions.rb
@@ -187,8 +187,8 @@ module Rails
# initializer("globals.rb") do
# data = ""
#
- # ['MY_WORK', 'ADMINS', 'BEST_COMPANY_EVAR'].each do
- # data << "#{const} = :entp"
+ # ['MY_WORK', 'ADMINS', 'BEST_COMPANY_EVAR'].each do |const|
+ # data << "#{const} = :entp\n"
# end
#
# data
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index 7907191c74..44f9fde0a6 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -108,12 +108,20 @@ module Rails
end
def javascripts
- unless options[:skip_prototype]
- directory "public/javascripts"
- else
- empty_directory_with_gitkeep "public/javascripts"
- create_file "public/javascripts/application.js"
+ empty_directory "public/javascripts"
+
+ unless options[:skip_javascript]
+ copy_file "public/javascripts/#{@options[:javascript]}.js"
+ copy_file "public/javascripts/#{@options[:javascript]}_ujs.js", "public/javascripts/rails.js"
+
+ if options[:prototype]
+ copy_file "public/javascripts/controls.js"
+ copy_file "public/javascripts/dragdrop.js"
+ copy_file "public/javascripts/effects.js"
+ end
end
+
+ copy_file "public/javascripts/application.js"
end
def script
@@ -152,6 +160,7 @@ module Rails
class AppGenerator < Base
DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
+ JAVASCRIPTS = %w( prototype jquery )
attr_accessor :rails_template
add_shebang_option!
@@ -161,6 +170,9 @@ module Rails
class_option :database, :type => :string, :aliases => "-d", :default => "sqlite3",
:desc => "Preconfigure for selected database (options: #{DATABASES.join('/')})"
+ class_option :javascript, :type => :string, :aliases => "-j", :default => "prototype",
+ :desc => "Preconfigure for selected javascript library (options: #{JAVASCRIPTS.join('/')})"
+
class_option :builder, :type => :string, :aliases => "-b",
:desc => "Path to an application builder (can be a filesystem path or URL)"
@@ -182,8 +194,8 @@ module Rails
class_option :skip_test_unit, :type => :boolean, :aliases => "-T", :default => false,
:desc => "Skip Test::Unit files"
- class_option :skip_prototype, :type => :boolean, :aliases => "-J", :default => false,
- :desc => "Skip Prototype files"
+ class_option :skip_javascript, :type => :boolean, :aliases => "-J", :default => false,
+ :desc => "Skip javascript files"
class_option :skip_git, :type => :boolean, :aliases => "-G", :default => false,
:desc => "Skip Git ignores and keeps"
@@ -205,6 +217,10 @@ module Rails
if !options[:skip_active_record] && !DATABASES.include?(options[:database])
raise Error, "Invalid value for --database option. Supported for preconfiguration are: #{DATABASES.join(", ")}."
end
+
+ if !options[:skip_javascript] && !JAVASCRIPTS.include?(options[:javascript])
+ raise Error, "Invalid value for --javascript option. Supported for preconfiguration are: #{JAVASCRIPTS.join(", ")}."
+ end
end
def create_root
@@ -269,7 +285,7 @@ module Rails
build(:stylesheets)
end
- def create_prototype_files
+ def create_javascript_files
build(:javascripts)
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb
index 7d63e99e05..00a23a7b89 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -40,8 +40,10 @@ module <%= app_const_base %>
# config.i18n.default_locale = :de
# JavaScript files you want as :defaults (application.js is always included).
-<% if options[:skip_prototype] -%>
+<% if options[:skip_javascript] -%>
config.action_view.javascript_expansions[:defaults] = %w()
+<% elsif options[:javascript] == 'jquery' -%>
+ config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
<% else -%>
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
<% end -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml
index fddf8b8144..b661a60389 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/oracle.yml
@@ -10,7 +10,7 @@
#
# By default prefetch_rows (OCI_ATTR_PREFETCH_ROWS) is set to 100. And
# until true bind variables are supported, cursor_sharing is set by default
-# to 'similar'. Both can be changed in the configation below; the defaults
+# to 'similar'. Both can be changed in the configuration below; the defaults
# are equivalent to specifying:
#
# prefetch_rows: 100
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
new file mode 100644
index 0000000000..109701084e
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
@@ -0,0 +1,6078 @@
+/*!
+ * jQuery JavaScript Library v1.4.1
+ * http://jquery.com/
+ *
+ * Copyright 2010, 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
+ * Released under the MIT, BSD, and GPL Licenses.
+ *
+ * Date: Mon Jan 25 19:43:33 2010 -0500
+ */
+(function( window, undefined ) {
+
+// 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 );
+ },
+
+ // Map over jQuery in case of overwrite
+ _jQuery = window.jQuery,
+
+ // Map over the $ in case of overwrite
+ _$ = window.$,
+
+ // Use the correct document accordingly with window argument (sandbox)
+ document = window.document,
+
+ // A central reference to the root jQuery(document)
+ rootjQuery,
+
+ // A simple way to check for HTML strings or ID strings
+ // (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/,
+
+ // Used for trimming whitespace
+ rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,
+
+ // Match a standalone tag
+ rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
+
+ // Keep a UserAgent string for use with jQuery.browser
+ userAgent = navigator.userAgent,
+
+ // 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 ready event handler
+ DOMContentLoaded,
+
+ // Save a reference to some core methods
+ toString = Object.prototype.toString,
+ hasOwnProperty = Object.prototype.hasOwnProperty,
+ push = Array.prototype.push,
+ slice = Array.prototype.slice,
+ indexOf = Array.prototype.indexOf;
+
+jQuery.fn = jQuery.prototype = {
+ init: function( selector, context ) {
+ var match, elem, ret, doc;
+
+ // Handle $(""), $(null), or $(undefined)
+ if ( !selector ) {
+ return this;
+ }
+
+ // Handle $(DOMElement)
+ if ( selector.nodeType ) {
+ this.context = this[0] = selector;
+ this.length = 1;
+ return this;
+ }
+
+ // Handle HTML strings
+ if ( typeof selector === "string" ) {
+ // Are we dealing with HTML string or an ID?
+ match = quickExpr.exec( selector );
+
+ // Verify a match, and that no context was specified for #id
+ if ( match && (match[1] || !context) ) {
+
+ // HANDLE: $(html) -> $(array)
+ if ( match[1] ) {
+ doc = (context ? context.ownerDocument || context : document);
+
+ // If a single string is passed in and it's a single tag
+ // just do a createElement and skip the rest
+ ret = rsingleTag.exec( selector );
+
+ if ( ret ) {
+ if ( jQuery.isPlainObject( context ) ) {
+ selector = [ document.createElement( ret[1] ) ];
+ jQuery.fn.attr.call( selector, context, true );
+
+ } else {
+ selector = [ doc.createElement( ret[1] ) ];
+ }
+
+ } else {
+ ret = buildFragment( [ match[1] ], [ doc ] );
+ selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
+ }
+
+ // HANDLE: $("#id")
+ } else {
+ elem = document.getElementById( match[2] );
+
+ if ( elem ) {
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id !== match[2] ) {
+ return rootjQuery.find( selector );
+ }
+
+ // Otherwise, we inject the element directly into the jQuery object
+ this.length = 1;
+ this[0] = elem;
+ }
+
+ this.context = document;
+ this.selector = selector;
+ return this;
+ }
+
+ // HANDLE: $("TAG")
+ } else if ( !context && /^\w+$/.test( selector ) ) {
+ this.selector = selector;
+ this.context = document;
+ selector = document.getElementsByTagName( selector );
+
+ // HANDLE: $(expr, $(...))
+ } else if ( !context || context.jquery ) {
+ return (context || rootjQuery).find( selector );
+
+ // HANDLE: $(expr, context)
+ // (which is just equivalent to: $(context).find(expr)
+ } else {
+ return jQuery( context ).find( selector );
+ }
+
+ // HANDLE: $(function)
+ // Shortcut for document ready
+ } else if ( jQuery.isFunction( selector ) ) {
+ return rootjQuery.ready( selector );
+ }
+
+ if (selector.selector !== undefined) {
+ this.selector = selector.selector;
+ this.context = selector.context;
+ }
+
+ return jQuery.isArray( selector ) ?
+ this.setArray( selector ) :
+ jQuery.makeArray( selector, this );
+ },
+
+ // Start with an empty selector
+ selector: "",
+
+ // The current version of jQuery being used
+ jquery: "1.4.1",
+
+ // The default length of a jQuery object is 0
+ length: 0,
+
+ // The number of elements contained in the matched element set
+ size: function() {
+ return this.length;
+ },
+
+ toArray: function() {
+ return slice.call( this, 0 );
+ },
+
+ // Get the Nth element in the matched element set OR
+ // Get the whole matched element set as a clean array
+ get: function( num ) {
+ return num == null ?
+
+ // Return a 'clean' array
+ this.toArray() :
+
+ // Return just the object
+ ( num < 0 ? this.slice(num)[ 0 ] : 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( elems || null );
+
+ // Add the old object onto the stack (as a reference)
+ ret.prevObject = this;
+
+ ret.context = this.context;
+
+ if ( name === "find" ) {
+ ret.selector = this.selector + (this.selector ? " " : "") + selector;
+ } else if ( name ) {
+ ret.selector = this.selector + "." + name + "(" + selector + ")";
+ }
+
+ // Return the newly-formed element set
+ return ret;
+ },
+
+ // Force the current matched set of elements to become
+ // the specified array of elements (destroying the stack in the process)
+ // You should use pushStack() in order to do this, but maintain the stack
+ setArray: function( elems ) {
+ // Resetting the length to 0, then using the native Array push
+ // is a super-fast way to populate an object with array-like properties
+ this.length = 0;
+ push.apply( this, elems );
+
+ return this;
+ },
+
+ // Execute a callback for every element in the matched set.
+ // (You can seed the arguments with an array of args, but this is
+ // only used internally.)
+ 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 );
+ }
+
+ return this;
+ },
+
+ eq: function( i ) {
+ return i === -1 ?
+ this.slice( i ) :
+ this.slice( i, +i + 1 );
+ },
+
+ first: function() {
+ return this.eq( 0 );
+ },
+
+ last: function() {
+ return this.eq( -1 );
+ },
+
+ slice: function() {
+ return this.pushStack( slice.apply( this, arguments ),
+ "slice", slice.call(arguments).join(",") );
+ },
+
+ map: function( callback ) {
+ return this.pushStack( jQuery.map(this, function( elem, i ) {
+ return callback.call( elem, i, elem );
+ }));
+ },
+
+ end: function() {
+ return this.prevObject || jQuery(null);
+ },
+
+ // For internal use only.
+ // Behaves like an Array's method, not like a jQuery method.
+ push: push,
+ sort: [].sort,
+ splice: [].splice
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+jQuery.extend = jQuery.fn.extend = function() {
+ // copy reference to target object
+ var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
+
+ // Handle a deep copy situation
+ if ( typeof target === "boolean" ) {
+ deep = target;
+ target = arguments[1] || {};
+ // skip the boolean and the target
+ i = 2;
+ }
+
+ // Handle case when target is a string or something (possible in deep copy)
+ if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
+ target = {};
+ }
+
+ // extend jQuery itself if only one argument is passed
+ if ( length === i ) {
+ target = this;
+ --i;
+ }
+
+ for ( ; i < length; i++ ) {
+ // Only deal with non-null/undefined values
+ if ( (options = arguments[ i ]) != null ) {
+ // Extend the base object
+ for ( name in options ) {
+ src = target[ name ];
+ copy = options[ name ];
+
+ // Prevent never-ending loop
+ if ( target === copy ) {
+ continue;
+ }
+
+ // Recurse if we're merging object literal values or arrays
+ if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) {
+ var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src
+ : jQuery.isArray(copy) ? [] : {};
+
+ // Never move original objects, clone them
+ target[ name ] = jQuery.extend( deep, clone, copy );
+
+ // Don't bring in undefined values
+ } else if ( copy !== undefined ) {
+ target[ name ] = copy;
+ }
+ }
+ }
+ }
+
+ // Return the modified object
+ return target;
+};
+
+jQuery.extend({
+ noConflict: function( deep ) {
+ window.$ = _$;
+
+ if ( deep ) {
+ window.jQuery = _jQuery;
+ }
+
+ return jQuery;
+ },
+
+ // Is the DOM ready to be used? Set to true once it occurs.
+ isReady: false,
+
+ // Handle when the DOM is ready
+ ready: function() {
+ // Make sure that the DOM is not already loaded
+ if ( !jQuery.isReady ) {
+ // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+ if ( !document.body ) {
+ return setTimeout( jQuery.ready, 13 );
+ }
+
+ // Remember that the DOM is ready
+ jQuery.isReady = true;
+
+ // If there are functions bound, to execute
+ if ( readyList ) {
+ // Execute all of them
+ var fn, i = 0;
+ while ( (fn = readyList[ i++ ]) ) {
+ fn.call( document, jQuery );
+ }
+
+ // Reset the list of functions
+ readyList = null;
+ }
+
+ // Trigger any bound ready events
+ if ( jQuery.fn.triggerHandler ) {
+ jQuery( document ).triggerHandler( "ready" );
+ }
+ }
+ },
+
+ bindReady: function() {
+ if ( readyBound ) {
+ return;
+ }
+
+ readyBound = true;
+
+ // Catch cases where $(document).ready() is called after the
+ // browser event has already occurred.
+ if ( document.readyState === "complete" ) {
+ return jQuery.ready();
+ }
+
+ // Mozilla, Opera and webkit nightlies currently support this event
+ 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 );
+
+ // If IE event model is used
+ } else if ( document.attachEvent ) {
+ // 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 );
+
+ // If IE and not a frame
+ // continually check to see if the document is ready
+ var toplevel = false;
+
+ try {
+ toplevel = window.frameElement == null;
+ } catch(e) {}
+
+ if ( document.documentElement.doScroll && toplevel ) {
+ doScrollCheck();
+ }
+ }
+ },
+
+ // See test/unit/core.js for details concerning isFunction.
+ // Since version 1.3, DOM methods and functions like alert
+ // aren't supported. They return false on IE (#2968).
+ isFunction: function( obj ) {
+ return toString.call(obj) === "[object Function]";
+ },
+
+ isArray: function( obj ) {
+ return toString.call(obj) === "[object Array]";
+ },
+
+ isPlainObject: function( obj ) {
+ // Must be an Object.
+ // Because of IE, we also have to check the presence of the constructor property.
+ // Make sure that DOM nodes and window objects don't pass through, as well
+ if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) {
+ return false;
+ }
+
+ // Not own constructor property must be Object
+ if ( obj.constructor
+ && !hasOwnProperty.call(obj, "constructor")
+ && !hasOwnProperty.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 || hasOwnProperty.call( obj, key );
+ },
+
+ isEmptyObject: function( obj ) {
+ for ( var name in obj ) {
+ return false;
+ }
+ return true;
+ },
+
+ error: function( msg ) {
+ throw msg;
+ },
+
+ parseJSON: function( data ) {
+ if ( typeof data !== "string" || !data ) {
+ return null;
+ }
+
+ // Make sure the incoming data is actual JSON
+ // Logic borrowed from http://json.org/json2.js
+ if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
+
+ // Try to use the native JSON parser first
+ return window.JSON && window.JSON.parse ?
+ window.JSON.parse( data ) :
+ (new Function("return " + data))();
+
+ } else {
+ jQuery.error( "Invalid JSON: " + data );
+ }
+ },
+
+ noop: function() {},
+
+ // Evalulates a script in a global context
+ globalEval: function( data ) {
+ if ( data && rnotwhite.test(data) ) {
+ // Inspired by code by Andrea Giammarchi
+ // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
+ var head = document.getElementsByTagName("head")[0] || document.documentElement,
+ script = document.createElement("script");
+
+ script.type = "text/javascript";
+
+ if ( jQuery.support.scriptEval ) {
+ script.appendChild( document.createTextNode( data ) );
+ } else {
+ script.text = data;
+ }
+
+ // Use insertBefore instead of appendChild to circumvent an IE6 bug.
+ // This arises when a base node is used (#2709).
+ head.insertBefore( script, head.firstChild );
+ head.removeChild( script );
+ }
+ },
+
+ nodeName: function( elem, name ) {
+ return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
+ },
+
+ // args is for internal usage only
+ each: function( object, callback, args ) {
+ var name, i = 0,
+ length = object.length,
+ isObj = length === undefined || jQuery.isFunction(object);
+
+ if ( args ) {
+ if ( isObj ) {
+ for ( name in object ) {
+ if ( callback.apply( object[ name ], args ) === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( ; i < length; ) {
+ if ( callback.apply( object[ i++ ], args ) === false ) {
+ break;
+ }
+ }
+ }
+
+ // A special, fast, case for the most common use of each
+ } else {
+ if ( isObj ) {
+ for ( name in object ) {
+ if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( var value = object[0];
+ i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
+ }
+ }
+
+ return object;
+ },
+
+ trim: function( text ) {
+ return (text || "").replace( rtrim, "" );
+ },
+
+ // results is for internal usage only
+ makeArray: function( array, results ) {
+ var ret = results || [];
+
+ if ( array != null ) {
+ // The window, strings (and functions) also have 'length'
+ // The extra typeof function check is to prevent crashes
+ // in Safari 2 (See: #3039)
+ if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) {
+ push.call( ret, array );
+ } else {
+ jQuery.merge( ret, array );
+ }
+ }
+
+ return ret;
+ },
+
+ inArray: function( elem, array ) {
+ if ( array.indexOf ) {
+ return array.indexOf( elem );
+ }
+
+ for ( var i = 0, length = array.length; i < length; i++ ) {
+ if ( array[ i ] === elem ) {
+ return i;
+ }
+ }
+
+ return -1;
+ },
+
+ merge: function( first, second ) {
+ var i = first.length, j = 0;
+
+ if ( typeof second.length === "number" ) {
+ for ( var l = second.length; j < l; j++ ) {
+ first[ i++ ] = second[ j ];
+ }
+ } else {
+ while ( second[j] !== undefined ) {
+ first[ i++ ] = second[ j++ ];
+ }
+ }
+
+ first.length = i;
+
+ return first;
+ },
+
+ grep: function( elems, callback, inv ) {
+ var ret = [];
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( var i = 0, length = elems.length; i < length; i++ ) {
+ if ( !inv !== !callback( elems[ i ], i ) ) {
+ ret.push( elems[ i ] );
+ }
+ }
+
+ return ret;
+ },
+
+ // arg is for internal usage only
+ map: function( elems, callback, arg ) {
+ var ret = [], value;
+
+ // Go through the array, translating each of the items to their
+ // new value (or values).
+ for ( var i = 0, length = elems.length; i < length; i++ ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret[ ret.length ] = value;
+ }
+ }
+
+ return ret.concat.apply( [], ret );
+ },
+
+ // A global GUID counter for objects
+ guid: 1,
+
+ proxy: function( fn, proxy, thisObject ) {
+ if ( arguments.length === 2 ) {
+ if ( typeof proxy === "string" ) {
+ thisObject = fn;
+ fn = thisObject[ proxy ];
+ proxy = undefined;
+
+ } else if ( proxy && !jQuery.isFunction( proxy ) ) {
+ thisObject = proxy;
+ proxy = undefined;
+ }
+ }
+
+ if ( !proxy && fn ) {
+ proxy = function() {
+ return fn.apply( thisObject || this, arguments );
+ };
+ }
+
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ if ( fn ) {
+ proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
+ }
+
+ // So proxy can be declared as an argument
+ return proxy;
+ },
+
+ // Use of jQuery.browser is frowned upon.
+ // More details: http://docs.jquery.com/Utilities/jQuery.browser
+ uaMatch: function( ua ) {
+ ua = ua.toLowerCase();
+
+ var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
+ /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) ||
+ /(msie) ([\w.]+)/.exec( ua ) ||
+ !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) ||
+ [];
+
+ return { browser: match[1] || "", version: match[2] || "0" };
+ },
+
+ browser: {}
+});
+
+browserMatch = jQuery.uaMatch( userAgent );
+if ( browserMatch.browser ) {
+ jQuery.browser[ browserMatch.browser ] = true;
+ jQuery.browser.version = browserMatch.version;
+}
+
+// Deprecated, use jQuery.browser.webkit instead
+if ( jQuery.browser.webkit ) {
+ jQuery.browser.safari = true;
+}
+
+if ( indexOf ) {
+ jQuery.inArray = function( elem, array ) {
+ return indexOf.call( array, elem );
+ };
+}
+
+// All jQuery objects should point back to these
+rootjQuery = jQuery(document);
+
+// Cleanup functions for the document ready method
+if ( document.addEventListener ) {
+ DOMContentLoaded = function() {
+ document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
+ jQuery.ready();
+ };
+
+} else if ( document.attachEvent ) {
+ DOMContentLoaded = function() {
+ // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+ if ( document.readyState === "complete" ) {
+ document.detachEvent( "onreadystatechange", DOMContentLoaded );
+ jQuery.ready();
+ }
+ };
+}
+
+// The DOM ready check for Internet Explorer
+function doScrollCheck() {
+ if ( jQuery.isReady ) {
+ return;
+ }
+
+ try {
+ // If IE is used, use the trick by Diego Perini
+ // http://javascript.nwbox.com/IEContentLoaded/
+ document.documentElement.doScroll("left");
+ } catch( error ) {
+ setTimeout( doScrollCheck, 1 );
+ return;
+ }
+
+ // and execute any waiting functions
+ jQuery.ready();
+}
+
+function evalScript( i, elem ) {
+ if ( elem.src ) {
+ jQuery.ajax({
+ url: elem.src,
+ async: false,
+ dataType: "script"
+ });
+ } else {
+ jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
+ }
+
+ if ( elem.parentNode ) {
+ elem.parentNode.removeChild( elem );
+ }
+}
+
+// Mutifunctional method to get and set values to a collection
+// The value/s can be optionally by executed if its a function
+function access( elems, key, value, exec, fn, pass ) {
+ var length = elems.length;
+
+ // Setting many attributes
+ if ( typeof key === "object" ) {
+ for ( var k in key ) {
+ access( elems, k, key[k], exec, fn, value );
+ }
+ 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 ) : null;
+}
+
+function now() {
+ return (new Date).getTime();
+}
+(function() {
+
+ jQuery.support = {};
+
+ var root = document.documentElement,
+ script = document.createElement("script"),
+ div = document.createElement("div"),
+ id = "script" + now();
+
+ div.style.display = "none";
+ div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
+
+ var all = div.getElementsByTagName("*"),
+ a = div.getElementsByTagName("a")[0];
+
+ // Can't get basic test support
+ if ( !all || !all.length || !a ) {
+ return;
+ }
+
+ jQuery.support = {
+ // IE strips leading whitespace when .innerHTML is used
+ leadingWhitespace: div.firstChild.nodeType === 3,
+
+ // Make sure that tbody elements aren't automatically inserted
+ // IE will insert them into empty tables
+ tbody: !div.getElementsByTagName("tbody").length,
+
+ // Make sure that link elements get serialized correctly by innerHTML
+ // This requires a wrapper element in IE
+ htmlSerialize: !!div.getElementsByTagName("link").length,
+
+ // Get the style information from getAttribute
+ // (IE uses .cssText insted)
+ style: /red/.test( a.getAttribute("style") ),
+
+ // Make sure that URLs aren't manipulated
+ // (IE normalizes it by default)
+ hrefNormalized: a.getAttribute("href") === "/a",
+
+ // Make sure that element opacity exists
+ // (IE uses filter instead)
+ // Use a regex to work around a WebKit issue. See #5145
+ opacity: /^0.55$/.test( a.style.opacity ),
+
+ // Verify style float existence
+ // (IE uses styleFloat instead of cssFloat)
+ cssFloat: !!a.style.cssFloat,
+
+ // Make sure that if no value is specified for a checkbox
+ // that it defaults to "on".
+ // (WebKit defaults to "" instead)
+ checkOn: div.getElementsByTagName("input")[0].value === "on",
+
+ // Make sure that a selected-by-default option has a working selected property.
+ // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
+ optSelected: document.createElement("select").appendChild( document.createElement("option") ).selected,
+
+ // Will be defined later
+ checkClone: false,
+ scriptEval: false,
+ noCloneEvent: true,
+ boxModel: null
+ };
+
+ script.type = "text/javascript";
+ try {
+ script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
+ } catch(e) {}
+
+ 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 ];
+ }
+
+ root.removeChild( script );
+
+ if ( div.attachEvent && div.fireEvent ) {
+ div.attachEvent("onclick", function click() {
+ // Cloning a node shouldn't copy over any
+ // bound event handlers (IE does this)
+ jQuery.support.noCloneEvent = false;
+ div.detachEvent("onclick", click);
+ });
+ div.cloneNode(true).fireEvent("onclick");
+ }
+
+ div = document.createElement("div");
+ div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>";
+
+ var fragment = document.createDocumentFragment();
+ fragment.appendChild( div.firstChild );
+
+ // WebKit doesn't clone checked state correctly in fragments
+ jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
+
+ // 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";
+
+ document.body.appendChild( div );
+ jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
+ document.body.removeChild( div ).style.display = 'none';
+ div = null;
+ });
+
+ // Technique from Juriy Zaytsev
+ // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
+ var eventSupported = function( eventName ) {
+ var el = document.createElement("div");
+ eventName = "on" + eventName;
+
+ var isSupported = (eventName in el);
+ if ( !isSupported ) {
+ el.setAttribute(eventName, "return;");
+ isSupported = typeof el[eventName] === "function";
+ }
+ el = null;
+
+ return isSupported;
+ };
+
+ jQuery.support.submitBubbles = eventSupported("submit");
+ jQuery.support.changeBubbles = eventSupported("change");
+
+ // release memory in IE
+ root = script = div = all = a = null;
+})();
+
+jQuery.props = {
+ "for": "htmlFor",
+ "class": "className",
+ readonly: "readOnly",
+ maxlength: "maxLength",
+ cellspacing: "cellSpacing",
+ rowspan: "rowSpan",
+ colspan: "colSpan",
+ tabindex: "tabIndex",
+ usemap: "useMap",
+ frameborder: "frameBorder"
+};
+var expando = "jQuery" + now(), uuid = 0, windowData = {};
+var emptyObject = {};
+
+jQuery.extend({
+ cache: {},
+
+ expando:expando,
+
+ // The following elements throw uncatchable exceptions if you
+ // attempt to add expando properties to them.
+ noData: {
+ "embed": true,
+ "object": true,
+ "applet": true
+ },
+
+ data: function( elem, name, data ) {
+ if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
+ return;
+ }
+
+ elem = elem == window ?
+ windowData :
+ elem;
+
+ var id = elem[ expando ], cache = jQuery.cache, thisCache;
+
+ // Handle the case where there's no name immediately
+ if ( !name && !id ) {
+ return null;
+ }
+
+ // Compute a unique ID for the element
+ if ( !id ) {
+ id = ++uuid;
+ }
+
+ // Avoid generating a new cache unless none exists and we
+ // want to manipulate it.
+ if ( typeof name === "object" ) {
+ elem[ expando ] = id;
+ thisCache = cache[ id ] = jQuery.extend(true, {}, name);
+ } else if ( cache[ id ] ) {
+ thisCache = cache[ id ];
+ } else if ( typeof data === "undefined" ) {
+ thisCache = emptyObject;
+ } else {
+ thisCache = cache[ id ] = {};
+ }
+
+ // Prevent overriding the named cache with undefined values
+ if ( data !== undefined ) {
+ elem[ expando ] = id;
+ thisCache[ name ] = data;
+ }
+
+ return typeof name === "string" ? thisCache[ name ] : thisCache;
+ },
+
+ removeData: function( elem, name ) {
+ if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
+ return;
+ }
+
+ elem = elem == window ?
+ windowData :
+ elem;
+
+ var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ];
+
+ // If we want to remove a specific section of the element's data
+ if ( name ) {
+ if ( thisCache ) {
+ // Remove the section of cache data
+ delete thisCache[ name ];
+
+ // If we've removed all the data, remove the element's cache
+ if ( jQuery.isEmptyObject(thisCache) ) {
+ jQuery.removeData( elem );
+ }
+ }
+
+ // Otherwise, we want to remove all of the element's data
+ } else {
+ // Clean up the element expando
+ try {
+ delete elem[ expando ];
+ } catch( e ) {
+ // IE has trouble directly removing the expando
+ // but it's ok with using removeAttribute
+ if ( elem.removeAttribute ) {
+ elem.removeAttribute( expando );
+ }
+ }
+
+ // Completely remove the data cache
+ delete cache[ id ];
+ }
+ }
+});
+
+jQuery.fn.extend({
+ data: function( key, value ) {
+ if ( typeof key === "undefined" && this.length ) {
+ return jQuery.data( this[0] );
+
+ } else if ( typeof key === "object" ) {
+ return this.each(function() {
+ jQuery.data( this, key );
+ });
+ }
+
+ var parts = key.split(".");
+ parts[1] = parts[1] ? "." + parts[1] : "";
+
+ if ( value === undefined ) {
+ var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
+
+ if ( data === undefined && this.length ) {
+ data = jQuery.data( this[0], key );
+ }
+ return data === undefined && parts[1] ?
+ this.data( parts[0] ) :
+ data;
+ } else {
+ return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() {
+ jQuery.data( this, key, value );
+ });
+ }
+ },
+
+ removeData: function( key ) {
+ return this.each(function() {
+ jQuery.removeData( this, key );
+ });
+ }
+});
+jQuery.extend({
+ queue: function( elem, type, data ) {
+ if ( !elem ) {
+ return;
+ }
+
+ type = (type || "fx") + "queue";
+ var q = jQuery.data( elem, type );
+
+ // Speed up dequeue by getting out quickly if this is just a lookup
+ if ( !data ) {
+ return q || [];
+ }
+
+ if ( !q || jQuery.isArray(data) ) {
+ q = jQuery.data( elem, type, jQuery.makeArray(data) );
+
+ } else {
+ q.push( data );
+ }
+
+ return q;
+ },
+
+ dequeue: function( elem, type ) {
+ type = type || "fx";
+
+ var queue = jQuery.queue( elem, type ), fn = queue.shift();
+
+ // If the fx queue is dequeued, always remove the progress sentinel
+ if ( fn === "inprogress" ) {
+ fn = queue.shift();
+ }
+
+ if ( fn ) {
+ // Add a progress sentinel to prevent the fx queue from being
+ // automatically dequeued
+ if ( type === "fx" ) {
+ queue.unshift("inprogress");
+ }
+
+ fn.call(elem, function() {
+ jQuery.dequeue(elem, type);
+ });
+ }
+ }
+});
+
+jQuery.fn.extend({
+ queue: function( type, data ) {
+ if ( typeof type !== "string" ) {
+ data = type;
+ type = "fx";
+ }
+
+ if ( data === undefined ) {
+ return jQuery.queue( this[0], type );
+ }
+ return this.each(function( i, elem ) {
+ var queue = jQuery.queue( this, type, data );
+
+ if ( type === "fx" && queue[0] !== "inprogress" ) {
+ jQuery.dequeue( this, type );
+ }
+ });
+ },
+ dequeue: function( type ) {
+ return this.each(function() {
+ jQuery.dequeue( this, type );
+ });
+ },
+
+ // Based off of the plugin by Clint Helfers, with permission.
+ // http://blindsignals.com/index.php/2009/07/jquery-delay/
+ delay: function( time, type ) {
+ time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
+ type = type || "fx";
+
+ return this.queue( type, function() {
+ var elem = this;
+ setTimeout(function() {
+ jQuery.dequeue( elem, type );
+ }, time );
+ });
+ },
+
+ clearQueue: function( type ) {
+ return this.queue( type || "fx", [] );
+ }
+});
+var rclass = /[\n\t]/g,
+ rspace = /\s+/,
+ rreturn = /\r/g,
+ rspecialurl = /href|src|style/,
+ rtype = /(button|input)/i,
+ rfocusable = /(button|input|object|select|textarea)/i,
+ rclickable = /^(a|area)$/i,
+ rradiocheck = /radio|checkbox/;
+
+jQuery.fn.extend({
+ attr: function( name, value ) {
+ return access( this, name, value, true, jQuery.attr );
+ },
+
+ removeAttr: function( name, fn ) {
+ return this.each(function(){
+ jQuery.attr( this, name, "" );
+ if ( this.nodeType === 1 ) {
+ this.removeAttribute( name );
+ }
+ });
+ },
+
+ addClass: function( value ) {
+ if ( jQuery.isFunction(value) ) {
+ return this.each(function(i) {
+ var self = jQuery(this);
+ self.addClass( value.call(this, i, self.attr("class")) );
+ });
+ }
+
+ if ( value && typeof value === "string" ) {
+ var classNames = (value || "").split( rspace );
+
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ var elem = this[i];
+
+ if ( elem.nodeType === 1 ) {
+ if ( !elem.className ) {
+ elem.className = value;
+
+ } else {
+ var className = " " + elem.className + " ";
+ for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
+ if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
+ elem.className += " " + classNames[c];
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ removeClass: function( value ) {
+ if ( jQuery.isFunction(value) ) {
+ return this.each(function(i) {
+ var self = jQuery(this);
+ self.removeClass( value.call(this, i, self.attr("class")) );
+ });
+ }
+
+ if ( (value && typeof value === "string") || value === undefined ) {
+ var classNames = (value || "").split(rspace);
+
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ var elem = this[i];
+
+ if ( elem.nodeType === 1 && elem.className ) {
+ if ( value ) {
+ var className = (" " + elem.className + " ").replace(rclass, " ");
+ for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
+ className = className.replace(" " + classNames[c] + " ", " ");
+ }
+ elem.className = className.substring(1, className.length - 1);
+
+ } else {
+ elem.className = "";
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ toggleClass: function( value, stateVal ) {
+ var type = typeof value, isBool = typeof stateVal === "boolean";
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function(i) {
+ var self = jQuery(this);
+ self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
+ });
+ }
+
+ return this.each(function() {
+ if ( type === "string" ) {
+ // toggle individual class names
+ var className, i = 0, self = jQuery(this),
+ state = stateVal,
+ classNames = value.split( rspace );
+
+ while ( (className = classNames[ i++ ]) ) {
+ // check each className given, space seperated list
+ state = isBool ? state : !self.hasClass( className );
+ self[ state ? "addClass" : "removeClass" ]( className );
+ }
+
+ } else if ( type === "undefined" || type === "boolean" ) {
+ if ( this.className ) {
+ // store className if set
+ jQuery.data( this, "__className__", this.className );
+ }
+
+ // toggle whole className
+ this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || "";
+ }
+ });
+ },
+
+ hasClass: function( selector ) {
+ var className = " " + selector + " ";
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+
+ val: function( value ) {
+ if ( value === undefined ) {
+ var elem = this[0];
+
+ if ( elem ) {
+ if ( jQuery.nodeName( elem, "option" ) ) {
+ return (elem.attributes.value || {}).specified ? elem.value : elem.text;
+ }
+
+ // We need to handle select boxes special
+ if ( jQuery.nodeName( elem, "select" ) ) {
+ var index = elem.selectedIndex,
+ values = [],
+ options = elem.options,
+ one = elem.type === "select-one";
+
+ // Nothing was selected
+ if ( index < 0 ) {
+ return null;
+ }
+
+ // Loop through all the selected options
+ for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
+ var option = options[ i ];
+
+ if ( option.selected ) {
+ // Get the specifc value for the option
+ value = jQuery(option).val();
+
+ // We don't need an array for one selects
+ if ( one ) {
+ return value;
+ }
+
+ // Multi-Selects return an array
+ values.push( value );
+ }
+ }
+
+ return values;
+ }
+
+ // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
+ 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, "");
+
+ }
+
+ return undefined;
+ }
+
+ var isFunction = jQuery.isFunction(value);
+
+ return this.each(function(i) {
+ var self = jQuery(this), val = value;
+
+ if ( this.nodeType !== 1 ) {
+ return;
+ }
+
+ if ( isFunction ) {
+ val = value.call(this, i, self.val());
+ }
+
+ // Typecast each time if the value is a Function and the appended
+ // value is therefore different each time.
+ if ( typeof val === "number" ) {
+ val += "";
+ }
+
+ if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) {
+ this.checked = jQuery.inArray( self.val(), val ) >= 0;
+
+ } else if ( jQuery.nodeName( this, "select" ) ) {
+ var values = jQuery.makeArray(val);
+
+ jQuery( "option", this ).each(function() {
+ this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
+ });
+
+ if ( !values.length ) {
+ this.selectedIndex = -1;
+ }
+
+ } else {
+ this.value = val;
+ }
+ });
+ }
+});
+
+jQuery.extend({
+ attrFn: {
+ val: true,
+ css: true,
+ html: true,
+ text: true,
+ data: true,
+ width: true,
+ 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 ) {
+ return undefined;
+ }
+
+ if ( pass && name in jQuery.attrFn ) {
+ return jQuery(elem)[name](value);
+ }
+
+ var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ),
+ // Whether we are setting (or getting)
+ set = value !== undefined;
+
+ // Try to normalize/fix the name
+ name = notxml && jQuery.props[ name ] || 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;
+ }
+ }
+ }
+
+ // If applicable, access the attribute via the DOM 0 way
+ if ( name in elem && 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" );
+ }
+
+ elem[ name ] = value;
+ }
+
+ // 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;
+ }
+
+ // 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" );
+
+ return attributeNode && attributeNode.specified ?
+ attributeNode.value :
+ rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
+ 0 :
+ undefined;
+ }
+
+ return elem[ name ];
+ }
+
+ if ( !jQuery.support.style && notxml && name === "style" ) {
+ if ( set ) {
+ elem.style.cssText = "" + value;
+ }
+
+ return elem.style.cssText;
+ }
+
+ 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 );
+
+ // Non-existent attributes return null, we normalize to undefined
+ return attr === null ? undefined : attr;
+ }
+
+ // elem is actually elem.style ... set the style
+ // Using attr for specific style information is now deprecated. Use style insead.
+ return jQuery.style( elem, name, value );
+ }
+});
+var fcleanup = function( nm ) {
+ return nm.replace(/[^\w\s\.\|`]/g, function( ch ) {
+ return "\\" + ch;
+ });
+};
+
+/*
+ * A number of helper functions used for managing events.
+ * Many of the ideas behind this code originated from
+ * Dean Edwards' addEvent library.
+ */
+jQuery.event = {
+
+ // Bind an event to an element
+ // Original by Dean Edwards
+ add: function( elem, types, handler, data ) {
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ // For whatever reason, IE has trouble passing the window object
+ // around, causing it to be cloned in the process
+ if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) {
+ elem = window;
+ }
+
+ // Make sure that the function being executed has a unique ID
+ if ( !handler.guid ) {
+ handler.guid = jQuery.guid++;
+ }
+
+ // if data is passed, bind to handler
+ if ( data !== undefined ) {
+ // Create temporary function pointer to original handler
+ var fn = handler;
+
+ // Create unique handler function, wrapped around original handler
+ handler = jQuery.proxy( fn );
+
+ // Store data in unique handler
+ handler.data = data;
+ }
+
+ // Init the element's event structure
+ var events = jQuery.data( elem, "events" ) || jQuery.data( elem, "events", {} ),
+ handle = jQuery.data( elem, "handle" ), eventHandle;
+
+ if ( !handle ) {
+ eventHandle = function() {
+ // Handle the second event of a trigger and when
+ // an event is called after a page has unloaded
+ return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
+ jQuery.event.handle.apply( eventHandle.elem, arguments ) :
+ undefined;
+ };
+
+ handle = jQuery.data( elem, "handle", eventHandle );
+ }
+
+ // If no handle is found then we must be trying to bind to one of the
+ // banned noData elements
+ if ( !handle ) {
+ return;
+ }
+
+ // Add elem as a property of the handle function
+ // This is to prevent a memory leak with non-native
+ // event in IE.
+ handle.elem = elem;
+
+ // Handle multiple events separated by a space
+ // jQuery(...).bind("mouseover mouseout", fn);
+ types = types.split( /\s+/ );
+
+ var type, i = 0;
+
+ while ( (type = types[ i++ ]) ) {
+ // Namespaced event handlers
+ var namespaces = type.split(".");
+ type = namespaces.shift();
+
+ if ( i > 1 ) {
+ handler = jQuery.proxy( handler );
+
+ if ( data !== undefined ) {
+ handler.data = data;
+ }
+ }
+
+ handler.type = namespaces.slice(0).sort().join(".");
+
+ // Get the current list of functions bound to this event
+ var handlers = events[ type ],
+ special = this.special[ type ] || {};
+
+ // Init the event handler queue
+ if ( !handlers ) {
+ handlers = events[ type ] = {};
+
+ // Check for a special event handler
+ // Only use addEventListener/attachEvent if the special
+ // events handler returns false
+ if ( !special.setup || special.setup.call( elem, data, namespaces, handler) === false ) {
+ // Bind the global event handler to the element
+ if ( elem.addEventListener ) {
+ elem.addEventListener( type, handle, false );
+ } else if ( elem.attachEvent ) {
+ elem.attachEvent( "on" + type, handle );
+ }
+ }
+ }
+
+ if ( special.add ) {
+ var modifiedHandler = special.add.call( elem, handler, data, namespaces, handlers );
+ if ( modifiedHandler && jQuery.isFunction( modifiedHandler ) ) {
+ modifiedHandler.guid = modifiedHandler.guid || handler.guid;
+ modifiedHandler.data = modifiedHandler.data || handler.data;
+ modifiedHandler.type = modifiedHandler.type || handler.type;
+ handler = modifiedHandler;
+ }
+ }
+
+ // Add the function to the element's handler list
+ handlers[ handler.guid ] = handler;
+
+ // Keep track of which events have been used, for global triggering
+ this.global[ type ] = true;
+ }
+
+ // Nullify elem to prevent memory leaks in IE
+ elem = null;
+ },
+
+ global: {},
+
+ // Detach an event or set of events from an element
+ remove: function( elem, types, handler ) {
+ // don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ var events = jQuery.data( elem, "events" ), ret, type, fn;
+
+ if ( events ) {
+ // Unbind all events for the element
+ if ( types === undefined || (typeof types === "string" && types.charAt(0) === ".") ) {
+ for ( type in events ) {
+ this.remove( elem, type + (types || "") );
+ }
+ } else {
+ // types is actually an event object here
+ if ( types.type ) {
+ handler = types.handler;
+ types = types.type;
+ }
+
+ // Handle multiple events separated by a space
+ // jQuery(...).unbind("mouseover mouseout", fn);
+ types = types.split(/\s+/);
+ var i = 0;
+ while ( (type = types[ i++ ]) ) {
+ // Namespaced event handlers
+ var namespaces = type.split(".");
+ type = namespaces.shift();
+ var all = !namespaces.length,
+ cleaned = jQuery.map( namespaces.slice(0).sort(), fcleanup ),
+ namespace = new RegExp("(^|\\.)" + cleaned.join("\\.(?:.*\\.)?") + "(\\.|$)"),
+ special = this.special[ type ] || {};
+
+ if ( events[ type ] ) {
+ // remove the given handler for the given type
+ if ( handler ) {
+ fn = events[ type ][ handler.guid ];
+ delete events[ type ][ handler.guid ];
+
+ // remove all handlers for the given type
+ } else {
+ for ( var handle in events[ type ] ) {
+ // Handle the removal of namespaced events
+ if ( all || namespace.test( events[ type ][ handle ].type ) ) {
+ delete events[ type ][ handle ];
+ }
+ }
+ }
+
+ if ( special.remove ) {
+ special.remove.call( elem, namespaces, fn);
+ }
+
+ // remove generic event handler if no more handlers exist
+ for ( ret in events[ type ] ) {
+ break;
+ }
+ if ( !ret ) {
+ if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
+ if ( elem.removeEventListener ) {
+ elem.removeEventListener( type, jQuery.data( elem, "handle" ), false );
+ } else if ( elem.detachEvent ) {
+ elem.detachEvent( "on" + type, jQuery.data( elem, "handle" ) );
+ }
+ }
+ ret = null;
+ delete events[ type ];
+ }
+ }
+ }
+ }
+
+ // Remove the expando if it's no longer used
+ for ( ret in events ) {
+ break;
+ }
+ if ( !ret ) {
+ var handle = jQuery.data( elem, "handle" );
+ if ( handle ) {
+ handle.elem = null;
+ }
+ jQuery.removeData( elem, "events" );
+ jQuery.removeData( elem, "handle" );
+ }
+ }
+ },
+
+ // bubbling is internal
+ trigger: function( event, data, elem /*, bubbling */ ) {
+ // Event object or event type
+ var type = event.type || event,
+ bubbling = arguments[3];
+
+ if ( !bubbling ) {
+ event = typeof event === "object" ?
+ // jQuery.Event object
+ event[expando] ? event :
+ // Object literal
+ jQuery.extend( jQuery.Event(type), event ) :
+ // Just the event type (string)
+ jQuery.Event(type);
+
+ if ( type.indexOf("!") >= 0 ) {
+ event.type = type = type.slice(0, -1);
+ event.exclusive = true;
+ }
+
+ // Handle a global trigger
+ if ( !elem ) {
+ // Don't bubble custom events when global (to avoid too much overhead)
+ event.stopPropagation();
+
+ // Only trigger if we've ever bound an event for it
+ if ( this.global[ type ] ) {
+ jQuery.each( jQuery.cache, function() {
+ if ( this.events && this.events[type] ) {
+ jQuery.event.trigger( event, data, this.handle.elem );
+ }
+ });
+ }
+ }
+
+ // Handle triggering a single element
+
+ // don't do events on text and comment nodes
+ if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return undefined;
+ }
+
+ // Clean up in case it is reused
+ event.result = undefined;
+ event.target = elem;
+
+ // Clone the incoming data, if any
+ data = jQuery.makeArray( data );
+ data.unshift( event );
+ }
+
+ event.currentTarget = elem;
+
+ // Trigger the event, it is assumed that "handle" is a function
+ var handle = jQuery.data( elem, "handle" );
+ if ( handle ) {
+ handle.apply( elem, data );
+ }
+
+ var parent = elem.parentNode || elem.ownerDocument;
+
+ // Trigger an inline bound script
+ try {
+ if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) {
+ if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) {
+ event.result = false;
+ }
+ }
+
+ // prevent IE from throwing an error for some elements with some event types, see #3533
+ } catch (e) {}
+
+ if ( !event.isPropagationStopped() && parent ) {
+ jQuery.event.trigger( event, data, parent, true );
+
+ } else if ( !event.isDefaultPrevented() ) {
+ var target = event.target, old,
+ isClick = jQuery.nodeName(target, "a") && type === "click";
+
+ if ( !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) {
+ try {
+ if ( target[ type ] ) {
+ // Make sure that we don't accidentally re-trigger the onFOO events
+ old = target[ "on" + type ];
+
+ if ( old ) {
+ target[ "on" + type ] = null;
+ }
+
+ this.triggered = true;
+ target[ type ]();
+ }
+
+ // prevent IE from throwing an error for some elements with some event types, see #3533
+ } catch (e) {}
+
+ if ( old ) {
+ target[ "on" + type ] = old;
+ }
+
+ this.triggered = false;
+ }
+ }
+ },
+
+ handle: function( event ) {
+ // returned undefined or false
+ var all, handlers;
+
+ event = arguments[0] = jQuery.event.fix( event || window.event );
+ event.currentTarget = this;
+
+ // Namespaced event handlers
+ var namespaces = event.type.split(".");
+ event.type = namespaces.shift();
+
+ // Cache this now, all = true means, any handler
+ all = !namespaces.length && !event.exclusive;
+
+ var namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)");
+
+ handlers = ( jQuery.data(this, "events") || {} )[ event.type ];
+
+ for ( var j in handlers ) {
+ var handler = handlers[ j ];
+
+ // Filter the functions by class
+ if ( all || namespace.test(handler.type) ) {
+ // Pass in a reference to the handler function itself
+ // So that we can later remove it
+ event.handler = handler;
+ event.data = handler.data;
+
+ var ret = handler.apply( this, arguments );
+
+ if ( ret !== undefined ) {
+ event.result = ret;
+ if ( ret === false ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }
+
+ if ( event.isImmediatePropagationStopped() ) {
+ break;
+ }
+
+ }
+ }
+
+ return event.result;
+ },
+
+ props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
+
+ fix: function( event ) {
+ if ( event[ expando ] ) {
+ return event;
+ }
+
+ // store a copy of the original event object
+ // and "clone" to set read-only properties
+ var originalEvent = event;
+ event = jQuery.Event( originalEvent );
+
+ for ( var i = this.props.length, prop; i; ) {
+ prop = this.props[ --i ];
+ event[ prop ] = originalEvent[ prop ];
+ }
+
+ // Fix target property, if necessary
+ if ( !event.target ) {
+ event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
+ }
+
+ // check if target is a textnode (safari)
+ if ( event.target.nodeType === 3 ) {
+ event.target = event.target.parentNode;
+ }
+
+ // Add relatedTarget, if necessary
+ if ( !event.relatedTarget && event.fromElement ) {
+ event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
+ }
+
+ // Calculate pageX/Y if missing and clientX/Y available
+ if ( event.pageX == null && event.clientX != null ) {
+ var doc = document.documentElement, body = document.body;
+ event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
+ event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
+ }
+
+ // Add which for key events
+ if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) {
+ event.which = event.charCode || event.keyCode;
+ }
+
+ // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
+ if ( !event.metaKey && event.ctrlKey ) {
+ event.metaKey = event.ctrlKey;
+ }
+
+ // Add which for click: 1 === left; 2 === middle; 3 === right
+ // Note: button is not normalized, so don't use it
+ if ( !event.which && event.button !== undefined ) {
+ event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
+ }
+
+ return event;
+ },
+
+ // Deprecated, use jQuery.guid instead
+ guid: 1E8,
+
+ // Deprecated, use jQuery.proxy instead
+ proxy: jQuery.proxy,
+
+ special: {
+ ready: {
+ // Make sure the ready event is setup
+ setup: jQuery.bindReady,
+ teardown: jQuery.noop
+ },
+
+ live: {
+ add: function( proxy, data, namespaces, live ) {
+ jQuery.extend( proxy, data || {} );
+
+ proxy.guid += data.selector + data.live;
+ data.liveProxy = proxy;
+
+ jQuery.event.add( this, data.live, liveHandler, data );
+
+ },
+
+ remove: function( namespaces ) {
+ if ( namespaces.length ) {
+ var remove = 0, name = new RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
+
+ jQuery.each( (jQuery.data(this, "events").live || {}), function() {
+ if ( name.test(this.type) ) {
+ remove++;
+ }
+ });
+
+ if ( remove < 1 ) {
+ jQuery.event.remove( this, namespaces[0], liveHandler );
+ }
+ }
+ },
+ special: {}
+ },
+ beforeunload: {
+ setup: function( data, namespaces, fn ) {
+ // We only want to do this special case on windows
+ if ( this.setInterval ) {
+ this.onbeforeunload = fn;
+ }
+
+ return false;
+ },
+ teardown: function( namespaces, fn ) {
+ if ( this.onbeforeunload === fn ) {
+ this.onbeforeunload = null;
+ }
+ }
+ }
+ }
+};
+
+jQuery.Event = function( src ) {
+ // Allow instantiation without the 'new' keyword
+ if ( !this.preventDefault ) {
+ return new jQuery.Event( src );
+ }
+
+ // Event object
+ if ( src && src.type ) {
+ this.originalEvent = src;
+ this.type = src.type;
+ // Event type
+ } else {
+ this.type = src;
+ }
+
+ // timeStamp is buggy for some events on Firefox(#3843)
+ // So we won't rely on the native value
+ this.timeStamp = now();
+
+ // Mark it as fixed
+ this[ expando ] = true;
+};
+
+function returnFalse() {
+ return false;
+}
+function returnTrue() {
+ return true;
+}
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+ preventDefault: function() {
+ this.isDefaultPrevented = returnTrue;
+
+ var e = this.originalEvent;
+ if ( !e ) {
+ return;
+ }
+
+ // if preventDefault exists run it on the original event
+ if ( e.preventDefault ) {
+ e.preventDefault();
+ }
+ // otherwise set the returnValue property of the original event to false (IE)
+ e.returnValue = false;
+ },
+ stopPropagation: function() {
+ this.isPropagationStopped = returnTrue;
+
+ var e = this.originalEvent;
+ if ( !e ) {
+ return;
+ }
+ // if stopPropagation exists run it on the original event
+ if ( e.stopPropagation ) {
+ e.stopPropagation();
+ }
+ // otherwise set the cancelBubble property of the original event to true (IE)
+ e.cancelBubble = true;
+ },
+ stopImmediatePropagation: function() {
+ this.isImmediatePropagationStopped = returnTrue;
+ this.stopPropagation();
+ },
+ isDefaultPrevented: returnFalse,
+ isPropagationStopped: returnFalse,
+ isImmediatePropagationStopped: returnFalse
+};
+
+// Checks if an event happened on an element within another element
+// Used in jQuery.event.special.mouseenter and mouseleave handlers
+var withinElement = function( event ) {
+ // Check if mouse(over|out) are still within the same parent element
+ var parent = event.relatedTarget;
+
+ // Traverse up the tree
+ while ( parent && parent !== this ) {
+ // Firefox sometimes assigns relatedTarget a XUL element
+ // which we cannot access the parentNode property of
+ try {
+ parent = parent.parentNode;
+
+ // assuming we've left the element since we most likely mousedover a xul element
+ } catch(e) {
+ break;
+ }
+ }
+
+ if ( parent !== this ) {
+ // set the correct event type
+ event.type = event.data;
+
+ // handle event if we actually just moused on to a non sub-element
+ jQuery.event.handle.apply( this, arguments );
+ }
+
+},
+
+// In case of event delegation, we only need to rename the event.type,
+// liveHandler will take care of the rest.
+delegate = function( event ) {
+ event.type = event.data;
+ jQuery.event.handle.apply( this, arguments );
+};
+
+// Create mouseenter and mouseleave events
+jQuery.each({
+ mouseenter: "mouseover",
+ mouseleave: "mouseout"
+}, function( orig, fix ) {
+ jQuery.event.special[ orig ] = {
+ setup: function( data ) {
+ jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
+ },
+ teardown: function( data ) {
+ jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
+ }
+ };
+});
+
+// submit delegation
+if ( !jQuery.support.submitBubbles ) {
+
+jQuery.event.special.submit = {
+ setup: function( data, namespaces, fn ) {
+ if ( this.nodeName.toLowerCase() !== "form" ) {
+ jQuery.event.add(this, "click.specialSubmit." + fn.guid, function( e ) {
+ var elem = e.target, type = elem.type;
+
+ if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
+ return trigger( "submit", this, arguments );
+ }
+ });
+
+ jQuery.event.add(this, "keypress.specialSubmit." + fn.guid, function( e ) {
+ var elem = e.target, type = elem.type;
+
+ if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
+ return trigger( "submit", this, arguments );
+ }
+ });
+
+ } else {
+ return false;
+ }
+ },
+
+ remove: function( namespaces, fn ) {
+ jQuery.event.remove( this, "click.specialSubmit" + (fn ? "."+fn.guid : "") );
+ jQuery.event.remove( this, "keypress.specialSubmit" + (fn ? "."+fn.guid : "") );
+ }
+};
+
+}
+
+// change delegation, happens here so we have bind.
+if ( !jQuery.support.changeBubbles ) {
+
+var formElems = /textarea|input|select/i;
+
+function getVal( elem ) {
+ var type = elem.type, val = elem.value;
+
+ if ( type === "radio" || type === "checkbox" ) {
+ val = elem.checked;
+
+ } else if ( type === "select-multiple" ) {
+ val = elem.selectedIndex > -1 ?
+ jQuery.map( elem.options, function( elem ) {
+ return elem.selected;
+ }).join("-") :
+ "";
+
+ } else if ( elem.nodeName.toLowerCase() === "select" ) {
+ val = elem.selectedIndex;
+ }
+
+ return val;
+}
+
+function testChange( e ) {
+ var elem = e.target, data, val;
+
+ if ( !formElems.test( elem.nodeName ) || elem.readOnly ) {
+ return;
+ }
+
+ 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 );
+ }
+
+ if ( data === undefined || val === data ) {
+ return;
+ }
+
+ if ( data != null || val ) {
+ e.type = "change";
+ return jQuery.event.trigger( e, arguments[1], elem );
+ }
+}
+
+jQuery.event.special.change = {
+ filters: {
+ focusout: testChange,
+
+ click: function( e ) {
+ var elem = e.target, type = elem.type;
+
+ if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) {
+ return testChange.call( this, e );
+ }
+ },
+
+ // Change has to be called before submit
+ // Keydown will be called before keypress, which is used in submit-event delegation
+ keydown: function( e ) {
+ var elem = e.target, type = elem.type;
+
+ if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
+ (e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
+ type === "select-multiple" ) {
+ return testChange.call( this, e );
+ }
+ },
+
+ // Beforeactivate happens also before the previous element is blurred
+ // with this event you can't trigger a change event, but you can store
+ // information/focus[in] is not needed anymore
+ beforeactivate: function( e ) {
+ var elem = e.target;
+
+ if ( elem.nodeName.toLowerCase() === "input" && elem.type === "radio" ) {
+ jQuery.data( elem, "_change_data", getVal(elem) );
+ }
+ }
+ },
+ setup: function( data, namespaces, fn ) {
+ for ( var type in changeFilters ) {
+ jQuery.event.add( this, type + ".specialChange." + fn.guid, changeFilters[type] );
+ }
+
+ return formElems.test( this.nodeName );
+ },
+ remove: function( namespaces, fn ) {
+ for ( var type in changeFilters ) {
+ jQuery.event.remove( this, type + ".specialChange" + (fn ? "."+fn.guid : ""), changeFilters[type] );
+ }
+
+ return formElems.test( this.nodeName );
+ }
+};
+
+var changeFilters = jQuery.event.special.change.filters;
+
+}
+
+function trigger( type, elem, args ) {
+ args[0].type = type;
+ return jQuery.event.handle.apply( elem, args );
+}
+
+// Create "bubbling" focus and blur events
+if ( document.addEventListener ) {
+ jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+ jQuery.event.special[ fix ] = {
+ setup: function() {
+ this.addEventListener( orig, handler, true );
+ },
+ teardown: function() {
+ this.removeEventListener( orig, handler, true );
+ }
+ };
+
+ function handler( e ) {
+ e = jQuery.event.fix( e );
+ e.type = fix;
+ return jQuery.event.handle.call( this, e );
+ }
+ });
+}
+
+jQuery.each(["bind", "one"], function( i, name ) {
+ jQuery.fn[ name ] = function( type, data, fn ) {
+ // Handle object literals
+ if ( typeof type === "object" ) {
+ for ( var key in type ) {
+ this[ name ](key, data, type[key], fn);
+ }
+ return this;
+ }
+
+ if ( jQuery.isFunction( data ) ) {
+ fn = data;
+ data = undefined;
+ }
+
+ var handler = name === "one" ? jQuery.proxy( fn, function( event ) {
+ jQuery( this ).unbind( event, handler );
+ return fn.apply( this, arguments );
+ }) : fn;
+
+ return type === "unload" && name !== "one" ?
+ this.one( type, data, fn ) :
+ this.each(function() {
+ jQuery.event.add( this, type, handler, data );
+ });
+ };
+});
+
+jQuery.fn.extend({
+ unbind: function( type, fn ) {
+ // Handle object literals
+ if ( typeof type === "object" && !type.preventDefault ) {
+ for ( var key in type ) {
+ this.unbind(key, type[key]);
+ }
+ return this;
+ }
+
+ return this.each(function() {
+ jQuery.event.remove( this, type, fn );
+ });
+ },
+ trigger: function( type, data ) {
+ return this.each(function() {
+ jQuery.event.trigger( type, data, this );
+ });
+ },
+
+ triggerHandler: function( type, data ) {
+ if ( this[0] ) {
+ var event = jQuery.Event( type );
+ event.preventDefault();
+ event.stopPropagation();
+ jQuery.event.trigger( event, data, this[0] );
+ return event.result;
+ }
+ },
+
+ toggle: function( fn ) {
+ // Save reference to arguments for access in closure
+ var args = arguments, i = 1;
+
+ // link all the functions, so any of them can unbind this click handler
+ while ( i < args.length ) {
+ jQuery.proxy( fn, args[ i++ ] );
+ }
+
+ 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 );
+
+ // Make sure that clicks stop
+ event.preventDefault();
+
+ // and execute the function
+ return args[ lastToggle ].apply( this, arguments ) || false;
+ }));
+ },
+
+ hover: function( fnOver, fnOut ) {
+ return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
+ }
+});
+
+jQuery.each(["live", "die"], function( i, name ) {
+ jQuery.fn[ name ] = function( types, data, fn ) {
+ var type, i = 0;
+
+ if ( jQuery.isFunction( data ) ) {
+ fn = data;
+ data = undefined;
+ }
+
+ types = (types || "").split( /\s+/ );
+
+ while ( (type = types[ i++ ]) != null ) {
+ type = type === "focus" ? "focusin" : // focus --> focusin
+ type === "blur" ? "focusout" : // blur --> focusout
+ type === "hover" ? types.push("mouseleave") && "mouseenter" : // hover support
+ type;
+
+ if ( name === "live" ) {
+ // bind live handler
+ jQuery( this.context ).bind( liveConvert( type, this.selector ), {
+ data: data, selector: this.selector, live: type
+ }, fn );
+
+ } else {
+ // unbind live handler
+ jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null );
+ }
+ }
+
+ return this;
+ }
+});
+
+function liveHandler( event ) {
+ var stop, elems = [], selectors = [], args = arguments,
+ related, match, fn, elem, j, i, l, data,
+ live = jQuery.extend({}, jQuery.data( this, "events" ).live);
+
+ // Make sure we avoid non-left-click bubbling in Firefox (#3861)
+ if ( event.button && event.type === "click" ) {
+ return;
+ }
+
+ for ( j in live ) {
+ fn = live[j];
+ if ( fn.live === event.type ||
+ fn.altLive && jQuery.inArray(event.type, fn.altLive) > -1 ) {
+
+ data = fn.data;
+ if ( !(data.beforeFilter && data.beforeFilter[event.type] &&
+ !data.beforeFilter[event.type](event)) ) {
+ selectors.push( fn.selector );
+ }
+ } else {
+ delete live[j];
+ }
+ }
+
+ match = jQuery( event.target ).closest( selectors, event.currentTarget );
+
+ for ( i = 0, l = match.length; i < l; i++ ) {
+ for ( j in live ) {
+ fn = live[j];
+ elem = match[i].elem;
+ related = null;
+
+ if ( match[i].selector === fn.selector ) {
+ // Those two events require additional checking
+ if ( fn.live === "mouseenter" || fn.live === "mouseleave" ) {
+ related = jQuery( event.relatedTarget ).closest( fn.selector )[0];
+ }
+
+ if ( !related || related !== elem ) {
+ elems.push({ elem: elem, fn: fn });
+ }
+ }
+ }
+ }
+
+ for ( i = 0, l = elems.length; i < l; i++ ) {
+ match = elems[i];
+ event.currentTarget = match.elem;
+ event.data = match.fn.data;
+ if ( match.fn.apply( match.elem, args ) === false ) {
+ stop = false;
+ break;
+ }
+ }
+
+ return stop;
+}
+
+function liveConvert( type, selector ) {
+ return "live." + (type ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&");
+}
+
+jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
+ "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
+ "change select submit keydown keypress keyup error").split(" "), function( i, name ) {
+
+ // Handle event binding
+ jQuery.fn[ name ] = function( fn ) {
+ return fn ? this.bind( name, fn ) : this.trigger( name );
+ };
+
+ if ( jQuery.attrFn ) {
+ jQuery.attrFn[ name ] = true;
+ }
+});
+
+// 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 ) {
+ window.attachEvent("onunload", 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
+ * Released under the MIT, BSD, and GPL Licenses.
+ * More information: http://sizzlejs.com/
+ */
+(function(){
+
+var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
+ done = 0,
+ toString = Object.prototype.toString,
+ hasDuplicate = false,
+ baseHasDuplicate = true;
+
+// Here we check if the JavaScript engine is using some sort of
+// optimization where it does not always call our comparision
+// function. If that is the case, discard the hasDuplicate value.
+// Thus far that includes Google Chrome.
+[0, 0].sort(function(){
+ baseHasDuplicate = false;
+ return 0;
+});
+
+var Sizzle = function(selector, context, results, seed) {
+ results = results || [];
+ var origContext = context = context || document;
+
+ if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
+ return [];
+ }
+
+ if ( !selector || typeof selector !== "string" ) {
+ return results;
+ }
+
+ var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context),
+ soFar = selector;
+
+ // Reset the position of the chunker regexp (start from head)
+ while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) {
+ soFar = m[3];
+
+ parts.push( m[1] );
+
+ if ( m[2] ) {
+ extra = m[3];
+ break;
+ }
+ }
+
+ if ( parts.length > 1 && origPOS.exec( selector ) ) {
+ if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
+ set = posProcess( parts[0] + parts[1], context );
+ } else {
+ set = Expr.relative[ parts[0] ] ?
+ [ context ] :
+ Sizzle( parts.shift(), context );
+
+ while ( parts.length ) {
+ selector = parts.shift();
+
+ if ( Expr.relative[ selector ] ) {
+ selector += parts.shift();
+ }
+
+ set = posProcess( selector, set );
+ }
+ }
+ } else {
+ // Take a shortcut and set the context if the root selector is an ID
+ // (but not if it'll be faster if the inner selector is an ID)
+ if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
+ Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
+ var ret = Sizzle.find( parts.shift(), context, contextXML );
+ context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
+ }
+
+ if ( context ) {
+ var ret = seed ?
+ { expr: parts.pop(), set: makeArray(seed) } :
+ Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
+ set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;
+
+ if ( parts.length > 0 ) {
+ checkSet = makeArray(set);
+ } else {
+ prune = false;
+ }
+
+ while ( parts.length ) {
+ var cur = parts.pop(), pop = cur;
+
+ if ( !Expr.relative[ cur ] ) {
+ cur = "";
+ } else {
+ pop = parts.pop();
+ }
+
+ if ( pop == null ) {
+ pop = context;
+ }
+
+ Expr.relative[ cur ]( checkSet, pop, contextXML );
+ }
+ } else {
+ checkSet = parts = [];
+ }
+ }
+
+ if ( !checkSet ) {
+ checkSet = set;
+ }
+
+ if ( !checkSet ) {
+ Sizzle.error( cur || selector );
+ }
+
+ if ( toString.call(checkSet) === "[object Array]" ) {
+ if ( !prune ) {
+ results.push.apply( results, checkSet );
+ } else if ( context && context.nodeType === 1 ) {
+ for ( var i = 0; checkSet[i] != null; i++ ) {
+ if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
+ results.push( set[i] );
+ }
+ }
+ } else {
+ for ( var i = 0; checkSet[i] != null; i++ ) {
+ if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
+ results.push( set[i] );
+ }
+ }
+ }
+ } else {
+ makeArray( checkSet, results );
+ }
+
+ if ( extra ) {
+ Sizzle( extra, origContext, results, seed );
+ Sizzle.uniqueSort( results );
+ }
+
+ return results;
+};
+
+Sizzle.uniqueSort = function(results){
+ if ( sortOrder ) {
+ hasDuplicate = baseHasDuplicate;
+ results.sort(sortOrder);
+
+ if ( hasDuplicate ) {
+ for ( var i = 1; i < results.length; i++ ) {
+ if ( results[i] === results[i-1] ) {
+ results.splice(i--, 1);
+ }
+ }
+ }
+ }
+
+ return results;
+};
+
+Sizzle.matches = function(expr, set){
+ return Sizzle(expr, null, null, set);
+};
+
+Sizzle.find = function(expr, context, isXML){
+ var set, match;
+
+ if ( !expr ) {
+ return [];
+ }
+
+ for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
+ var type = Expr.order[i], match;
+
+ if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
+ var left = match[1];
+ match.splice(1,1);
+
+ if ( left.substr( left.length - 1 ) !== "\\" ) {
+ match[1] = (match[1] || "").replace(/\\/g, "");
+ set = Expr.find[ type ]( match, context, isXML );
+ if ( set != null ) {
+ expr = expr.replace( Expr.match[ type ], "" );
+ break;
+ }
+ }
+ }
+ }
+
+ if ( !set ) {
+ set = context.getElementsByTagName("*");
+ }
+
+ return {set: set, expr: expr};
+};
+
+Sizzle.filter = function(expr, set, inplace, not){
+ var old = expr, result = [], curLoop = set, match, anyFound,
+ isXMLFilter = set && set[0] && isXML(set[0]);
+
+ while ( expr && set.length ) {
+ for ( var type in Expr.filter ) {
+ if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
+ var filter = Expr.filter[ type ], found, item, left = match[1];
+ anyFound = false;
+
+ match.splice(1,1);
+
+ if ( left.substr( left.length - 1 ) === "\\" ) {
+ continue;
+ }
+
+ if ( curLoop === result ) {
+ result = [];
+ }
+
+ if ( Expr.preFilter[ type ] ) {
+ match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
+
+ if ( !match ) {
+ anyFound = found = true;
+ } else if ( match === true ) {
+ continue;
+ }
+ }
+
+ if ( match ) {
+ for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
+ if ( item ) {
+ found = filter( item, match, i, curLoop );
+ var pass = not ^ !!found;
+
+ if ( inplace && found != null ) {
+ if ( pass ) {
+ anyFound = true;
+ } else {
+ curLoop[i] = false;
+ }
+ } else if ( pass ) {
+ result.push( item );
+ anyFound = true;
+ }
+ }
+ }
+ }
+
+ if ( found !== undefined ) {
+ if ( !inplace ) {
+ curLoop = result;
+ }
+
+ expr = expr.replace( Expr.match[ type ], "" );
+
+ if ( !anyFound ) {
+ return [];
+ }
+
+ break;
+ }
+ }
+ }
+
+ // Improper expression
+ if ( expr === old ) {
+ if ( anyFound == null ) {
+ Sizzle.error( expr );
+ } else {
+ break;
+ }
+ }
+
+ old = expr;
+ }
+
+ return curLoop;
+};
+
+Sizzle.error = function( msg ) {
+ throw "Syntax error, unrecognized expression: " + msg;
+};
+
+var Expr = Sizzle.selectors = {
+ order: [ "ID", "NAME", "TAG" ],
+ match: {
+ ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
+ CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
+ NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,
+ ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
+ TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,
+ CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
+ POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
+ PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
+ },
+ leftMatch: {},
+ attrMap: {
+ "class": "className",
+ "for": "htmlFor"
+ },
+ attrHandle: {
+ href: function(elem){
+ return elem.getAttribute("href");
+ }
+ },
+ relative: {
+ "+": function(checkSet, part){
+ var isPartStr = typeof part === "string",
+ isTag = isPartStr && !/\W/.test(part),
+ isPartStrNotTag = isPartStr && !isTag;
+
+ if ( isTag ) {
+ part = part.toLowerCase();
+ }
+
+ for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
+ if ( (elem = checkSet[i]) ) {
+ while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
+
+ checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
+ elem || false :
+ elem === part;
+ }
+ }
+
+ if ( isPartStrNotTag ) {
+ Sizzle.filter( part, checkSet, true );
+ }
+ },
+ ">": function(checkSet, part){
+ var isPartStr = typeof part === "string";
+
+ if ( isPartStr && !/\W/.test(part) ) {
+ part = part.toLowerCase();
+
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+ if ( elem ) {
+ var parent = elem.parentNode;
+ checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
+ }
+ }
+ } else {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+ if ( elem ) {
+ checkSet[i] = isPartStr ?
+ elem.parentNode :
+ elem.parentNode === part;
+ }
+ }
+
+ if ( isPartStr ) {
+ Sizzle.filter( part, checkSet, true );
+ }
+ }
+ },
+ "": function(checkSet, part, isXML){
+ var doneName = done++, checkFn = dirCheck;
+
+ if ( typeof part === "string" && !/\W/.test(part) ) {
+ var nodeCheck = part = part.toLowerCase();
+ checkFn = dirNodeCheck;
+ }
+
+ checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
+ },
+ "~": function(checkSet, part, isXML){
+ var doneName = done++, checkFn = dirCheck;
+
+ if ( typeof part === "string" && !/\W/.test(part) ) {
+ var nodeCheck = part = part.toLowerCase();
+ checkFn = dirNodeCheck;
+ }
+
+ checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
+ }
+ },
+ find: {
+ ID: function(match, context, isXML){
+ if ( typeof context.getElementById !== "undefined" && !isXML ) {
+ var m = context.getElementById(match[1]);
+ return m ? [m] : [];
+ }
+ },
+ NAME: function(match, context){
+ if ( typeof context.getElementsByName !== "undefined" ) {
+ var ret = [], results = context.getElementsByName(match[1]);
+
+ for ( var i = 0, l = results.length; i < l; i++ ) {
+ if ( results[i].getAttribute("name") === match[1] ) {
+ ret.push( results[i] );
+ }
+ }
+
+ return ret.length === 0 ? null : ret;
+ }
+ },
+ TAG: function(match, context){
+ return context.getElementsByTagName(match[1]);
+ }
+ },
+ preFilter: {
+ CLASS: function(match, curLoop, inplace, result, not, isXML){
+ match = " " + match[1].replace(/\\/g, "") + " ";
+
+ if ( isXML ) {
+ return match;
+ }
+
+ 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 ( !inplace ) {
+ result.push( elem );
+ }
+ } else if ( inplace ) {
+ curLoop[i] = false;
+ }
+ }
+ }
+
+ return false;
+ },
+ ID: function(match){
+ return match[1].replace(/\\/g, "");
+ },
+ TAG: function(match, curLoop){
+ return match[1].toLowerCase();
+ },
+ CHILD: function(match){
+ if ( match[1] === "nth" ) {
+ // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
+ var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
+ match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
+ !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
+
+ // calculate the numbers (first)n+(last) including if they are negative
+ match[2] = (test[1] + (test[2] || 1)) - 0;
+ match[3] = test[3] - 0;
+ }
+
+ // TODO: Move to normal caching system
+ match[0] = done++;
+
+ return match;
+ },
+ ATTR: function(match, curLoop, inplace, result, not, isXML){
+ var name = match[1].replace(/\\/g, "");
+
+ if ( !isXML && Expr.attrMap[name] ) {
+ match[1] = Expr.attrMap[name];
+ }
+
+ if ( match[2] === "~=" ) {
+ match[4] = " " + match[4] + " ";
+ }
+
+ return match;
+ },
+ PSEUDO: function(match, curLoop, inplace, result, not){
+ if ( match[1] === "not" ) {
+ // If we're dealing with a complex expression, or a simple one
+ if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
+ match[3] = Sizzle(match[3], null, null, curLoop);
+ } else {
+ var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
+ if ( !inplace ) {
+ result.push.apply( result, ret );
+ }
+ return false;
+ }
+ } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
+ return true;
+ }
+
+ return match;
+ },
+ POS: function(match){
+ match.unshift( true );
+ return match;
+ }
+ },
+ filters: {
+ enabled: function(elem){
+ return elem.disabled === false && elem.type !== "hidden";
+ },
+ disabled: function(elem){
+ return elem.disabled === true;
+ },
+ checked: function(elem){
+ return elem.checked === true;
+ },
+ selected: function(elem){
+ // Accessing this property makes selected-by-default
+ // options in Safari work properly
+ elem.parentNode.selectedIndex;
+ return elem.selected === true;
+ },
+ parent: function(elem){
+ return !!elem.firstChild;
+ },
+ empty: function(elem){
+ return !elem.firstChild;
+ },
+ has: function(elem, i, match){
+ return !!Sizzle( match[3], elem ).length;
+ },
+ header: function(elem){
+ return /h\d/i.test( elem.nodeName );
+ },
+ text: function(elem){
+ return "text" === elem.type;
+ },
+ radio: function(elem){
+ return "radio" === elem.type;
+ },
+ checkbox: function(elem){
+ return "checkbox" === elem.type;
+ },
+ file: function(elem){
+ return "file" === elem.type;
+ },
+ password: function(elem){
+ return "password" === elem.type;
+ },
+ submit: function(elem){
+ return "submit" === elem.type;
+ },
+ image: function(elem){
+ return "image" === elem.type;
+ },
+ reset: function(elem){
+ return "reset" === elem.type;
+ },
+ button: function(elem){
+ return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
+ },
+ input: function(elem){
+ return /input|select|textarea|button/i.test(elem.nodeName);
+ }
+ },
+ setFilters: {
+ first: function(elem, i){
+ return i === 0;
+ },
+ last: function(elem, i, match, array){
+ return i === array.length - 1;
+ },
+ even: function(elem, i){
+ return i % 2 === 0;
+ },
+ odd: function(elem, i){
+ return i % 2 === 1;
+ },
+ lt: function(elem, i, match){
+ return i < match[3] - 0;
+ },
+ gt: function(elem, i, match){
+ return i > match[3] - 0;
+ },
+ nth: function(elem, i, match){
+ return match[3] - 0 === i;
+ },
+ eq: function(elem, i, match){
+ return match[3] - 0 === i;
+ }
+ },
+ filter: {
+ PSEUDO: function(elem, match, i, array){
+ var name = match[1], filter = Expr.filters[ name ];
+
+ if ( filter ) {
+ return filter( elem, i, match, array );
+ } else if ( name === "contains" ) {
+ return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
+ } else if ( name === "not" ) {
+ var not = match[3];
+
+ for ( var i = 0, l = not.length; i < l; i++ ) {
+ if ( not[i] === elem ) {
+ return false;
+ }
+ }
+
+ return true;
+ } else {
+ Sizzle.error( "Syntax error, unrecognized expression: " + name );
+ }
+ },
+ CHILD: function(elem, match){
+ var type = match[1], node = elem;
+ switch (type) {
+ case 'only':
+ case 'first':
+ while ( (node = node.previousSibling) ) {
+ if ( node.nodeType === 1 ) {
+ return false;
+ }
+ }
+ if ( type === "first" ) {
+ return true;
+ }
+ node = elem;
+ case 'last':
+ while ( (node = node.nextSibling) ) {
+ if ( node.nodeType === 1 ) {
+ return false;
+ }
+ }
+ return true;
+ case 'nth':
+ var first = match[2], last = match[3];
+
+ if ( first === 1 && last === 0 ) {
+ return true;
+ }
+
+ var doneName = match[0],
+ parent = elem.parentNode;
+
+ if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
+ var count = 0;
+ for ( node = parent.firstChild; node; node = node.nextSibling ) {
+ if ( node.nodeType === 1 ) {
+ node.nodeIndex = ++count;
+ }
+ }
+ parent.sizcache = doneName;
+ }
+
+ var diff = elem.nodeIndex - last;
+ if ( first === 0 ) {
+ return diff === 0;
+ } else {
+ return ( diff % first === 0 && diff / first >= 0 );
+ }
+ }
+ },
+ ID: function(elem, match){
+ return elem.nodeType === 1 && elem.getAttribute("id") === match;
+ },
+ TAG: function(elem, match){
+ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
+ },
+ CLASS: function(elem, match){
+ return (" " + (elem.className || elem.getAttribute("class")) + " ")
+ .indexOf( match ) > -1;
+ },
+ ATTR: function(elem, match){
+ var name = match[1],
+ result = Expr.attrHandle[ name ] ?
+ Expr.attrHandle[ name ]( elem ) :
+ elem[ name ] != null ?
+ elem[ name ] :
+ elem.getAttribute( name ),
+ value = result + "",
+ type = match[2],
+ check = match[4];
+
+ return result == null ?
+ type === "!=" :
+ type === "=" ?
+ value === check :
+ type === "*=" ?
+ value.indexOf(check) >= 0 :
+ type === "~=" ?
+ (" " + value + " ").indexOf(check) >= 0 :
+ !check ?
+ value && result !== false :
+ type === "!=" ?
+ value !== check :
+ type === "^=" ?
+ value.indexOf(check) === 0 :
+ type === "$=" ?
+ value.substr(value.length - check.length) === check :
+ type === "|=" ?
+ value === check || value.substr(0, check.length + 1) === check + "-" :
+ false;
+ },
+ POS: function(elem, match, i, array){
+ var name = match[2], filter = Expr.setFilters[ name ];
+
+ if ( filter ) {
+ return filter( elem, i, match, array );
+ }
+ }
+ }
+};
+
+var origPOS = Expr.match.POS;
+
+for ( var type in Expr.match ) {
+ Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
+ Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, function(all, num){
+ return "\\" + (num - 0 + 1);
+ }));
+}
+
+var makeArray = function(array, results) {
+ array = Array.prototype.slice.call( array, 0 );
+
+ if ( results ) {
+ results.push.apply( results, array );
+ return results;
+ }
+
+ return array;
+};
+
+// Perform a simple check to determine if the browser is capable of
+// converting a NodeList to an array using builtin methods.
+try {
+ Array.prototype.slice.call( document.documentElement.childNodes, 0 );
+
+// Provide a fallback method if it does not work
+} catch(e){
+ makeArray = function(array, results) {
+ var ret = results || [];
+
+ if ( toString.call(array) === "[object Array]" ) {
+ Array.prototype.push.apply( ret, array );
+ } else {
+ if ( typeof array.length === "number" ) {
+ for ( var i = 0, l = array.length; i < l; i++ ) {
+ ret.push( array[i] );
+ }
+ } else {
+ for ( var i = 0; array[i]; i++ ) {
+ ret.push( array[i] );
+ }
+ }
+ }
+
+ return ret;
+ };
+}
+
+var sortOrder;
+
+if ( document.documentElement.compareDocumentPosition ) {
+ sortOrder = function( a, b ) {
+ if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
+ if ( a == b ) {
+ hasDuplicate = true;
+ }
+ return a.compareDocumentPosition ? -1 : 1;
+ }
+
+ var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
+ if ( ret === 0 ) {
+ hasDuplicate = true;
+ }
+ return ret;
+ };
+} else if ( "sourceIndex" in document.documentElement ) {
+ sortOrder = function( a, b ) {
+ if ( !a.sourceIndex || !b.sourceIndex ) {
+ if ( a == b ) {
+ hasDuplicate = true;
+ }
+ return a.sourceIndex ? -1 : 1;
+ }
+
+ var ret = a.sourceIndex - b.sourceIndex;
+ if ( ret === 0 ) {
+ hasDuplicate = true;
+ }
+ return ret;
+ };
+} else if ( document.createRange ) {
+ sortOrder = function( a, b ) {
+ if ( !a.ownerDocument || !b.ownerDocument ) {
+ if ( a == b ) {
+ hasDuplicate = true;
+ }
+ return a.ownerDocument ? -1 : 1;
+ }
+
+ var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
+ aRange.setStart(a, 0);
+ aRange.setEnd(a, 0);
+ bRange.setStart(b, 0);
+ bRange.setEnd(b, 0);
+ var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
+ if ( ret === 0 ) {
+ hasDuplicate = true;
+ }
+ return ret;
+ };
+}
+
+// Utility function for retreiving the text value of an array of DOM nodes
+function getText( elems ) {
+ var ret = "", elem;
+
+ for ( var i = 0; elems[i]; i++ ) {
+ elem = elems[i];
+
+ // Get the text from text nodes and CDATA nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
+ ret += elem.nodeValue;
+
+ // Traverse everything else, except comment nodes
+ } else if ( elem.nodeType !== 8 ) {
+ ret += getText( elem.childNodes );
+ }
+ }
+
+ return ret;
+}
+
+// Check to see if the browser returns elements by name when
+// querying by getElementById (and provide a workaround)
+(function(){
+ // We're going to inject a fake input element with a specified name
+ var form = document.createElement("div"),
+ id = "script" + (new Date).getTime();
+ form.innerHTML = "<a name='" + id + "'/>";
+
+ // Inject it into the root element, check its status, and remove it quickly
+ var root = document.documentElement;
+ root.insertBefore( form, root.firstChild );
+
+ // The workaround has to do additional checks after a getElementById
+ // Which slows things down for other browsers (hence the branching)
+ if ( document.getElementById( id ) ) {
+ Expr.find.ID = function(match, context, isXML){
+ if ( typeof context.getElementById !== "undefined" && !isXML ) {
+ var m = context.getElementById(match[1]);
+ return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
+ }
+ };
+
+ Expr.filter.ID = function(elem, match){
+ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
+ return elem.nodeType === 1 && node && node.nodeValue === match;
+ };
+ }
+
+ root.removeChild( form );
+ root = form = null; // release memory in IE
+})();
+
+(function(){
+ // Check to see if the browser returns only elements
+ // when doing getElementsByTagName("*")
+
+ // Create a fake element
+ var div = document.createElement("div");
+ div.appendChild( document.createComment("") );
+
+ // Make sure no comments are found
+ if ( div.getElementsByTagName("*").length > 0 ) {
+ Expr.find.TAG = function(match, context){
+ var results = context.getElementsByTagName(match[1]);
+
+ // Filter out possible comments
+ if ( match[1] === "*" ) {
+ var tmp = [];
+
+ for ( var i = 0; results[i]; i++ ) {
+ if ( results[i].nodeType === 1 ) {
+ tmp.push( results[i] );
+ }
+ }
+
+ results = tmp;
+ }
+
+ return results;
+ };
+ }
+
+ // Check to see if an attribute returns normalized href attributes
+ div.innerHTML = "<a href='#'></a>";
+ if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
+ div.firstChild.getAttribute("href") !== "#" ) {
+ Expr.attrHandle.href = function(elem){
+ return elem.getAttribute("href", 2);
+ };
+ }
+
+ div = null; // release memory in IE
+})();
+
+if ( document.querySelectorAll ) {
+ (function(){
+ var oldSizzle = Sizzle, div = document.createElement("div");
+ div.innerHTML = "<p class='TEST'></p>";
+
+ // Safari can't handle uppercase or unicode characters when
+ // in quirks mode.
+ if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
+ return;
+ }
+
+ Sizzle = function(query, context, extra, seed){
+ context = context || document;
+
+ // Only use querySelectorAll on non-XML documents
+ // (ID selectors don't work in non-HTML documents)
+ if ( !seed && context.nodeType === 9 && !isXML(context) ) {
+ try {
+ return makeArray( context.querySelectorAll(query), extra );
+ } catch(e){}
+ }
+
+ return oldSizzle(query, context, extra, seed);
+ };
+
+ for ( var prop in oldSizzle ) {
+ Sizzle[ prop ] = oldSizzle[ prop ];
+ }
+
+ div = null; // release memory in IE
+ })();
+}
+
+(function(){
+ var div = document.createElement("div");
+
+ div.innerHTML = "<div class='test e'></div><div class='test'></div>";
+
+ // Opera can't find a second classname (in 9.6)
+ // Also, make sure that getElementsByClassName actually exists
+ if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
+ return;
+ }
+
+ // Safari caches class attributes, doesn't catch changes (in 3.2)
+ div.lastChild.className = "e";
+
+ if ( div.getElementsByClassName("e").length === 1 ) {
+ return;
+ }
+
+ Expr.order.splice(1, 0, "CLASS");
+ Expr.find.CLASS = function(match, context, isXML) {
+ if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
+ return context.getElementsByClassName(match[1]);
+ }
+ };
+
+ div = null; // release memory in IE
+})();
+
+function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+ if ( elem ) {
+ elem = elem[dir];
+ var match = false;
+
+ while ( elem ) {
+ if ( elem.sizcache === doneName ) {
+ match = checkSet[elem.sizset];
+ break;
+ }
+
+ if ( elem.nodeType === 1 && !isXML ){
+ elem.sizcache = doneName;
+ elem.sizset = i;
+ }
+
+ if ( elem.nodeName.toLowerCase() === cur ) {
+ match = elem;
+ break;
+ }
+
+ elem = elem[dir];
+ }
+
+ checkSet[i] = match;
+ }
+ }
+}
+
+function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+ if ( elem ) {
+ elem = elem[dir];
+ var match = false;
+
+ while ( elem ) {
+ if ( elem.sizcache === doneName ) {
+ match = checkSet[elem.sizset];
+ break;
+ }
+
+ if ( elem.nodeType === 1 ) {
+ if ( !isXML ) {
+ elem.sizcache = doneName;
+ elem.sizset = i;
+ }
+ if ( typeof cur !== "string" ) {
+ if ( elem === cur ) {
+ match = true;
+ break;
+ }
+
+ } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
+ match = elem;
+ break;
+ }
+ }
+
+ elem = elem[dir];
+ }
+
+ checkSet[i] = match;
+ }
+ }
+}
+
+var contains = document.compareDocumentPosition ? function(a, b){
+ return a.compareDocumentPosition(b) & 16;
+} : function(a, b){
+ return a !== b && (a.contains ? a.contains(b) : true);
+};
+
+var isXML = function(elem){
+ // documentElement is verified for cases where it doesn't yet exist
+ // (such as loading iframes in IE - #4833)
+ var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
+ return documentElement ? documentElement.nodeName !== "HTML" : false;
+};
+
+var posProcess = function(selector, context){
+ var tmpSet = [], later = "", match,
+ root = context.nodeType ? [context] : context;
+
+ // Position selectors must be done after the filter
+ // And so must :not(positional) so we move all PSEUDOs to the end
+ while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
+ later += match[0];
+ selector = selector.replace( Expr.match.PSEUDO, "" );
+ }
+
+ selector = Expr.relative[selector] ? selector + "*" : selector;
+
+ for ( var i = 0, l = root.length; i < l; i++ ) {
+ Sizzle( selector, root[i], tmpSet );
+ }
+
+ return Sizzle.filter( later, tmpSet );
+};
+
+// EXPOSE
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.filters;
+jQuery.unique = Sizzle.uniqueSort;
+jQuery.getText = getText;
+jQuery.isXMLDoc = isXML;
+jQuery.contains = contains;
+
+return;
+
+window.Sizzle = Sizzle;
+
+})();
+var runtil = /Until$/,
+ rparentsprev = /^(?:parents|prevUntil|prevAll)/,
+ // Note: This RegExp should be improved, or likely pulled from Sizzle
+ rmultiselector = /,/,
+ slice = Array.prototype.slice;
+
+// Implement the identical functionality for filter and not
+var winnow = function( elements, qualifier, keep ) {
+ if ( jQuery.isFunction( qualifier ) ) {
+ return jQuery.grep(elements, function( elem, i ) {
+ return !!qualifier.call( elem, i, elem ) === keep;
+ });
+
+ } else if ( qualifier.nodeType ) {
+ return jQuery.grep(elements, function( elem, i ) {
+ return (elem === qualifier) === keep;
+ });
+
+ } else if ( typeof qualifier === "string" ) {
+ var filtered = jQuery.grep(elements, function( elem ) {
+ return elem.nodeType === 1;
+ });
+
+ if ( isSimple.test( qualifier ) ) {
+ return jQuery.filter(qualifier, filtered, !keep);
+ } else {
+ qualifier = jQuery.filter( qualifier, filtered );
+ }
+ }
+
+ return jQuery.grep(elements, function( elem, i ) {
+ return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
+ });
+};
+
+jQuery.fn.extend({
+ find: function( selector ) {
+ var ret = this.pushStack( "", "find", selector ), length = 0;
+
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ length = ret.length;
+ jQuery.find( selector, this[i], ret );
+
+ if ( i > 0 ) {
+ // Make sure that the results are unique
+ for ( var n = length; n < ret.length; n++ ) {
+ for ( var r = 0; r < length; r++ ) {
+ if ( ret[r] === ret[n] ) {
+ ret.splice(n--, 1);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ return ret;
+ },
+
+ has: function( target ) {
+ var targets = jQuery( target );
+ return this.filter(function() {
+ for ( var i = 0, l = targets.length; i < l; i++ ) {
+ if ( jQuery.contains( this, targets[i] ) ) {
+ return true;
+ }
+ }
+ });
+ },
+
+ not: function( selector ) {
+ return this.pushStack( winnow(this, selector, false), "not", selector);
+ },
+
+ filter: function( selector ) {
+ return this.pushStack( winnow(this, selector, true), "filter", selector );
+ },
+
+ is: function( selector ) {
+ return !!selector && jQuery.filter( selector, this ).length > 0;
+ },
+
+ closest: function( selectors, context ) {
+ if ( jQuery.isArray( selectors ) ) {
+ var ret = [], cur = this[0], match, matches = {}, selector;
+
+ if ( cur && selectors.length ) {
+ for ( var i = 0, l = selectors.length; i < l; i++ ) {
+ selector = selectors[i];
+
+ if ( !matches[selector] ) {
+ matches[selector] = jQuery.expr.match.POS.test( selector ) ?
+ jQuery( selector, context || this.context ) :
+ selector;
+ }
+ }
+
+ while ( cur && cur.ownerDocument && cur !== context ) {
+ for ( selector in matches ) {
+ match = matches[selector];
+
+ if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) {
+ ret.push({ selector: selector, elem: cur });
+ delete matches[selector];
+ }
+ }
+ cur = cur.parentNode;
+ }
+ }
+
+ return ret;
+ }
+
+ var pos = jQuery.expr.match.POS.test( selectors ) ?
+ jQuery( selectors, context || this.context ) : null;
+
+ return this.map(function( i, cur ) {
+ while ( cur && cur.ownerDocument && cur !== context ) {
+ if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) {
+ return cur;
+ }
+ cur = cur.parentNode;
+ }
+ return null;
+ });
+ },
+
+ // Determine the position of an element within
+ // the matched set of elements
+ index: function( elem ) {
+ if ( !elem || typeof elem === "string" ) {
+ return jQuery.inArray( this[0],
+ // If it receives a string, the selector is used
+ // If it receives nothing, the siblings are used
+ elem ? jQuery( elem ) : this.parent().children() );
+ }
+ // Locate the position of the desired element
+ return jQuery.inArray(
+ // If it receives a jQuery object, the first element is used
+ elem.jquery ? elem[0] : elem, this );
+ },
+
+ add: function( selector, context ) {
+ var set = typeof selector === "string" ?
+ jQuery( selector, context || this.context ) :
+ jQuery.makeArray( selector ),
+ all = jQuery.merge( this.get(), set );
+
+ return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
+ all :
+ jQuery.unique( all ) );
+ },
+
+ andSelf: function() {
+ return this.add( this.prevObject );
+ }
+});
+
+// A painfully simple check to see if an element is disconnected
+// from a document (should be improved, where feasible).
+function isDisconnected( node ) {
+ return !node || !node.parentNode || node.parentNode.nodeType === 11;
+}
+
+jQuery.each({
+ parent: function( elem ) {
+ var parent = elem.parentNode;
+ return parent && parent.nodeType !== 11 ? parent : null;
+ },
+ parents: function( elem ) {
+ return jQuery.dir( elem, "parentNode" );
+ },
+ parentsUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "parentNode", until );
+ },
+ next: function( elem ) {
+ return jQuery.nth( elem, 2, "nextSibling" );
+ },
+ prev: function( elem ) {
+ return jQuery.nth( elem, 2, "previousSibling" );
+ },
+ nextAll: function( elem ) {
+ return jQuery.dir( elem, "nextSibling" );
+ },
+ prevAll: function( elem ) {
+ return jQuery.dir( elem, "previousSibling" );
+ },
+ nextUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "nextSibling", until );
+ },
+ prevUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "previousSibling", until );
+ },
+ siblings: function( elem ) {
+ return jQuery.sibling( elem.parentNode.firstChild, elem );
+ },
+ children: function( elem ) {
+ return jQuery.sibling( elem.firstChild );
+ },
+ contents: function( elem ) {
+ return jQuery.nodeName( elem, "iframe" ) ?
+ elem.contentDocument || elem.contentWindow.document :
+ jQuery.makeArray( elem.childNodes );
+ }
+}, function( name, fn ) {
+ jQuery.fn[ name ] = function( until, selector ) {
+ var ret = jQuery.map( this, fn, until );
+
+ if ( !runtil.test( name ) ) {
+ selector = until;
+ }
+
+ if ( selector && typeof selector === "string" ) {
+ ret = jQuery.filter( selector, ret );
+ }
+
+ ret = this.length > 1 ? 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(",") );
+ };
+});
+
+jQuery.extend({
+ filter: function( expr, elems, not ) {
+ if ( not ) {
+ expr = ":not(" + expr + ")";
+ }
+
+ return jQuery.find.matches(expr, elems);
+ },
+
+ dir: function( elem, dir, until ) {
+ var matched = [], cur = elem[dir];
+ while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
+ if ( cur.nodeType === 1 ) {
+ matched.push( cur );
+ }
+ cur = cur[dir];
+ }
+ return matched;
+ },
+
+ nth: function( cur, result, dir, elem ) {
+ result = result || 1;
+ var num = 0;
+
+ for ( ; cur; cur = cur[dir] ) {
+ if ( cur.nodeType === 1 && ++num === result ) {
+ break;
+ }
+ }
+
+ return cur;
+ },
+
+ sibling: function( n, elem ) {
+ var r = [];
+
+ for ( ; n; n = n.nextSibling ) {
+ if ( n.nodeType === 1 && n !== elem ) {
+ r.push( n );
+ }
+ }
+
+ return r;
+ }
+});
+var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
+ rleadingWhitespace = /^\s+/,
+ rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g,
+ rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,
+ rtagName = /<([\w:]+)/,
+ rtbody = /<tbody/i,
+ rhtml = /<|&\w+;/,
+ rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, // checked="checked" or checked (html5)
+ fcloseTag = function( all, front, tag ) {
+ return rselfClosing.test( tag ) ?
+ all :
+ front + "></" + tag + ">";
+ },
+ wrapMap = {
+ option: [ 1, "<select multiple='multiple'>", "</select>" ],
+ legend: [ 1, "<fieldset>", "</fieldset>" ],
+ thead: [ 1, "<table>", "</table>" ],
+ tr: [ 2, "<table><tbody>", "</tbody></table>" ],
+ td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
+ col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
+ area: [ 1, "<map>", "</map>" ],
+ _default: [ 0, "", "" ]
+ };
+
+wrapMap.optgroup = wrapMap.option;
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+// IE can't serialize <link> and <script> tags normally
+if ( !jQuery.support.htmlSerialize ) {
+ wrapMap._default = [ 1, "div<div>", "</div>" ];
+}
+
+jQuery.fn.extend({
+ text: function( text ) {
+ if ( jQuery.isFunction(text) ) {
+ return this.each(function(i) {
+ var self = jQuery(this);
+ self.text( text.call(this, i, self.text()) );
+ });
+ }
+
+ if ( typeof text !== "object" && text !== undefined ) {
+ return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
+ }
+
+ return jQuery.getText( this );
+ },
+
+ wrapAll: function( html ) {
+ if ( jQuery.isFunction( html ) ) {
+ return this.each(function(i) {
+ jQuery(this).wrapAll( html.call(this, i) );
+ });
+ }
+
+ if ( this[0] ) {
+ // The elements to wrap the target around
+ var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
+
+ if ( this[0].parentNode ) {
+ wrap.insertBefore( this[0] );
+ }
+
+ wrap.map(function() {
+ var elem = this;
+
+ while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
+ elem = elem.firstChild;
+ }
+
+ return elem;
+ }).append(this);
+ }
+
+ return this;
+ },
+
+ wrapInner: function( html ) {
+ if ( jQuery.isFunction( html ) ) {
+ return this.each(function(i) {
+ jQuery(this).wrapInner( html.call(this, i) );
+ });
+ }
+
+ return this.each(function() {
+ var self = jQuery( this ), contents = self.contents();
+
+ if ( contents.length ) {
+ contents.wrapAll( html );
+
+ } else {
+ self.append( html );
+ }
+ });
+ },
+
+ wrap: function( html ) {
+ return this.each(function() {
+ jQuery( this ).wrapAll( html );
+ });
+ },
+
+ unwrap: function() {
+ return this.parent().each(function() {
+ if ( !jQuery.nodeName( this, "body" ) ) {
+ jQuery( this ).replaceWith( this.childNodes );
+ }
+ }).end();
+ },
+
+ append: function() {
+ return this.domManip(arguments, true, function( elem ) {
+ if ( this.nodeType === 1 ) {
+ this.appendChild( elem );
+ }
+ });
+ },
+
+ prepend: function() {
+ return this.domManip(arguments, true, function( elem ) {
+ if ( this.nodeType === 1 ) {
+ this.insertBefore( elem, this.firstChild );
+ }
+ });
+ },
+
+ before: function() {
+ if ( this[0] && this[0].parentNode ) {
+ return this.domManip(arguments, false, function( elem ) {
+ this.parentNode.insertBefore( elem, this );
+ });
+ } else if ( arguments.length ) {
+ var set = jQuery(arguments[0]);
+ set.push.apply( set, this.toArray() );
+ return this.pushStack( set, "before", arguments );
+ }
+ },
+
+ after: function() {
+ if ( this[0] && this[0].parentNode ) {
+ return this.domManip(arguments, false, function( elem ) {
+ this.parentNode.insertBefore( elem, this.nextSibling );
+ });
+ } else if ( arguments.length ) {
+ var set = this.pushStack( this, "after", arguments );
+ set.push.apply( set, jQuery(arguments[0]).toArray() );
+ return set;
+ }
+ },
+
+ 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, "")
+ .replace(rleadingWhitespace, "")], ownerDocument)[0];
+ } else {
+ return this.cloneNode(true);
+ }
+ });
+
+ // 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;
+ },
+
+ html: function( value ) {
+ if ( value === undefined ) {
+ return this[0] && this[0].nodeType === 1 ?
+ this[0].innerHTML.replace(rinlinejQuery, "") :
+ null;
+
+ // See if we can take a shortcut and just use innerHTML
+ } else if ( typeof value === "string" && !/<script/i.test( value ) &&
+ (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
+ !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
+
+ value = value.replace(rxhtmlTag, fcloseTag);
+
+ try {
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ // Remove element nodes and prevent memory leaks
+ if ( this[i].nodeType === 1 ) {
+ jQuery.cleanData( this[i].getElementsByTagName("*") );
+ this[i].innerHTML = value;
+ }
+ }
+
+ // If using innerHTML throws an exception, use the fallback method
+ } catch(e) {
+ this.empty().append( value );
+ }
+
+ } else if ( jQuery.isFunction( value ) ) {
+ this.each(function(i){
+ var self = jQuery(this), old = self.html();
+ self.empty().append(function(){
+ return value.call( this, i, old );
+ });
+ });
+
+ } else {
+ this.empty().append( value );
+ }
+
+ return this;
+ },
+
+ replaceWith: function( value ) {
+ if ( this[0] && this[0].parentNode ) {
+ // Make sure that the elements are removed from the DOM before they are inserted
+ // this can help fix replacing a parent with child elements
+ if ( !jQuery.isFunction( value ) ) {
+ value = jQuery( value ).detach();
+
+ } else {
+ return this.each(function(i) {
+ var self = jQuery(this), old = self.html();
+ self.replaceWith( value.call( this, i, old ) );
+ });
+ }
+
+ return this.each(function() {
+ var next = this.nextSibling, parent = this.parentNode;
+
+ jQuery(this).remove();
+
+ if ( next ) {
+ jQuery(next).before( value );
+ } else {
+ jQuery(parent).append( value );
+ }
+ });
+ } else {
+ return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
+ }
+ },
+
+ detach: function( selector ) {
+ return this.remove( selector, true );
+ },
+
+ domManip: function( args, table, callback ) {
+ var results, first, value = args[0], scripts = [];
+
+ // We can't cloneNode fragments that contain checked, in WebKit
+ if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
+ return this.each(function() {
+ jQuery(this).domManip( args, table, callback, true );
+ });
+ }
+
+ if ( jQuery.isFunction(value) ) {
+ return this.each(function(i) {
+ var self = jQuery(this);
+ args[0] = value.call(this, i, table ? self.html() : undefined);
+ self.domManip( args, table, callback );
+ });
+ }
+
+ if ( this[0] ) {
+ // If we're in a fragment, just use that instead of building a new one
+ if ( args[0] && args[0].parentNode && args[0].parentNode.nodeType === 11 ) {
+ results = { fragment: args[0].parentNode };
+ } else {
+ results = buildFragment( args, this, scripts );
+ }
+
+ first = results.fragment.firstChild;
+
+ if ( first ) {
+ table = table && jQuery.nodeName( first, "tr" );
+
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ callback.call(
+ table ?
+ root(this[i], first) :
+ this[i],
+ results.cacheable || this.length > 1 || i > 0 ?
+ results.fragment.cloneNode(true) :
+ results.fragment
+ );
+ }
+ }
+
+ if ( scripts ) {
+ jQuery.each( scripts, evalScript );
+ }
+ }
+
+ return this;
+
+ function root( elem, cur ) {
+ return jQuery.nodeName(elem, "table") ?
+ (elem.getElementsByTagName("tbody")[0] ||
+ elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
+ elem;
+ }
+ }
+});
+
+function cloneCopyEvent(orig, ret) {
+ var i = 0;
+
+ ret.each(function() {
+ if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
+ return;
+ }
+
+ var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events;
+
+ 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 );
+ }
+ }
+ }
+ });
+}
+
+function buildFragment( args, nodes, scripts ) {
+ var fragment, cacheable, cacheresults, doc;
+
+ // webkit does not clone 'checked' attribute of radio inputs on cloneNode, so don't cache if string has a checked
+ if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && args[0].indexOf("<option") < 0 && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
+ cacheable = true;
+ cacheresults = jQuery.fragments[ args[0] ];
+ if ( cacheresults ) {
+ if ( cacheresults !== 1 ) {
+ fragment = cacheresults;
+ }
+ }
+ }
+
+ if ( !fragment ) {
+ doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
+ fragment = doc.createDocumentFragment();
+ jQuery.clean( args, doc, fragment, scripts );
+ }
+
+ if ( cacheable ) {
+ jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
+ }
+
+ return { fragment: fragment, cacheable: cacheable };
+}
+
+jQuery.fragments = {};
+
+jQuery.each({
+ appendTo: "append",
+ prependTo: "prepend",
+ insertBefore: "before",
+ insertAfter: "after",
+ replaceAll: "replaceWith"
+}, function( name, original ) {
+ jQuery.fn[ name ] = function( selector ) {
+ var ret = [], insert = jQuery( selector );
+
+ for ( var i = 0, l = insert.length; i < l; i++ ) {
+ var elems = (i > 0 ? this.clone(true) : this).get();
+ jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
+ ret = ret.concat( elems );
+ }
+ return this.pushStack( ret, name, insert.selector );
+ };
+});
+
+jQuery.each({
+ // keepData is for internal use only--do not document
+ remove: function( selector, keepData ) {
+ if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
+ if ( !keepData && this.nodeType === 1 ) {
+ jQuery.cleanData( this.getElementsByTagName("*") );
+ jQuery.cleanData( [ this ] );
+ }
+
+ if ( this.parentNode ) {
+ this.parentNode.removeChild( this );
+ }
+ }
+ },
+
+ empty: function() {
+ // Remove element nodes and prevent memory leaks
+ if ( this.nodeType === 1 ) {
+ jQuery.cleanData( this.getElementsByTagName("*") );
+ }
+
+ // Remove any remaining nodes
+ while ( this.firstChild ) {
+ this.removeChild( this.firstChild );
+ }
+ }
+}, function( name, fn ) {
+ jQuery.fn[ name ] = function() {
+ return this.each( fn, arguments );
+ };
+});
+
+jQuery.extend({
+ clean: function( elems, context, fragment, scripts ) {
+ context = context || document;
+
+ // !context.createElement fails in IE with an error but returns typeof 'object'
+ if ( typeof context.createElement === "undefined" ) {
+ context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
+ }
+
+ var ret = [];
+
+ jQuery.each(elems, function( i, elem ) {
+ if ( typeof elem === "number" ) {
+ elem += "";
+ }
+
+ if ( !elem ) {
+ return;
+ }
+
+ // Convert html string into DOM nodes
+ if ( typeof elem === "string" && !rhtml.test( elem ) ) {
+ elem = context.createTextNode( elem );
+
+ } else if ( typeof elem === "string" ) {
+ // Fix "XHTML"-style tags in all browsers
+ elem = elem.replace(rxhtmlTag, fcloseTag);
+
+ // Trim whitespace, otherwise indexOf won't work as expected
+ var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
+ wrap = wrapMap[ tag ] || wrapMap._default,
+ depth = wrap[0],
+ div = context.createElement("div");
+
+ // Go to html and back, then peel off extra wrappers
+ div.innerHTML = wrap[1] + elem + wrap[2];
+
+ // Move to the right depth
+ while ( depth-- ) {
+ div = div.lastChild;
+ }
+
+ // Remove IE's autoinserted <tbody> from table fragments
+ if ( !jQuery.support.tbody ) {
+
+ // String was a <table>, *may* have spurious <tbody>
+ var hasBody = rtbody.test(elem),
+ tbody = tag === "table" && !hasBody ?
+ div.firstChild && div.firstChild.childNodes :
+
+ // String was a bare <thead> or <tfoot>
+ wrap[1] === "<table>" && !hasBody ?
+ div.childNodes :
+ [];
+
+ for ( var j = tbody.length - 1; j >= 0 ; --j ) {
+ if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
+ tbody[ j ].parentNode.removeChild( tbody[ j ] );
+ }
+ }
+
+ }
+
+ // IE completely kills leading whitespace when innerHTML is used
+ if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
+ div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
+ }
+
+ elem = jQuery.makeArray( div.childNodes );
+ }
+
+ if ( elem.nodeType ) {
+ ret.push( elem );
+ } else {
+ ret = jQuery.merge( ret, elem );
+ }
+
+ });
+
+ if ( fragment ) {
+ for ( var 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"))) );
+ }
+ fragment.appendChild( ret[i] );
+ }
+ }
+ }
+
+ return ret;
+ },
+
+ cleanData: function( elems ) {
+ for ( var i = 0, elem, id; (elem = elems[i]) != null; i++ ) {
+ jQuery.event.remove( elem );
+ jQuery.removeData( elem );
+ }
+ }
+});
+// exclude the following css properties to add px
+var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
+ ralpha = /alpha\([^)]*\)/,
+ ropacity = /opacity=([^)]*)/,
+ rfloat = /float/i,
+ rdashAlpha = /-([a-z])/ig,
+ rupper = /([A-Z])/g,
+ rnumpx = /^-?\d+(?:px)?$/i,
+ rnum = /^-?\d/,
+
+ cssShow = { position: "absolute", visibility: "hidden", display:"block" },
+ cssWidth = [ "Left", "Right" ],
+ cssHeight = [ "Top", "Bottom" ],
+
+ // cache check for defaultView.getComputedStyle
+ getComputedStyle = document.defaultView && document.defaultView.getComputedStyle,
+ // normalize float css property
+ styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat",
+ fcamelCase = function( all, letter ) {
+ return letter.toUpperCase();
+ };
+
+jQuery.fn.css = function( name, value ) {
+ return access( this, name, value, true, function( elem, name, value ) {
+ if ( value === undefined ) {
+ return jQuery.curCSS( elem, name );
+ }
+
+ if ( typeof value === "number" && !rexclude.test(name) ) {
+ value += "px";
+ }
+
+ jQuery.style( elem, name, value );
+ });
+};
+
+jQuery.extend({
+ style: function( elem, name, value ) {
+ // don't set styles on text and comment nodes
+ if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return undefined;
+ }
+
+ // ignore negative width and height values #1599
+ if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) {
+ value = undefined;
+ }
+
+ var style = elem.style || elem, set = value !== undefined;
+
+ // IE uses filters for opacity
+ if ( !jQuery.support.opacity && name === "opacity" ) {
+ if ( set ) {
+ // IE has trouble with opacity if it does not have layout
+ // Force it by setting the zoom level
+ style.zoom = 1;
+
+ // Set the alpha filter to set the opacity
+ var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")";
+ var filter = style.filter || jQuery.curCSS( elem, "filter" ) || "";
+ style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity;
+ }
+
+ return style.filter && style.filter.indexOf("opacity=") >= 0 ?
+ (parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "":
+ "";
+ }
+
+ // Make sure we're using the right name for getting the float value
+ if ( rfloat.test( name ) ) {
+ name = styleFloat;
+ }
+
+ name = name.replace(rdashAlpha, fcamelCase);
+
+ if ( set ) {
+ style[ name ] = value;
+ }
+
+ return style[ name ];
+ },
+
+ css: function( elem, name, force, extra ) {
+ if ( name === "width" || name === "height" ) {
+ var val, props = cssShow, which = name === "width" ? cssWidth : cssHeight;
+
+ function getWH() {
+ val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
+
+ if ( extra === "border" ) {
+ return;
+ }
+
+ jQuery.each( which, function() {
+ if ( !extra ) {
+ val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
+ }
+
+ if ( extra === "margin" ) {
+ val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
+ } else {
+ val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
+ }
+ });
+ }
+
+ if ( elem.offsetWidth !== 0 ) {
+ getWH();
+ } else {
+ jQuery.swap( elem, props, getWH );
+ }
+
+ return Math.max(0, Math.round(val));
+ }
+
+ return jQuery.curCSS( elem, name, force );
+ },
+
+ curCSS: function( elem, name, force ) {
+ var ret, style = elem.style, filter;
+
+ // IE uses filters for opacity
+ if ( !jQuery.support.opacity && name === "opacity" && elem.currentStyle ) {
+ ret = ropacity.test(elem.currentStyle.filter || "") ?
+ (parseFloat(RegExp.$1) / 100) + "" :
+ "";
+
+ return ret === "" ?
+ "1" :
+ ret;
+ }
+
+ // Make sure we're using the right name for getting the float value
+ if ( rfloat.test( name ) ) {
+ name = styleFloat;
+ }
+
+ if ( !force && style && style[ name ] ) {
+ ret = style[ name ];
+
+ } else if ( getComputedStyle ) {
+
+ // Only "float" is needed here
+ if ( rfloat.test( name ) ) {
+ name = "float";
+ }
+
+ name = name.replace( rupper, "-$1" ).toLowerCase();
+
+ var defaultView = elem.ownerDocument.defaultView;
+
+ if ( !defaultView ) {
+ return null;
+ }
+
+ var computedStyle = defaultView.getComputedStyle( elem, null );
+
+ if ( computedStyle ) {
+ ret = computedStyle.getPropertyValue( name );
+ }
+
+ // We should always get a number back from opacity
+ if ( name === "opacity" && ret === "" ) {
+ ret = "1";
+ }
+
+ } else if ( elem.currentStyle ) {
+ var camelCase = name.replace(rdashAlpha, fcamelCase);
+
+ ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
+
+ // From the awesome hack by Dean Edwards
+ // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+
+ // If we're not dealing with a regular pixel number
+ // but a number that has a weird ending, we need to convert it to pixels
+ if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
+ // Remember the original values
+ var left = style.left, rsLeft = elem.runtimeStyle.left;
+
+ // Put in the new values to get a computed value out
+ elem.runtimeStyle.left = elem.currentStyle.left;
+ style.left = camelCase === "fontSize" ? "1em" : (ret || 0);
+ ret = style.pixelLeft + "px";
+
+ // Revert the changed values
+ style.left = left;
+ elem.runtimeStyle.left = rsLeft;
+ }
+ }
+
+ return ret;
+ },
+
+ // A method for quickly swapping in/out CSS properties to get correct calculations
+ swap: function( elem, options, callback ) {
+ var old = {};
+
+ // Remember the old values, and insert the new ones
+ for ( var name in options ) {
+ old[ name ] = elem.style[ name ];
+ elem.style[ name ] = options[ name ];
+ }
+
+ callback.call( elem );
+
+ // Revert the old values
+ for ( var name in options ) {
+ elem.style[ name ] = old[ name ];
+ }
+ }
+});
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+ jQuery.expr.filters.hidden = function( elem ) {
+ var width = elem.offsetWidth, height = elem.offsetHeight,
+ skip = elem.nodeName.toLowerCase() === "tr";
+
+ return width === 0 && height === 0 && !skip ?
+ true :
+ width > 0 && height > 0 && !skip ?
+ false :
+ jQuery.curCSS(elem, "display") === "none";
+ };
+
+ jQuery.expr.filters.visible = function( elem ) {
+ return !jQuery.expr.filters.hidden( elem );
+ };
+}
+var jsc = now(),
+ rscript = /<script(.|\s)*?\/script>/gi,
+ rselectTextarea = /select|textarea/i,
+ rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,
+ jsre = /=\?(&|$)/,
+ rquery = /\?/,
+ rts = /(\?|&)_=.*?(&|$)/,
+ rurl = /^(\w+:)?\/\/([^\/?#]+)/,
+ r20 = /%20/g;
+
+jQuery.fn.extend({
+ // Keep a copy of the old load
+ _load: jQuery.fn.load,
+
+ load: function( url, params, callback ) {
+ if ( typeof url !== "string" ) {
+ return this._load( url );
+
+ // Don't do a request if no elements are being requested
+ } else if ( !this.length ) {
+ return this;
+ }
+
+ var off = url.indexOf(" ");
+ if ( off >= 0 ) {
+ var selector = url.slice(off, url.length);
+ url = url.slice(0, off);
+ }
+
+ // Default to a GET request
+ var type = "GET";
+
+ // If the second parameter was provided
+ if ( params ) {
+ // If it's a function
+ if ( jQuery.isFunction( params ) ) {
+ // We assume that it's the callback
+ callback = params;
+ params = null;
+
+ // Otherwise, build a param string
+ } else if ( typeof params === "object" ) {
+ params = jQuery.param( params, jQuery.ajaxSettings.traditional );
+ type = "POST";
+ }
+ }
+
+ var self = this;
+
+ // Request the remote document
+ jQuery.ajax({
+ url: url,
+ type: type,
+ dataType: "html",
+ data: params,
+ complete: function( res, status ) {
+ // If successful, inject the HTML into all the matched elements
+ if ( status === "success" || status === "notmodified" ) {
+ // 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, ""))
+
+ // Locate the specified elements
+ .find(selector) :
+
+ // If not, just inject the full result
+ res.responseText );
+ }
+
+ if ( callback ) {
+ self.each( callback, [res.responseText, status, res] );
+ }
+ }
+ });
+
+ return this;
+ },
+
+ serialize: function() {
+ return jQuery.param(this.serializeArray());
+ },
+ serializeArray: function() {
+ return this.map(function() {
+ return this.elements ? jQuery.makeArray(this.elements) : this;
+ })
+ .filter(function() {
+ return this.name && !this.disabled &&
+ (this.checked || rselectTextarea.test(this.nodeName) ||
+ rinput.test(this.type));
+ })
+ .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 };
+ }) :
+ { name: elem.name, value: val };
+ }).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.extend({
+
+ get: function( url, data, callback, type ) {
+ // shift arguments if data argument was omited
+ if ( jQuery.isFunction( data ) ) {
+ type = type || callback;
+ callback = data;
+ data = null;
+ }
+
+ return jQuery.ajax({
+ type: "GET",
+ url: url,
+ data: data,
+ success: callback,
+ dataType: type
+ });
+ },
+
+ getScript: function( url, callback ) {
+ 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
+ });
+ },
+
+ ajaxSetup: function( settings ) {
+ jQuery.extend( jQuery.ajaxSettings, settings );
+ },
+
+ ajaxSettings: {
+ url: location.href,
+ global: true,
+ type: "GET",
+ contentType: "application/x-www-form-urlencoded",
+ processData: true,
+ async: true,
+ /*
+ timeout: 0,
+ data: null,
+ username: null,
+ password: null,
+ traditional: false,
+ */
+ // 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
+ // This function can be overriden by calling jQuery.ajaxSetup
+ xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
+ function() {
+ return new window.XMLHttpRequest();
+ } :
+ function() {
+ try {
+ return new window.ActiveXObject("Microsoft.XMLHTTP");
+ } catch(e) {}
+ },
+ accepts: {
+ xml: "application/xml, text/xml",
+ html: "text/html",
+ script: "text/javascript, application/javascript",
+ json: "application/json, text/javascript",
+ text: "text/plain",
+ _default: "*/*"
+ }
+ },
+
+ // Last-Modified header cache for next request
+ lastModified: {},
+ etag: {},
+
+ ajax: function( origSettings ) {
+ var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings);
+
+ var jsonp, status, data,
+ callbackContext = origSettings && origSettings.context || s,
+ type = s.type.toUpperCase();
+
+ // convert data if not already a string
+ if ( s.data && s.processData && typeof s.data !== "string" ) {
+ s.data = jQuery.param( s.data, s.traditional );
+ }
+
+ // 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") + "=?";
+ }
+ 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++);
+
+ // Replace the =? sequence both in the query string and the data
+ if ( s.data ) {
+ s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
+ }
+
+ s.url = s.url.replace(jsre, "=" + jsonp + "$1");
+
+ // We need to make sure
+ // that a JSONP style response is executed properly
+ s.dataType = "script";
+
+ // Handle JSONP-style loading
+ window[ jsonp ] = window[ jsonp ] || function( tmp ) {
+ data = tmp;
+ success();
+ complete();
+ // Garbage collect
+ window[ jsonp ] = undefined;
+
+ try {
+ delete window[ jsonp ];
+ } catch(e) {}
+
+ if ( head ) {
+ head.removeChild( script );
+ }
+ };
+ }
+
+ if ( s.dataType === "script" && s.cache === null ) {
+ s.cache = false;
+ }
+
+ if ( s.cache === false && type === "GET" ) {
+ var ts = now();
+
+ // try replacing _= if it is there
+ var ret = s.url.replace(rts, "$1_=" + ts + "$2");
+
+ // if nothing was replaced, add timestamp to the end
+ s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
+ }
+
+ // If data is available, append data to url for get requests
+ if ( s.data && type === "GET" ) {
+ s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
+ }
+
+ // Watch for a new set of requests
+ if ( s.global && ! jQuery.active++ ) {
+ jQuery.event.trigger( "ajaxStart" );
+ }
+
+ // Matches an absolute URL, and saves the domain
+ var parts = rurl.exec( s.url ),
+ remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
+
+ // 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");
+ script.src = s.url;
+ if ( s.scriptCharset ) {
+ script.charset = s.scriptCharset;
+ }
+
+ // Handle Script loading
+ if ( !jsonp ) {
+ var done = false;
+
+ // Attach handlers for all browsers
+ script.onload = script.onreadystatechange = function() {
+ if ( !done && (!this.readyState ||
+ this.readyState === "loaded" || this.readyState === "complete") ) {
+ done = true;
+ success();
+ complete();
+
+ // Handle memory leak in IE
+ script.onload = script.onreadystatechange = null;
+ if ( head && script.parentNode ) {
+ head.removeChild( script );
+ }
+ }
+ };
+ }
+
+ // 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 );
+
+ // We handle everything using the script element injection
+ return undefined;
+ }
+
+ var requestDone = false;
+
+ // Create the request object
+ var xhr = s.xhr();
+
+ if ( !xhr ) {
+ return;
+ }
+
+ // 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);
+ }
+
+ // Need an extra try/catch for cross domain requests in Firefox 3
+ try {
+ // Set the correct header, if data is being sent
+ if ( s.data || 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]);
+ }
+
+ if ( jQuery.etag[s.url] ) {
+ xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
+ }
+ }
+
+ // 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");
+ }
+
+ // Set the Accepts header for the server, depending on the dataType
+ xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
+ s.accepts[ s.dataType ] + ", */*" :
+ s.accepts._default );
+ } catch(e) {}
+
+ // Allow custom headers/mimetypes and early abort
+ if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) {
+ // Handle the global AJAX counter
+ if ( s.global && ! --jQuery.active ) {
+ jQuery.event.trigger( "ajaxStop" );
+ }
+
+ // close opended socket
+ xhr.abort();
+ return false;
+ }
+
+ if ( s.global ) {
+ trigger("ajaxSend", [xhr, s]);
+ }
+
+ // 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 ) {
+ complete();
+ }
+
+ requestDone = true;
+ if ( xhr ) {
+ xhr.onreadystatechange = jQuery.noop;
+ }
+
+ // 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;
+
+ status = isTimeout === "timeout" ?
+ "timeout" :
+ !jQuery.httpSuccess( xhr ) ?
+ "error" :
+ s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
+ "notmodified" :
+ "success";
+
+ var errMsg;
+
+ 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(err) {
+ status = "parsererror";
+ errMsg = err;
+ }
+ }
+
+ // Make sure that the request was successful or notmodified
+ if ( status === "success" || status === "notmodified" ) {
+ // JSONP handles its own success callback
+ if ( !jsonp ) {
+ success();
+ }
+ } else {
+ jQuery.handleError(s, xhr, status, errMsg);
+ }
+
+ // Fire the complete handlers
+ complete();
+
+ if ( isTimeout === "timeout" ) {
+ xhr.abort();
+ }
+
+ // Stop memory leaks
+ if ( s.async ) {
+ xhr = null;
+ }
+ }
+ };
+
+ // Override the abort handler, if we can (IE 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.call( xhr );
+ }
+
+ onreadystatechange( "abort" );
+ };
+ } catch(e) { }
+
+ // 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( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null );
+ } catch(e) {
+ jQuery.handleError(s, xhr, null, e);
+ // Fire the complete handlers
+ complete();
+ }
+
+ // firefox 1.5 doesn't fire statechange for sync requests
+ if ( !s.async ) {
+ onreadystatechange();
+ }
+
+ function success() {
+ // If a local callback was specified, fire it and pass it the data
+ if ( s.success ) {
+ s.success.call( callbackContext, data, status, xhr );
+ }
+
+ // Fire the global callback
+ if ( s.global ) {
+ trigger( "ajaxSuccess", [xhr, s] );
+ }
+ }
+
+ function complete() {
+ // Process result
+ if ( s.complete ) {
+ s.complete.call( callbackContext, xhr, status);
+ }
+
+ // The request was completed
+ if ( s.global ) {
+ trigger( "ajaxComplete", [xhr, s] );
+ }
+
+ // Handle the global AJAX counter
+ if ( s.global && ! --jQuery.active ) {
+ jQuery.event.trigger( "ajaxStop" );
+ }
+ }
+
+ function trigger(type, args) {
+ (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
+ }
+
+ // return XMLHttpRequest to allow aborting the request etc.
+ return xhr;
+ },
+
+ handleError: function( s, xhr, status, e ) {
+ // If a local callback was specified, fire it
+ if ( s.error ) {
+ s.error.call( s.context || s, xhr, status, e );
+ }
+
+ // Fire the global callback
+ if ( s.global ) {
+ (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
+ }
+ },
+
+ // Counter for holding the number of active queries
+ active: 0,
+
+ // 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:" ||
+ // Opera returns 0 when status is 304
+ ( xhr.status >= 200 && xhr.status < 300 ) ||
+ xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
+ } 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;
+ }
+
+ if ( etag ) {
+ jQuery.etag[url] = etag;
+ }
+
+ // Opera returns 0 when status is 304
+ return xhr.status === 304 || xhr.status === 0;
+ },
+
+ 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;
+
+ if ( xml && data.documentElement.nodeName === "parsererror" ) {
+ jQuery.error( "parsererror" );
+ }
+
+ // 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 );
+ }
+
+ // 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 );
+
+ // If the type is "script", eval it in global context
+ } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
+ jQuery.globalEval( data );
+ }
+ }
+
+ return data;
+ },
+
+ // Serialize an array of form elements or a set of
+ // key/values into a query string
+ param: function( a, traditional ) {
+ var s = [];
+
+ // 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 ) {
+ // 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] );
+ }
+ }
+
+ // Return the resulting serialization
+ return s.join("&").replace(r20, "+");
+
+ function buildParams( prefix, obj ) {
+ if ( jQuery.isArray(obj) ) {
+ // Serialize array item.
+ jQuery.each( obj, function( i, v ) {
+ if ( traditional ) {
+ // Treat each array item as a scalar.
+ add( prefix, v );
+ } else {
+ // If array item is non-scalar (array or object), encode its
+ // numeric index to resolve deserialization ambiguity issues.
+ // Note that rack (as of 1.0.0) can't currently deserialize
+ // nested arrays properly, and attempting to do so may cause
+ // a server error. Possible fixes are to modify rack's
+ // deserialization algorithm or to provide an option or flag
+ // to force array serialization to be shallow.
+ buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v );
+ }
+ });
+
+ } else if ( !traditional && obj != null && typeof obj === "object" ) {
+ // Serialize object item.
+ jQuery.each( obj, function( k, v ) {
+ buildParams( prefix + "[" + k + "]", v );
+ });
+
+ } else {
+ // Serialize scalar item.
+ add( prefix, obj );
+ }
+ }
+
+ function add( 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);
+ }
+ }
+});
+var elemdisplay = {},
+ rfxtypes = /toggle|show|hide/,
+ rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/,
+ timerId,
+ fxAttrs = [
+ // height animations
+ [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
+ // width animations
+ [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
+ // opacity animations
+ [ "opacity" ]
+ ];
+
+jQuery.fn.extend({
+ show: function( speed, callback ) {
+ if ( speed || speed === 0) {
+ return this.animate( genFx("show", 3), speed, callback);
+
+ } else {
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ var old = jQuery.data(this[i], "olddisplay");
+
+ this[i].style.display = old || "";
+
+ if ( jQuery.css(this[i], "display") === "none" ) {
+ var nodeName = this[i].nodeName, display;
+
+ if ( elemdisplay[ nodeName ] ) {
+ display = elemdisplay[ nodeName ];
+
+ } else {
+ var elem = jQuery("<" + nodeName + " />").appendTo("body");
+
+ display = elem.css("display");
+
+ if ( display === "none" ) {
+ display = "block";
+ }
+
+ elem.remove();
+
+ elemdisplay[ nodeName ] = display;
+ }
+
+ jQuery.data(this[i], "olddisplay", display);
+ }
+ }
+
+ // Set the display of the elements in a second loop
+ // to avoid the constant reflow
+ for ( var j = 0, k = this.length; j < k; j++ ) {
+ this[j].style.display = jQuery.data(this[j], "olddisplay") || "";
+ }
+
+ return this;
+ }
+ },
+
+ hide: function( speed, callback ) {
+ if ( speed || speed === 0 ) {
+ return this.animate( genFx("hide", 3), speed, callback);
+
+ } else {
+ for ( var i = 0, l = this.length; i < l; i++ ) {
+ var old = jQuery.data(this[i], "olddisplay");
+ if ( !old && old !== "none" ) {
+ jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
+ }
+ }
+
+ // Set the display of the elements in a second loop
+ // to avoid the constant reflow
+ for ( var j = 0, k = this.length; j < k; j++ ) {
+ this[j].style.display = "none";
+ }
+
+ return this;
+ }
+ },
+
+ // Save the old toggle function
+ _toggle: jQuery.fn.toggle,
+
+ toggle: function( fn, fn2 ) {
+ var bool = typeof fn === "boolean";
+
+ if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
+ this._toggle.apply( this, arguments );
+
+ } else if ( fn == null || bool ) {
+ this.each(function() {
+ var state = bool ? fn : jQuery(this).is(":hidden");
+ jQuery(this)[ state ? "show" : "hide" ]();
+ });
+
+ } else {
+ this.animate(genFx("toggle", 3), fn, fn2);
+ }
+
+ return this;
+ },
+
+ fadeTo: function( speed, to, callback ) {
+ return this.filter(":hidden").css("opacity", 0).show().end()
+ .animate({opacity: to}, speed, callback);
+ },
+
+ animate: function( prop, speed, easing, callback ) {
+ var optall = jQuery.speed(speed, easing, callback);
+
+ if ( jQuery.isEmptyObject( prop ) ) {
+ return this.each( optall.complete );
+ }
+
+ return this[ optall.queue === false ? "each" : "queue" ](function() {
+ var opt = jQuery.extend({}, optall), p,
+ hidden = this.nodeType === 1 && jQuery(this).is(":hidden"),
+ self = this;
+
+ for ( p in prop ) {
+ var name = p.replace(rdashAlpha, fcamelCase);
+
+ if ( p !== name ) {
+ prop[ name ] = prop[ p ];
+ delete prop[ p ];
+ p = name;
+ }
+
+ if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) {
+ return opt.complete.call(this);
+ }
+
+ if ( ( p === "height" || p === "width" ) && this.style ) {
+ // Store display property
+ opt.display = jQuery.css(this, "display");
+
+ // Make sure that nothing sneaks out
+ opt.overflow = this.style.overflow;
+ }
+
+ if ( jQuery.isArray( prop[p] ) ) {
+ // Create (if needed) and add to specialEasing
+ (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1];
+ prop[p] = prop[p][0];
+ }
+ }
+
+ if ( opt.overflow != null ) {
+ this.style.overflow = "hidden";
+ }
+
+ opt.curAnim = jQuery.extend({}, prop);
+
+ jQuery.each( prop, function( name, val ) {
+ var e = new jQuery.fx( self, opt, name );
+
+ if ( rfxtypes.test(val) ) {
+ e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop );
+
+ } else {
+ var parts = rfxnum.exec(val),
+ start = e.cur(true) || 0;
+
+ if ( parts ) {
+ var end = parseFloat( parts[2] ),
+ unit = parts[3] || "px";
+
+ // We need to compute starting value
+ if ( unit !== "px" ) {
+ self.style[ name ] = (end || 1) + unit;
+ start = ((end || 1) / e.cur(true)) * start;
+ self.style[ name ] = start + unit;
+ }
+
+ // If a +=/-= token was provided, we're doing a relative animation
+ if ( parts[1] ) {
+ end = ((parts[1] === "-=" ? -1 : 1) * end) + start;
+ }
+
+ e.custom( start, end, unit );
+
+ } else {
+ e.custom( start, val, "" );
+ }
+ }
+ });
+
+ // For JS strict compliance
+ return true;
+ });
+ },
+
+ stop: function( clearQueue, gotoEnd ) {
+ var timers = jQuery.timers;
+
+ if ( clearQueue ) {
+ this.queue([]);
+ }
+
+ this.each(function() {
+ // go in reverse order so anything added to the queue during the loop is ignored
+ for ( var i = timers.length - 1; i >= 0; i-- ) {
+ if ( timers[i].elem === this ) {
+ if (gotoEnd) {
+ // force the next step to be the last
+ timers[i](true);
+ }
+
+ timers.splice(i, 1);
+ }
+ }
+ });
+
+ // start the next in the queue if the last step wasn't forced
+ if ( !gotoEnd ) {
+ this.dequeue();
+ }
+
+ return this;
+ }
+
+});
+
+// Generate shortcuts for custom animations
+jQuery.each({
+ slideDown: genFx("show", 1),
+ slideUp: genFx("hide", 1),
+ slideToggle: genFx("toggle", 1),
+ fadeIn: { opacity: "show" },
+ fadeOut: { opacity: "hide" }
+}, function( name, props ) {
+ jQuery.fn[ name ] = function( speed, callback ) {
+ return this.animate( props, speed, callback );
+ };
+});
+
+jQuery.extend({
+ speed: function( speed, easing, fn ) {
+ var opt = speed && typeof speed === "object" ? speed : {
+ complete: fn || !fn && easing ||
+ jQuery.isFunction( speed ) && speed,
+ duration: speed,
+ easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
+ };
+
+ opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
+ jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default;
+
+ // Queueing
+ opt.old = opt.complete;
+ opt.complete = function() {
+ if ( opt.queue !== false ) {
+ jQuery(this).dequeue();
+ }
+ if ( jQuery.isFunction( opt.old ) ) {
+ opt.old.call( this );
+ }
+ };
+
+ return opt;
+ },
+
+ easing: {
+ linear: function( p, n, firstNum, diff ) {
+ return firstNum + diff * p;
+ },
+ swing: function( p, n, firstNum, diff ) {
+ return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
+ }
+ },
+
+ timers: [],
+
+ fx: function( elem, options, prop ) {
+ this.options = options;
+ this.elem = elem;
+ this.prop = prop;
+
+ if ( !options.orig ) {
+ options.orig = {};
+ }
+ }
+
+});
+
+jQuery.fx.prototype = {
+ // Simple function for setting a style value
+ update: function() {
+ if ( this.options.step ) {
+ this.options.step.call( this.elem, this.now, this );
+ }
+
+ (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
+
+ // Set display property to block for height/width animations
+ if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) {
+ this.elem.style.display = "block";
+ }
+ },
+
+ // Get the current size
+ cur: function( force ) {
+ if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
+ return this.elem[ this.prop ];
+ }
+
+ var r = parseFloat(jQuery.css(this.elem, this.prop, force));
+ return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
+ },
+
+ // Start an animation from one number to another
+ custom: function( from, to, unit ) {
+ this.startTime = now();
+ this.start = from;
+ this.end = to;
+ this.unit = unit || this.unit || "px";
+ this.now = this.start;
+ this.pos = this.state = 0;
+
+ var self = this;
+ function t( gotoEnd ) {
+ return self.step(gotoEnd);
+ }
+
+ t.elem = this.elem;
+
+ if ( t() && jQuery.timers.push(t) && !timerId ) {
+ timerId = setInterval(jQuery.fx.tick, 13);
+ }
+ },
+
+ // Simple 'show' function
+ show: function() {
+ // Remember where we started, so that we can go back to it later
+ this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
+ this.options.show = true;
+
+ // Begin the animation
+ // Make sure that we start at a small width/height to avoid any
+ // flash of content
+ this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
+
+ // Start by showing the element
+ jQuery( this.elem ).show();
+ },
+
+ // Simple 'hide' function
+ hide: function() {
+ // Remember where we started, so that we can go back to it later
+ this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
+ this.options.hide = true;
+
+ // Begin the animation
+ this.custom(this.cur(), 0);
+ },
+
+ // Each step of an animation
+ step: function( gotoEnd ) {
+ var t = now(), done = true;
+
+ if ( gotoEnd || t >= this.options.duration + this.startTime ) {
+ this.now = this.end;
+ this.pos = this.state = 1;
+ this.update();
+
+ this.options.curAnim[ this.prop ] = true;
+
+ for ( var i in this.options.curAnim ) {
+ if ( this.options.curAnim[i] !== true ) {
+ done = false;
+ }
+ }
+
+ if ( done ) {
+ if ( this.options.display != null ) {
+ // Reset the overflow
+ this.elem.style.overflow = this.options.overflow;
+
+ // Reset the display
+ var old = jQuery.data(this.elem, "olddisplay");
+ this.elem.style.display = old ? old : this.options.display;
+
+ if ( jQuery.css(this.elem, "display") === "none" ) {
+ this.elem.style.display = "block";
+ }
+ }
+
+ // Hide the element if the "hide" operation was done
+ if ( this.options.hide ) {
+ jQuery(this.elem).hide();
+ }
+
+ // Reset the properties, if the item has been hidden or shown
+ if ( this.options.hide || this.options.show ) {
+ for ( var p in this.options.curAnim ) {
+ jQuery.style(this.elem, p, this.options.orig[p]);
+ }
+ }
+
+ // Execute the complete function
+ this.options.complete.call( this.elem );
+ }
+
+ return false;
+
+ } else {
+ var n = t - this.startTime;
+ this.state = n / this.options.duration;
+
+ // Perform the easing function, defaults to swing
+ var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop];
+ var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear");
+ this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration);
+ this.now = this.start + ((this.end - this.start) * this.pos);
+
+ // Perform the next step of the animation
+ this.update();
+ }
+
+ return true;
+ }
+};
+
+jQuery.extend( jQuery.fx, {
+ tick: function() {
+ var timers = jQuery.timers;
+
+ for ( var i = 0; i < timers.length; i++ ) {
+ if ( !timers[i]() ) {
+ timers.splice(i--, 1);
+ }
+ }
+
+ if ( !timers.length ) {
+ jQuery.fx.stop();
+ }
+ },
+
+ stop: function() {
+ clearInterval( timerId );
+ timerId = null;
+ },
+
+ speeds: {
+ slow: 600,
+ fast: 200,
+ // Default speed
+ _default: 400
+ },
+
+ step: {
+ opacity: function( fx ) {
+ jQuery.style(fx.elem, "opacity", fx.now);
+ },
+
+ _default: function( fx ) {
+ if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
+ fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
+ } else {
+ fx.elem[ fx.prop ] = fx.now;
+ }
+ }
+ }
+});
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+ jQuery.expr.filters.animated = function( elem ) {
+ return jQuery.grep(jQuery.timers, function( fn ) {
+ return elem === fn.elem;
+ }).length;
+ };
+}
+
+function genFx( type, num ) {
+ var obj = {};
+
+ jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
+ obj[ this ] = type;
+ });
+
+ return obj;
+}
+if ( "getBoundingClientRect" in document.documentElement ) {
+ jQuery.fn.offset = function( options ) {
+ var elem = this[0];
+
+ if ( options ) {
+ return this.each(function( i ) {
+ jQuery.offset.setOffset( this, options, i );
+ });
+ }
+
+ if ( !elem || !elem.ownerDocument ) {
+ return null;
+ }
+
+ if ( elem === elem.ownerDocument.body ) {
+ return jQuery.offset.bodyOffset( elem );
+ }
+
+ var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement,
+ clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
+ top = box.top + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop,
+ left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
+
+ return { top: top, left: left };
+ };
+
+} else {
+ jQuery.fn.offset = function( options ) {
+ var elem = this[0];
+
+ if ( options ) {
+ return this.each(function( i ) {
+ jQuery.offset.setOffset( this, options, i );
+ });
+ }
+
+ if ( !elem || !elem.ownerDocument ) {
+ return null;
+ }
+
+ if ( elem === elem.ownerDocument.body ) {
+ return jQuery.offset.bodyOffset( elem );
+ }
+
+ jQuery.offset.initialize();
+
+ var offsetParent = elem.offsetParent, prevOffsetParent = elem,
+ doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
+ body = doc.body, defaultView = doc.defaultView,
+ prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
+ top = elem.offsetTop, left = elem.offsetLeft;
+
+ while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
+ if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
+ break;
+ }
+
+ computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
+ top -= elem.scrollTop;
+ left -= elem.scrollLeft;
+
+ if ( elem === offsetParent ) {
+ top += elem.offsetTop;
+ left += elem.offsetLeft;
+
+ if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.nodeName)) ) {
+ top += parseFloat( computedStyle.borderTopWidth ) || 0;
+ left += parseFloat( computedStyle.borderLeftWidth ) || 0;
+ }
+
+ prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
+ }
+
+ if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
+ top += parseFloat( computedStyle.borderTopWidth ) || 0;
+ left += parseFloat( computedStyle.borderLeftWidth ) || 0;
+ }
+
+ prevComputedStyle = computedStyle;
+ }
+
+ if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
+ top += body.offsetTop;
+ left += body.offsetLeft;
+ }
+
+ if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
+ top += Math.max( docElem.scrollTop, body.scrollTop );
+ left += Math.max( docElem.scrollLeft, body.scrollLeft );
+ }
+
+ return { top: top, left: left };
+ };
+}
+
+jQuery.offset = {
+ initialize: function() {
+ var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0,
+ html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
+
+ jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );
+
+ container.innerHTML = html;
+ body.insertBefore( container, body.firstChild );
+ innerDiv = container.firstChild;
+ checkDiv = innerDiv.firstChild;
+ td = innerDiv.nextSibling.firstChild.firstChild;
+
+ this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
+ this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
+
+ checkDiv.style.position = "fixed", checkDiv.style.top = "20px";
+ // safari subtracts parent border width here which is 5px
+ this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
+ checkDiv.style.position = checkDiv.style.top = "";
+
+ innerDiv.style.overflow = "hidden", innerDiv.style.position = "relative";
+ this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
+
+ this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);
+
+ body.removeChild( container );
+ body = container = innerDiv = checkDiv = table = td = null;
+ jQuery.offset.initialize = jQuery.noop;
+ },
+
+ bodyOffset: function( body ) {
+ var top = body.offsetTop, left = body.offsetLeft;
+
+ jQuery.offset.initialize();
+
+ if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
+ top += parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0;
+ left += parseFloat( jQuery.curCSS(body, "marginLeft", true) ) || 0;
+ }
+
+ return { top: top, left: left };
+ },
+
+ setOffset: function( elem, options, i ) {
+ // set position first, in-case top/left are set even on static elem
+ if ( /static/.test( jQuery.curCSS( elem, "position" ) ) ) {
+ elem.style.position = "relative";
+ }
+ var curElem = jQuery( elem ),
+ curOffset = curElem.offset(),
+ curTop = parseInt( jQuery.curCSS( elem, "top", true ), 10 ) || 0,
+ curLeft = parseInt( jQuery.curCSS( elem, "left", true ), 10 ) || 0;
+
+ if ( jQuery.isFunction( options ) ) {
+ options = options.call( elem, i, curOffset );
+ }
+
+ var props = {
+ top: (options.top - curOffset.top) + curTop,
+ left: (options.left - curOffset.left) + curLeft
+ };
+
+ if ( "using" in options ) {
+ options.using.call( elem, props );
+ } else {
+ curElem.css( props );
+ }
+ }
+};
+
+
+jQuery.fn.extend({
+ position: function() {
+ if ( !this[0] ) {
+ return null;
+ }
+
+ var elem = this[0],
+
+ // Get *real* offsetParent
+ offsetParent = this.offsetParent(),
+
+ // Get correct offsets
+ offset = this.offset(),
+ parentOffset = /^body|html$/i.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
+
+ // Subtract element margins
+ // note: when an element has margin: auto the offsetLeft and marginLeft
+ // are the same in Safari causing offset.left to incorrectly be 0
+ offset.top -= parseFloat( jQuery.curCSS(elem, "marginTop", true) ) || 0;
+ offset.left -= parseFloat( jQuery.curCSS(elem, "marginLeft", true) ) || 0;
+
+ // Add offsetParent borders
+ parentOffset.top += parseFloat( jQuery.curCSS(offsetParent[0], "borderTopWidth", true) ) || 0;
+ parentOffset.left += parseFloat( jQuery.curCSS(offsetParent[0], "borderLeftWidth", true) ) || 0;
+
+ // Subtract the two offsets
+ return {
+ top: offset.top - parentOffset.top,
+ left: offset.left - parentOffset.left
+ };
+ },
+
+ offsetParent: function() {
+ return this.map(function() {
+ var offsetParent = this.offsetParent || document.body;
+ while ( offsetParent && (!/^body|html$/i.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
+ offsetParent = offsetParent.offsetParent;
+ }
+ return offsetParent;
+ });
+ }
+});
+
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( ["Left", "Top"], function( i, name ) {
+ var method = "scroll" + name;
+
+ jQuery.fn[ method ] = function(val) {
+ var elem = this[0], win;
+
+ if ( !elem ) {
+ return null;
+ }
+
+ if ( val !== undefined ) {
+ // Set the scroll offset
+ return this.each(function() {
+ win = getWindow( this );
+
+ if ( win ) {
+ win.scrollTo(
+ !i ? val : jQuery(win).scrollLeft(),
+ i ? val : jQuery(win).scrollTop()
+ );
+
+ } else {
+ this[ method ] = val;
+ }
+ });
+ } else {
+ win = getWindow( elem );
+
+ // Return the scroll offset
+ return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
+ jQuery.support.boxModel && win.document.documentElement[ method ] ||
+ win.document.body[ method ] :
+ elem[ method ];
+ }
+ };
+});
+
+function getWindow( elem ) {
+ return ("scrollTo" in elem && elem.document) ?
+ elem :
+ elem.nodeType === 9 ?
+ elem.defaultView || elem.parentWindow :
+ false;
+}
+// Create innerHeight, innerWidth, outerHeight and outerWidth methods
+jQuery.each([ "Height", "Width" ], function( i, name ) {
+
+ var type = name.toLowerCase();
+
+ // innerHeight and innerWidth
+ jQuery.fn["inner" + name] = function() {
+ return this[0] ?
+ jQuery.css( this[0], type, false, "padding" ) :
+ null;
+ };
+
+ // outerHeight and outerWidth
+ jQuery.fn["outer" + name] = function( margin ) {
+ return this[0] ?
+ jQuery.css( this[0], type, false, margin ? "margin" : "border" ) :
+ null;
+ };
+
+ jQuery.fn[ type ] = function( size ) {
+ // Get window width or height
+ var elem = this[0];
+ if ( !elem ) {
+ return size == null ? null : this;
+ }
+
+ if ( jQuery.isFunction( size ) ) {
+ return this.each(function( i ) {
+ var self = jQuery( this );
+ self[ type ]( size.call( this, i, self[ type ]() ) );
+ });
+ }
+
+ return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window?
+ // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
+ elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] ||
+ elem.document.body[ "client" + name ] :
+
+ // Get document width or height
+ (elem.nodeType === 9) ? // is it a document
+ // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
+ Math.max(
+ elem.documentElement["client" + name],
+ elem.body["scroll" + name], elem.documentElement["scroll" + name],
+ elem.body["offset" + name], elem.documentElement["offset" + name]
+ ) :
+
+ // Get or set width or height on the element
+ size === undefined ?
+ // Get width or height on the element
+ jQuery.css( elem, type ) :
+
+ // Set the width or height on the element (default to pixels if value is unitless)
+ this.css( type, typeof size === "string" ? size : size + "px" );
+ };
+
+});
+// Expose jQuery to the global object
+window.jQuery = window.$ = jQuery;
+
+})(window);
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
new file mode 100644
index 0000000000..43456a77f6
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js
@@ -0,0 +1,132 @@
+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'));
+ });
+ });
+
+});
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/rails.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js
index 4283ed8982..fc69f93c58 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/rails.js
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js
@@ -14,33 +14,33 @@
}
function isForm(element) {
- return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM'
+ return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM';
}
function isInput(element) {
if (Object.isElement(element)) {
- var name = element.nodeName.toUpperCase()
- return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA'
+ var name = element.nodeName.toUpperCase();
+ return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA';
}
- else return false
+ else return false;
}
var submitBubbles = isEventSupported('submit'),
- changeBubbles = isEventSupported('change')
+ changeBubbles = isEventSupported('change');
if (!submitBubbles || !changeBubbles) {
// augment the Event.Handler class to observe custom events when needed
Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap(
function(init, element, eventName, selector, callback) {
- init(element, eventName, selector, callback)
+ init(element, eventName, selector, callback);
// is the handler being attached to an element that doesn't support this event?
if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) ||
(!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) {
// "submit" => "emulated:submit"
- this.eventName = 'emulated:' + this.eventName
+ this.eventName = 'emulated:' + this.eventName;
}
}
- )
+ );
}
if (!submitBubbles) {
@@ -49,26 +49,26 @@
// special handler for the real "submit" event (one-time operation)
if (!form.retrieve('emulated:submit')) {
form.on('submit', function(submitEvent) {
- var emulated = form.fire('emulated:submit', submitEvent, true)
+ var emulated = form.fire('emulated:submit', submitEvent, true);
// if custom event received preventDefault, cancel the real one too
- if (emulated.returnValue === false) submitEvent.preventDefault()
- })
- form.store('emulated:submit', true)
+ if (emulated.returnValue === false) submitEvent.preventDefault();
+ });
+ form.store('emulated:submit', true);
}
- })
+ });
}
if (!changeBubbles) {
// discover form inputs on the page
- document.on('focusin', 'input, select, texarea', function(focusEvent, input) {
+ document.on('focusin', 'input, select, textarea', function(focusEvent, input) {
// special handler for real "change" events
if (!input.retrieve('emulated:change')) {
input.on('change', function(changeEvent) {
- input.fire('emulated:change', changeEvent, true)
- })
- input.store('emulated:change', true)
+ input.fire('emulated:change', changeEvent, true);
+ });
+ input.store('emulated:change', true);
}
- })
+ });
}
function handleRemote(element) {
@@ -80,7 +80,10 @@
if (element.tagName.toLowerCase() === 'form') {
method = element.readAttribute('method') || 'post';
url = element.readAttribute('action');
- params = element.serialize();
+ // serialize the form with respect to the submit button that was pressed
+ params = element.serialize({ submit: element.retrieve('rails:submit-button') });
+ // clear the pressed submit button information
+ element.store('rails:submit-button', null);
} else {
method = element.readAttribute('data-method') || 'get';
url = element.readAttribute('href');
@@ -100,6 +103,10 @@
element.fire("ajax:after");
}
+ function insertHiddenField(form, name, value) {
+ form.insert(new Element('input', { type: 'hidden', name: name, value: value }));
+ }
+
function handleMethod(element) {
var method = element.readAttribute('data-method'),
url = element.readAttribute('href'),
@@ -110,15 +117,11 @@
element.parentNode.insert(form);
if (method !== 'post') {
- var field = new Element('input', { type: 'hidden', name: '_method', value: method });
- form.insert(field);
+ insertHiddenField(form, '_method', method);
}
if (csrf_param) {
- var param = csrf_param.readAttribute('content'),
- token = csrf_token.readAttribute('content'),
- field = new Element('input', { type: 'hidden', name: param, value: token });
- form.insert(field);
+ insertHiddenField(form, csrf_param.readAttribute('content'), csrf_token.readAttribute('content'));
}
form.submit();
@@ -142,34 +145,34 @@
event.stop();
});
+ document.on("click", "form input[type=submit]", function(event, button) {
+ // register the pressed submit button
+ event.findElement('form').store('rails:submit-button', button.name || false);
+ });
+
document.on("submit", function(event) {
- var element = event.findElement(),
- message = element.readAttribute('data-confirm');
+ var form = event.findElement(),
+ message = form.readAttribute('data-confirm');
+
if (message && !confirm(message)) {
event.stop();
return false;
}
- var inputs = element.select("input[type=submit][data-disable-with]");
- inputs.each(function(input) {
- input.disabled = true;
- input.writeAttribute('data-original-value', input.value);
- input.value = input.readAttribute('data-disable-with');
+ 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'));
});
- var element = event.findElement("form[data-remote]");
- if (element) {
- handleRemote(element);
+ if (form.readAttribute('data-remote')) {
+ handleRemote(form);
event.stop();
}
});
- document.on("ajax:after", "form", function(event, element) {
- var inputs = element.select("input[type=submit][disabled=true][data-disable-with]");
- inputs.each(function(input) {
- input.value = input.readAttribute('data-original-value');
- input.removeAttribute('data-original-value');
- input.disabled = false;
+ 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();
});
});
})();
diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb
index d303212f52..8570fc7b3f 100644
--- a/railties/lib/rails/paths.rb
+++ b/railties/lib/rails/paths.rb
@@ -2,15 +2,17 @@ require 'set'
module Rails
module Paths
- module PathParent
- attr_reader :children
-
+ module PathParent #:nodoc:
def method_missing(id, *args)
- name = id.to_s
+ match = id.to_s.match(/^(.*)=$/)
+ full = [@current, $1 || id].compact.join("/")
+
+ ActiveSupport::Deprecation.warn 'config.paths.app.controller API is deprecated in ' <<
+ 'favor of config.paths["app/controller"] API.'
- if name =~ /^(.*)=$/ || args.any?
- @children[$1 || name] = Path.new(@root, *args)
- elsif path = @children[name]
+ if match || args.any?
+ @root[full] = Path.new(@root, full, *args)
+ elsif path = @root[full]
path
else
super
@@ -18,22 +20,72 @@ module Rails
end
end
- class Root
+ # This object is an extended hash that behaves as root of the Rails::Paths system.
+ # It allows you to collect information about how you want to structure your application
+ # paths by a Hash like API. It requires you to give a physical path on initialization.
+ #
+ # root = Root.new
+ # root.add "app/controllers", :eager_load => true
+ #
+ # The command above creates a new root object and add "app/controllers" as a path.
+ # This means we can get a Path object back like below:
+ #
+ # path = root["app/controllers"]
+ # path.eager_load? #=> true
+ # path.is_a?(Rails::Paths::Path) #=> true
+ #
+ # The Path object is simply an array and allows you to easily add extra paths:
+ #
+ # path.is_a?(Array) #=> true
+ # path.inspect #=> ["app/controllers"]
+ #
+ # path << "lib/controllers"
+ # path.inspect #=> ["app/controllers", "lib/controllers"]
+ #
+ # Notice that when you add a path using #add, the path object created already
+ # contains the path with the same path value given to #add. In some situations,
+ # you may not want this behavior, so you can give :with as option.
+ #
+ # root.add "config/routes", :with => "config/routes.rb"
+ # root["config/routes"].inspect #=> ["config/routes.rb"]
+ #
+ # #add also accepts the following options as argument: eager_load, autoload,
+ # autoload_once and glob.
+ #
+ # Finally, the Path object also provides a few helpers:
+ #
+ # root = Root.new
+ # root.path = "/rails"
+ # root.add "app/controllers"
+ #
+ # root["app/controllers"].expanded #=> ["/rails/app/controllers"]
+ # root["app/controllers"].existent #=> ["/rails/app/controllers"]
+ #
+ # Check the Path documentation for more information.
+ class Root < ::Hash
include PathParent
-
attr_accessor :path
def initialize(path)
raise if path.is_a?(Array)
- @children = {}
+ @current = nil
@path = path
@root = self
- @all_paths = []
+ super()
+ end
+
+ def []=(path, value)
+ value = Path.new(self, path, value) unless value.is_a?(Path)
+ super(path, value)
+ end
+
+ def add(path, options={})
+ with = options[:with] || path
+ self[path] = Path.new(self, path, with, options)
end
def all_paths
- @all_paths.uniq!
- @all_paths
+ values.tap { |v| v.uniq! }
end
def autoload_once
@@ -52,68 +104,54 @@ module Rails
filter_by(:load_path?)
end
- def push(*)
- raise "Application root can only have one physical path"
- end
-
- alias unshift push
- alias << push
- alias concat push
-
protected
def filter_by(constraint)
all = []
all_paths.each do |path|
if path.send(constraint)
- paths = path.paths
- paths -= path.children.values.map { |p| p.send(constraint) ? [] : p.paths }.flatten
+ paths = path.existent
+ paths -= path.children.map { |p| p.send(constraint) ? [] : p.existent }.flatten
all.concat(paths)
end
end
all.uniq!
- all.reject! { |p| !File.exists?(p) }
all
end
end
- class Path
- include PathParent, Enumerable
+ class Path < Array
+ include PathParent
attr_reader :path
attr_accessor :glob
- def initialize(root, *paths)
- options = paths.last.is_a?(::Hash) ? paths.pop : {}
- @children = {}
+ def initialize(root, current, *paths)
+ options = paths.last.is_a?(::Hash) ? paths.pop : {}
+ super(paths.flatten)
+
+ @current = current
@root = root
- @paths = paths.flatten
@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]
-
- @root.all_paths << self
- end
-
- def each
- to_a.each { |p| yield p }
end
- def push(path)
- @paths.push path
+ def children
+ keys = @root.keys.select { |k| k.include?(@current) }
+ keys.delete(@current)
+ @root.values_at(*keys.sort)
end
- alias << push
-
- def unshift(path)
- @paths.unshift path
+ def first
+ expanded.first
end
- def concat(paths)
- @paths.concat paths
+ def last
+ expanded.last
end
%w(autoload_once eager_load autoload load_path).each do |m|
@@ -132,20 +170,36 @@ module Rails
RUBY
end
- def paths
+ # Expands all paths against the root and return all unique values.
+ def expanded
raise "You need to set a path root" unless @root.path
+ result = []
- result = @paths.map do |p|
+ each do |p|
path = File.expand_path(p, @root.path)
- @glob ? Dir[File.join(path, @glob)] : path
+
+ if @glob
+ result.concat Dir[File.join(path, @glob)]
+ else
+ result << path
+ end
end
- result.flatten!
result.uniq!
result
end
- alias to_a paths
+ # Returns all expanded paths but only if they exist in the filesystem.
+ def existent
+ expanded.select { |f| File.exists?(f) }
+ end
+
+ def paths
+ ActiveSupport::Deprecation.warn "paths is deprecated. Please call expand instead."
+ expanded
+ end
+
+ alias to_a expanded
end
end
-end \ No newline at end of file
+end
diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb
index 5614624673..ceddd25eaa 100644
--- a/railties/lib/rails/plugin.rb
+++ b/railties/lib/rails/plugin.rb
@@ -62,13 +62,13 @@ module Rails
end
initializer :handle_lib_autoload, :before => :set_load_path do |app|
- paths = if app.config.reload_plugins
+ autoload = if app.config.reload_plugins
config.autoload_paths
else
config.autoload_once_paths
end
- paths.concat config.paths.lib.to_a
+ autoload.concat paths["lib"].existent
end
initializer :load_init_rb, :before => :load_config_initializers do |app|
@@ -83,7 +83,7 @@ module Rails
initializer :sanity_check_railties_collision do
if Engine.subclasses.map { |k| k.root.to_s }.include?(root.to_s)
- raise "\"#{name}\" is a Railtie/Engine and cannot be installed as plugin"
+ raise "\"#{name}\" is a Railtie/Engine and cannot be installed as a plugin"
end
end
end
diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb
index 2b68a3c453..c76bc83377 100644
--- a/railties/lib/rails/railtie.rb
+++ b/railties/lib/rails/railtie.rb
@@ -191,6 +191,13 @@ module Rails
def load_tasks
self.class.rake_tasks.each(&:call)
+
+ # load also tasks from all superclasses
+ klass = self.class.superclass
+ while klass.respond_to?(:rake_tasks)
+ klass.rake_tasks.each { |t| self.instance_exec(&t) }
+ klass = klass.superclass
+ end
end
def load_generators
diff --git a/railties/lib/rails/tasks/documentation.rake b/railties/lib/rails/tasks/documentation.rake
index 7aefbb49b0..edd716d7d0 100644
--- a/railties/lib/rails/tasks/documentation.rake
+++ b/railties/lib/rails/tasks/documentation.rake
@@ -47,7 +47,7 @@ namespace :doc do
rdoc.rdoc_files.include('app/**/*.rb')
rdoc.rdoc_files.include('lib/**/*.rb')
}
- Rake::Task['doc:app'].comment = "Generate docs for the app -- also availble doc:rails, doc:guides, doc:plugins (options: TEMPLATE=/rdoc-template.rb, TITLE=\"Custom Title\")"
+ Rake::Task['doc:app'].comment = "Generate docs for the app -- also available doc:rails, doc:guides, doc:plugins (options: TEMPLATE=/rdoc-template.rb, TITLE=\"Custom Title\")"
# desc 'Generate documentation for the Rails framework.'
RDocTaskWithoutDescriptions.new("rails") { |rdoc|
diff --git a/railties/lib/rails/tasks/framework.rake b/railties/lib/rails/tasks/framework.rake
index 745a32a1fa..5222b7bf50 100644
--- a/railties/lib/rails/tasks/framework.rake
+++ b/railties/lib/rails/tasks/framework.rake
@@ -60,7 +60,7 @@ namespace :rails do
# desc "Update Prototype javascripts from your current rails install"
task :javascripts do
- invoke_from_app_generator :create_prototype_files
+ invoke_from_app_generator :create_javascript_files
end
# desc "Adds new scripts to the application script/ directory"
diff --git a/railties/lib/rails/tasks/railties.rake b/railties/lib/rails/tasks/railties.rake
index 7cf31f84a0..16703879cf 100644
--- a/railties/lib/rails/tasks/railties.rake
+++ b/railties/lib/rails/tasks/railties.rake
@@ -1,20 +1,29 @@
namespace :railties do
- desc "Create symlinks to railties public directories in application's public directory."
- task :create_symlinks => :environment do
- paths = Rails.application.config.static_asset_paths.dup
- app_public_path = Rails.application.config.paths.public.to_a.first
+ namespace :install do
+ # desc "Copies missing assets from Railties (e.g. plugins, engines). You can specify Railties to use with FROM=railtie1,railtie2"
+ task :assets => :rails_env do
+ require 'rails/generators/base'
+ Rails.application.initialize!
- paths.each do |mount_path, path|
- symlink_path = File.join(app_public_path, mount_path)
- if File.exist?(symlink_path)
- File.symlink?(symlink_path) ? FileUtils.rm(symlink_path) : next
- end
+ to_load = ENV["FROM"].blank? ? :all : ENV["FROM"].split(",").map {|n| n.strip }
+ app_public_path = Rails.application.paths["public"].first
- next unless File.exist?(path)
+ Rails.application.railties.all do |railtie|
+ next unless to_load == :all || to_load.include?(railtie.railtie_name)
- File.symlink(path, symlink_path)
+ if railtie.respond_to?(:paths) && (path = railtie.paths["public"].first) &&
+ (assets_dir = railtie.config.compiled_asset_path) && File.exist?(path)
- puts "Created symlink #{symlink_path} -> #{path}"
+ Rails::Generators::Base.source_root(path)
+ copier = Rails::Generators::Base.new
+ Dir[File.join(path, "**/*")].each do |file|
+ relative = file.gsub(/^#{path}\//, '')
+ if File.file?(file)
+ copier.copy_file relative, File.join(app_public_path, assets_dir, relative)
+ end
+ end
+ end
+ end
end
end
end
diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake
index 713833f884..28dc40379b 100644
--- a/railties/lib/rails/test_unit/testing.rake
+++ b/railties/lib/rails/test_unit/testing.rake
@@ -73,7 +73,8 @@ end
desc 'Runs test:units, test:functionals, test:integration together (also available: test:benchmark, test:profile, test:plugins)'
task :test do
- errors = %w(test:units test:functionals test:integration).collect do |task|
+ tests_to_run = ENV['TEST'] ? ["test:single"] : %w(test:units test:functionals test:integration)
+ errors = tests_to_run.collect do |task|
begin
Rake::Task[task].invoke
nil
@@ -123,6 +124,10 @@ namespace :test do
end
Rake::Task['test:uncommitted'].comment = "Test changes since last checkin (only Subversion and Git)"
+ Rake::TestTask.new(:single => "test:prepare") do |t|
+ t.libs << "test"
+ end
+
TestTaskWithoutDescription.new(:units => "test:prepare") do |t|
t.libs << "test"
t.pattern = 'test/unit/**/*_test.rb'
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index 7403d16cf4..b8d0854286 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -42,7 +42,7 @@ module ApplicationTests
test "Rails::Application responds to paths" do
require "#{app_path}/config/environment"
assert_respond_to AppTemplate::Application, :paths
- assert_equal AppTemplate::Application.paths.app.views.to_a, ["#{app_path}/app/views"]
+ assert_equal AppTemplate::Application.paths["app/views"].expanded, ["#{app_path}/app/views"]
end
test "the application root is set correctly" do
@@ -180,7 +180,7 @@ module ApplicationTests
test "config.paths.public sets Rails.public_path" do
add_to_config <<-RUBY
- config.paths.public = "somewhere"
+ config.paths["public"] = "somewhere"
RUBY
require "#{app_path}/config/application"
diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb
index 25b4a21902..d4159dd0fd 100644
--- a/railties/test/application/console_test.rb
+++ b/railties/test/application/console_test.rb
@@ -1,7 +1,7 @@
require 'isolation/abstract_unit'
class ConsoleTest < Test::Unit::TestCase
- include ActiveSupport::Testing::Isolation
+ include ActiveSupport::Testing::Isolation
def setup
build_app
@@ -14,16 +14,15 @@ class ConsoleTest < Test::Unit::TestCase
end
def test_app_method_should_return_integration_session
+ TestHelpers::Rack.send :remove_method, :app
load_environment
console_session = app
- assert_not_nil console_session
assert_instance_of ActionDispatch::Integration::Session, console_session
end
def test_new_session_should_return_integration_session
load_environment
session = new_session
- assert_not_nil session
assert_instance_of ActionDispatch::Integration::Session, session
end
diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb
index d258625f42..551e966c85 100644
--- a/railties/test/application/generators_test.rb
+++ b/railties/test/application/generators_test.rb
@@ -69,7 +69,7 @@ module ApplicationTests
assert_equal :rspec, Rails::Generators.options[:rails][:test_framework]
assert_equal "-w", Rails::Generators.aliases[:rails][:test_framework]
assert_equal Hash[:shoulda => :test_unit], Rails::Generators.fallbacks
- assert_equal ["#{app_path}/lib/templates", "some/where"], Rails::Generators.templates_path
+ assert_equal ["some/where"], Rails::Generators.templates_path
end
test "generators no color on initialization" do
diff --git a/railties/test/application/paths_test.rb b/railties/test/application/paths_test.rb
index c98b11556b..b1ff6e9cb1 100644
--- a/railties/test/application/paths_test.rb
+++ b/railties/test/application/paths_test.rb
@@ -25,7 +25,7 @@ module ApplicationTests
end
def assert_path(paths, *dir)
- assert_equal [root(*dir)], paths.paths
+ assert_equal [root(*dir)], paths.expanded
end
def assert_in_load_path(*path)
@@ -37,20 +37,20 @@ module ApplicationTests
end
test "booting up Rails yields a valid paths object" do
- assert_path @paths.app.models, "app", "models"
- assert_path @paths.app.helpers, "app", "helpers"
- assert_path @paths.app.views, "app", "views"
- assert_path @paths.lib, "lib"
- assert_path @paths.vendor, "vendor"
- assert_path @paths.vendor.plugins, "vendor", "plugins"
- assert_path @paths.tmp, "tmp"
- assert_path @paths.tmp.cache, "tmp", "cache"
- assert_path @paths.config, "config"
- assert_path @paths.config.locales, "config", "locales", "en.yml"
- assert_path @paths.config.environment, "config", "environment.rb"
- assert_path @paths.config.environments, "config", "environments", "development.rb"
+ assert_path @paths["app/models"], "app/models"
+ assert_path @paths["app/helpers"], "app/helpers"
+ assert_path @paths["app/views"], "app/views"
+ assert_path @paths["lib"], "lib"
+ assert_path @paths["vendor"], "vendor"
+ assert_path @paths["vendor/plugins"], "vendor/plugins"
+ assert_path @paths["tmp"], "tmp"
+ assert_path @paths["tmp/cache"], "tmp/cache"
+ assert_path @paths["config"], "config"
+ assert_path @paths["config/locales"], "config/locales/en.yml"
+ assert_path @paths["config/environment"], "config/environment.rb"
+ assert_path @paths["config/environments"], "config/environments/development.rb"
- assert_equal root("app", "controllers"), @paths.app.controllers.to_a.first
+ assert_equal root("app", "controllers"), @paths["app/controllers"].expanded.first
end
test "booting up Rails yields a list of paths that are eager" do
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 3653b067c8..c7339cb8d2 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -165,9 +165,13 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "Gemfile", /^gem\s+["']mysql2["']$/
end
- def test_config_database_is_not_added_if_skip_active_record_is_given
+ def test_generator_if_skip_active_record_is_given
run_generator [destination_root, "--skip-active-record"]
assert_no_file "config/database.yml"
+ assert_file "test/test_helper.rb" do |helper_content|
+ assert_no_match /fixtures :all/, helper_content
+ end
+ assert_file "test/performance/browsing_test.rb"
end
def test_active_record_is_removed_from_frameworks_if_skip_active_record_is_given
@@ -183,14 +187,34 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "public/javascripts/rails.js"
assert_file "test"
end
-
- def test_prototype_and_test_unit_are_skipped_if_required
- run_generator [destination_root, "--skip-prototype", "--skip-test-unit"]
+
+ def test_test_unit_is_skipped_if_required
+ run_generator [destination_root, "--skip-test-unit"]
+ assert_no_file "test"
+ end
+
+ def test_javascript_is_skipped_if_required
+ run_generator [destination_root, "--skip-javascript"]
assert_file "config/application.rb", /^\s+config\.action_view\.javascript_expansions\[:defaults\]\s+=\s+%w\(\)/
assert_file "public/javascripts/application.js"
assert_no_file "public/javascripts/prototype.js"
assert_no_file "public/javascripts/rails.js"
- assert_no_file "test"
+ end
+
+ def test_config_prototype_javascript_library
+ run_generator [destination_root, "-j", "prototype"]
+ assert_file "config/application.rb", /#\s+config\.action_view\.javascript_expansions\[:defaults\]\s+=\s+%w\(jquery rails\)/
+ assert_file "public/javascripts/application.js"
+ assert_file "public/javascripts/prototype.js"
+ assert_file "public/javascripts/rails.js", /prototype/
+ end
+
+ def test_config_jquery_javascript_library
+ run_generator [destination_root, "-j", "jquery"]
+ assert_file "config/application.rb", /^\s+config\.action_view\.javascript_expansions\[:defaults\]\s+=\s+%w\(jquery rails\)/
+ assert_file "public/javascripts/application.js"
+ assert_file "public/javascripts/jquery.js"
+ assert_file "public/javascripts/rails.js", /jQuery/
end
def test_shebang_is_added_to_rails_file
diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb
index 38b95a49ac..d1190fd17d 100644
--- a/railties/test/generators/namespaced_generators_test.rb
+++ b/railties/test/generators/namespaced_generators_test.rb
@@ -6,14 +6,14 @@ require 'rails/generators/mailer/mailer_generator'
class NamespacedGeneratorTestCase < Rails::Generators::TestCase
def setup
- TestApp::Application.namespace(TestApp)
+ TestApp::Application.isolate_namespace(TestApp)
end
def teardown
if TestApp.respond_to?(:_railtie)
TestApp.singleton_class.send(:undef_method, :_railtie)
TestApp.singleton_class.send(:undef_method, :table_name_prefix)
- TestApp::Application.namespaced = false
+ TestApp::Application.isolated = false
end
end
end
diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb
index 80fae8c543..6e4e3446b3 100644
--- a/railties/test/paths_test.rb
+++ b/railties/test/paths_test.rb
@@ -20,234 +20,264 @@ class PathsTest < ActiveSupport::TestCase
test "a paths object initialized with nil can be updated" do
root = Rails::Paths::Root.new(nil)
- root.app = "app"
+ root.add "app"
root.path = "/root"
- assert_equal ["/root/app"], root.app.to_a
+ assert_equal ["app"], root["app"]
+ assert_equal ["/root/app"], root["app"].to_a
end
test "creating a root level path" do
- @root.app = "/foo/bar"
- assert_equal ["/foo/bar"], @root.app.to_a
+ @root.add "app"
+ assert_equal ["/foo/bar/app"], @root["app"].to_a
+ end
+
+ test "creating a root level path with options" do
+ @root.add "app", :with => "/foo/bar"
+ assert_equal ["/foo/bar"], @root["app"].to_a
end
test "raises exception if root path never set" do
root = Rails::Paths::Root.new(nil)
- root.app = "app"
+ root.add "app"
assert_raises RuntimeError do
- root.app.to_a
+ root["app"].to_a
end
end
- test "creating a root level path without assignment" do
- @root.app "/foo/bar"
- assert_equal ["/foo/bar"], @root.app.to_a
- end
-
- test "trying to access a path that does not exist raises NoMethodError" do
- assert_raises(NoMethodError) { @root.app }
- end
-
- test "relative paths are relative to the paths root" do
- @root.app = "app"
- assert_equal ["/foo/bar/app"], @root.app.to_a
- end
-
- test "relative paths are relative to the paths root without assignment" do
- @root.app "app"
- assert_equal ["/foo/bar/app"], @root.app.to_a
- end
-
test "creating a child level path" do
- @root.app = "/foo/bar"
- @root.app.models = "/foo/bar/baz"
- assert_equal ["/foo/bar/baz"], @root.app.models.to_a
+ @root.add "app"
+ @root.add "app/models"
+ assert_equal ["/foo/bar/app/models"], @root["app/models"].to_a
end
- test "creating a child level path without assignment" do
- @root.app = "/foo/bar"
- @root.app.models "/foo/bar/baz"
- assert_equal ["/foo/bar/baz"], @root.app.models.to_a
+ test "creating a child level path with option" do
+ @root.add "app"
+ @root.add "app/models", :with => "/foo/bar/baz"
+ assert_equal ["/foo/bar/baz"], @root["app/models"].to_a
end
test "child level paths are relative from the root" do
- @root.app = "/app"
- @root.app.models = "baz"
-
- assert_equal ["/foo/bar/baz"], @root.app.models.to_a
+ @root.add "app"
+ @root.add "app/models", :with => "baz"
+ assert_equal ["/foo/bar/baz"], @root["app/models"].to_a
end
test "adding multiple physical paths as an array" do
- @root.app = ["/app", "/app2"]
- assert_equal ["/app", "/app2"], @root.app.to_a
- end
-
- test "adding multiple physical paths as an array without assignment" do
- @root.app "/app", "/app2"
- assert_equal ["/app", "/app2"], @root.app.to_a
+ @root.add "app", :with => ["/app", "/app2"]
+ assert_equal ["/app", "/app2"], @root["app"].to_a
end
test "adding multiple physical paths using #push" do
- @root.app = "/app"
- @root.app.push "/app2"
- assert_equal ["/app", "/app2"], @root.app.to_a
+ @root.add "app"
+ @root["app"].push "app2"
+ assert_equal ["/foo/bar/app", "/foo/bar/app2"], @root["app"].to_a
end
test "adding multiple physical paths using <<" do
- @root.app = "/app"
- @root.app << "/app2"
- assert_equal ["/app", "/app2"], @root.app.to_a
+ @root.add "app"
+ @root["app"] << "app2"
+ assert_equal ["/foo/bar/app", "/foo/bar/app2"], @root["app"].to_a
end
test "adding multiple physical paths using concat" do
- @root.app = "/app"
- @root.app.concat ["/app2", "/app3"]
- assert_equal ["/app", "/app2", "/app3"], @root.app.to_a
+ @root.add "app"
+ @root["app"].concat ["app2", "/app3"]
+ assert_equal ["/foo/bar/app", "/foo/bar/app2", "/app3"], @root["app"].to_a
end
test "adding multiple physical paths using #unshift" do
- @root.app = "/app"
- @root.app.unshift "/app2"
- assert_equal ["/app2", "/app"], @root.app.to_a
+ @root.add "app"
+ @root["app"].unshift "app2"
+ assert_equal ["/foo/bar/app2", "/foo/bar/app"], @root["app"].to_a
end
test "the root can only have one physical path" do
assert_raise(RuntimeError) { Rails::Paths::Root.new(["/fiz", "/biz"]) }
- assert_raise(RuntimeError) { @root.push "/biz" }
- assert_raise(RuntimeError) { @root.unshift "/biz" }
- assert_raise(RuntimeError) { @root.concat ["/biz"]}
- assert_raise(RuntimeError) { @root << "/biz" }
end
test "it is possible to add a path that should be autoloaded only once" do
- @root.app = "/app"
- @root.app.autoload_once!
- assert @root.app.autoload_once?
- assert @root.autoload_once.include?(@root.app.paths.first)
+ @root.add "app", :with => "/app"
+ @root["app"].autoload_once!
+ assert @root["app"].autoload_once?
+ assert @root.autoload_once.include?(@root["app"].expanded.first)
end
test "it is possible to remove a path that should be autoloaded only once" do
- @root.app = "/app"
- @root.app.autoload_once!
- assert @root.app.autoload_once?
+ @root["app"] = "/app"
+ @root["app"].autoload_once!
+ assert @root["app"].autoload_once?
- @root.app.skip_autoload_once!
- assert !@root.app.autoload_once?
- assert !@root.autoload_once.include?(@root.app.paths.first)
+ @root["app"].skip_autoload_once!
+ assert !@root["app"].autoload_once?
+ assert !@root.autoload_once.include?(@root["app"].expanded.first)
end
test "it is possible to add a path without assignment and specify it should be loaded only once" do
- @root.app "/app", :autoload_once => true
- assert @root.app.autoload_once?
+ @root.add "app", :with => "/app", :autoload_once => true
+ assert @root["app"].autoload_once?
assert @root.autoload_once.include?("/app")
end
test "it is possible to add multiple paths without assignment and specify it should be loaded only once" do
- @root.app "/app", "/app2", :autoload_once => true
- assert @root.app.autoload_once?
+ @root.add "app", :with => ["/app", "/app2"], :autoload_once => true
+ assert @root["app"].autoload_once?
assert @root.autoload_once.include?("/app")
assert @root.autoload_once.include?("/app2")
end
test "making a path autoload_once more than once only includes it once in @root.load_once" do
- @root.app = "/app"
- @root.app.autoload_once!
- @root.app.autoload_once!
- assert_equal 1, @root.autoload_once.select {|p| p == @root.app.paths.first }.size
+ @root["app"] = "/app"
+ @root["app"].autoload_once!
+ @root["app"].autoload_once!
+ assert_equal 1, @root.autoload_once.select {|p| p == @root["app"].expanded.first }.size
end
test "paths added to a load_once path should be added to the autoload_once collection" do
- @root.app = "/app"
- @root.app.autoload_once!
- @root.app << "/app2"
+ @root["app"] = "/app"
+ @root["app"].autoload_once!
+ @root["app"] << "/app2"
assert_equal 2, @root.autoload_once.size
end
test "it is possible to mark a path as eager loaded" do
- @root.app = "/app"
- @root.app.eager_load!
- assert @root.app.eager_load?
- assert @root.eager_load.include?(@root.app.paths.first)
+ @root["app"] = "/app"
+ @root["app"].eager_load!
+ assert @root["app"].eager_load?
+ assert @root.eager_load.include?(@root["app"].to_a.first)
end
test "it is possible to skip a path from eager loading" do
- @root.app = "/app"
- @root.app.eager_load!
- assert @root.app.eager_load?
+ @root["app"] = "/app"
+ @root["app"].eager_load!
+ assert @root["app"].eager_load?
- @root.app.skip_eager_load!
- assert !@root.app.eager_load?
- assert !@root.eager_load.include?(@root.app.paths.first)
+ @root["app"].skip_eager_load!
+ assert !@root["app"].eager_load?
+ assert !@root.eager_load.include?(@root["app"].to_a.first)
end
test "it is possible to add a path without assignment and mark it as eager" do
- @root.app "/app", :eager_load => true
- assert @root.app.eager_load?
+ @root.add "app", :with => "/app", :eager_load => true
+ assert @root["app"].eager_load?
assert @root.eager_load.include?("/app")
end
test "it is possible to add multiple paths without assignment and mark them as eager" do
- @root.app "/app", "/app2", :eager_load => true
- assert @root.app.eager_load?
+ @root.add "app", :with => ["/app", "/app2"], :eager_load => true
+ assert @root["app"].eager_load?
assert @root.eager_load.include?("/app")
assert @root.eager_load.include?("/app2")
end
test "it is possible to create a path without assignment and mark it both as eager and load once" do
- @root.app "/app", :eager_load => true, :autoload_once => true
- assert @root.app.eager_load?
- assert @root.app.autoload_once?
+ @root.add "app", :with => "/app", :eager_load => true, :autoload_once => true
+ assert @root["app"].eager_load?
+ assert @root["app"].autoload_once?
assert @root.eager_load.include?("/app")
assert @root.autoload_once.include?("/app")
end
test "making a path eager more than once only includes it once in @root.eager_paths" do
- @root.app = "/app"
- @root.app.eager_load!
- @root.app.eager_load!
- assert_equal 1, @root.eager_load.select {|p| p == @root.app.paths.first }.size
+ @root["app"] = "/app"
+ @root["app"].eager_load!
+ @root["app"].eager_load!
+ assert_equal 1, @root.eager_load.select {|p| p == @root["app"].expanded.first }.size
end
test "paths added to a eager_load path should be added to the eager_load collection" do
- @root.app = "/app"
- @root.app.eager_load!
- @root.app << "/app2"
+ @root["app"] = "/app"
+ @root["app"].eager_load!
+ @root["app"] << "/app2"
assert_equal 2, @root.eager_load.size
end
test "it should be possible to add a path's default glob" do
- @root.app = "/app"
- @root.app.glob = "*.rb"
- assert_equal "*.rb", @root.app.glob
+ @root["app"] = "/app"
+ @root["app"].glob = "*.rb"
+ assert_equal "*.rb", @root["app"].glob
end
test "it should be possible to override a path's default glob without assignment" do
- @root.app "/app", :glob => "*.rb"
- assert_equal "*.rb", @root.app.glob
+ @root.add "app", :with => "/app", :glob => "*.rb"
+ assert_equal "*.rb", @root["app"].glob
end
test "a path can be added to the load path" do
- @root.app = "app"
- @root.app.load_path!
- @root.app.models = "app/models"
+ @root["app"] = "app"
+ @root["app"].load_path!
+ @root["app/models"] = "app/models"
assert_equal ["/foo/bar/app"], @root.load_paths
end
test "a path can be added to the load path on creation" do
- @root.app "/app", :load_path => true
- assert @root.app.load_path?
+ @root.add "app", :with => "/app", :load_path => true
+ assert @root["app"].load_path?
assert_equal ["/app"], @root.load_paths
end
test "a path can be marked as autoload path" do
- @root.app = "app"
- @root.app.autoload!
- @root.app.models = "app/models"
+ @root["app"] = "app"
+ @root["app"].autoload!
+ @root["app/models"] = "app/models"
assert_equal ["/foo/bar/app"], @root.autoload_paths
end
test "a path can be marked as autoload on creation" do
- @root.app "/app", :autoload => true
- assert @root.app.autoload?
+ @root.add "app", :with => "/app", :autoload => true
+ assert @root["app"].autoload?
assert_equal ["/app"], @root.autoload_paths
end
+
+ # Deprecated API tests
+
+ test "reading a root level path with assignment" do
+ @root.add "app"
+ assert_deprecated do
+ assert_equal ["/foo/bar/app"], @root.app.to_a
+ end
+ end
+
+ test "creating a root level path with assignment" do
+ assert_deprecated do
+ @root.app = "/foo/bar"
+ end
+ assert_equal ["/foo/bar"], @root["app"].to_a
+ end
+
+ test "creating a root level path without assignment" do
+ assert_deprecated do
+ @root.app "/foo/bar"
+ end
+ assert_equal ["/foo/bar"], @root["app"].to_a
+ end
+
+ test "reading a nested level path with assignment" do
+ @root.add "app"
+ @root.add "app/model"
+ assert_deprecated do
+ assert_equal ["/foo/bar/app/model"], @root.app.model.to_a
+ end
+ end
+
+ test "creating a nested level path with assignment" do
+ @root.add "app"
+ assert_deprecated do
+ @root.app.model = "/foo/bar"
+ end
+ assert_equal ["/foo/bar"], @root["app/model"].to_a
+ end
+
+ test "creating a nested level path without assignment" do
+ @root.add "app"
+ assert_deprecated do
+ @root.app.model "/foo/bar"
+ end
+ assert_equal ["/foo/bar"], @root["app/model"].to_a
+ end
+
+ test "trying to access a path that does not exist raises NoMethodError" do
+ assert_deprecated do
+ assert_raises(NoMethodError) { @root.app }
+ end
+ end
end
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 89262aeaae..4b52260ecc 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -62,17 +62,18 @@ module RailtiesTest
def call(env)
response = @app.call(env)
- response[2].upcase!
+ response[2].each { |b| b.upcase! }
response
end
end
test "engine is a rack app and can have his own middleware stack" do
+ add_to_config("config.action_dispatch.show_exceptions = false")
+
@plugin.write "lib/bukkits.rb", <<-RUBY
class Bukkits
class Engine < ::Rails::Engine
- endpoint lambda { |env| [200, {'Content-Type' => 'text/html'}, 'Hello World'] }
-
+ endpoint lambda { |env| [200, {'Content-Type' => 'text/html'}, ['Hello World']] }
config.middleware.use ::RailtiesTest::EngineTest::Upcaser
end
end
@@ -102,7 +103,7 @@ module RailtiesTest
@plugin.write "config/routes.rb", <<-RUBY
Bukkits::Engine.routes.draw do
- match "/foo" => lambda { |env| [200, {'Content-Type' => 'text/html'}, 'foo'] }
+ match "/foo" => lambda { |env| [200, {'Content-Type' => 'text/html'}, ['foo']] }
end
RUBY
@@ -393,7 +394,7 @@ module RailtiesTest
@plugin.write "lib/bukkits.rb", <<-RUBY
module Bukkits
class Engine < ::Rails::Engine
- namespace Bukkits
+ isolate_namespace Bukkits
end
end
RUBY
@@ -510,7 +511,7 @@ module RailtiesTest
@plugin.write "lib/bukkits.rb", <<-RUBY
module Bukkits
class Engine < ::Rails::Engine
- namespace Bukkits
+ isolate_namespace Bukkits
end
end
RUBY
@@ -552,11 +553,11 @@ module RailtiesTest
end
RUBY
- @plugin.write "app/views/bukkits/posts/new.html.erb", <<-RUBY
+ @plugin.write "app/views/bukkits/posts/new.html.erb", <<-ERB
<%= form_for(Bukkits::Post.new) do |f| %>
<%= f.text_field :title %>
<% end %>
- RUBY
+ ERB
add_to_config("config.action_dispatch.show_exceptions = false")
@@ -567,63 +568,6 @@ module RailtiesTest
assert rack_body(response[2]) =~ /name="post\[title\]"/
end
- test "creating symlinks" do
- @plugin.write "lib/bukkits.rb", <<-RUBY
- module Bukkits
- class Engine < ::Rails::Engine
- namespace(Bukkits)
- end
- end
- RUBY
-
- @plugin.write "public/hello.txt", "foo"
- @plugin.write "alternate_public/hello.txt", "bar"
-
- Dir.chdir(app_path) do
- output = `rake railties:create_symlinks`
-
- assert_match /Created symlink/, output
- assert_match /#{app_path}\/public\/bukkits/, output
- assert_match /#{@plugin.path}\/public/, output
-
- assert File.symlink?(File.join(app_path, 'public/bukkits'))
- assert_equal "foo\n", File.read(File.join(app_path, 'public/bukkits/hello.txt'))
-
- @plugin.write "lib/bukkits.rb", <<-RUBY
- module Bukkits
- class Engine < ::Rails::Engine
- namespace(Bukkits)
- config.paths.public = "#{File.join(@plugin.path, "alternate_public")}"
- end
- end
- RUBY
-
- output = `rake railties:create_symlinks`
-
- assert_match /Created symlink/, output
- assert_match /#{app_path}\/public\/bukkits/, output
- assert_match /#{@plugin.path}\/alternate_public/, output
-
- assert File.symlink?(File.join(app_path, 'public/bukkits'))
- assert_equal "bar\n", File.read(File.join(app_path, 'public/bukkits/hello.txt'))
-
- @plugin.write "lib/bukkits.rb", <<-RUBY
- module Bukkits
- class Engine < ::Rails::Engine
- namespace(Bukkits)
- config.paths.public = "#{File.join(@plugin.path, "not_existing")}"
- end
- end
- RUBY
-
- FileUtils.rm File.join(app_path, 'public/bukkits')
-
- output = `rake railties:create_symlinks`
- assert_no_match /Created symlink/, output
- assert !File.exist?(File.join(app_path, 'public/bukkits'))
- end
- end
-
test "loading seed data" do
@plugin.write "db/seeds.rb", <<-RUBY
Bukkits::Engine.config.bukkits_seeds_loaded = true
@@ -647,12 +591,12 @@ module RailtiesTest
@plugin.write "lib/bukkits.rb", <<-RUBY
module AppTemplate
class Engine < ::Rails::Engine
- namespace(AppTemplate)
+ isolate_namespace(AppTemplate)
end
end
RUBY
- add_to_config "namespace AppTemplate"
+ add_to_config "isolate_namespace AppTemplate"
app_file "config/routes.rb", <<-RUBY
AppTemplate::Application.routes.draw do end
@@ -685,7 +629,7 @@ module RailtiesTest
@plugin.write "lib/bukkits.rb", <<-RUBY
module Bukkits
class Engine < ::Rails::Engine
- namespace(Bukkits)
+ isolate_namespace(Bukkits)
end
end
RUBY
diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb
index b52ced92ec..47a4753e78 100644
--- a/railties/test/railties/mounted_engine_test.rb
+++ b/railties/test/railties/mounted_engine_test.rb
@@ -49,7 +49,7 @@ module ApplicationTests
@plugin.write "lib/blog.rb", <<-RUBY
module Blog
class Engine < ::Rails::Engine
- namespace(Blog)
+ isolate_namespace(Blog)
end
end
RUBY
diff --git a/railties/test/railties/plugin_test.rb b/railties/test/railties/plugin_test.rb
index bae05d6978..c15ac05103 100644
--- a/railties/test/railties/plugin_test.rb
+++ b/railties/test/railties/plugin_test.rb
@@ -110,7 +110,7 @@ module RailtiesTest
boot_rails
rescue Exception => e
rescued = true
- assert_equal '"bukkits" is a Railtie/Engine and cannot be installed as plugin', e.message
+ assert_equal '"bukkits" is a Railtie/Engine and cannot be installed as a plugin', e.message
end
assert rescued, "Expected boot rails to fail"
diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb
index 406d5d764f..6d194eecba 100644
--- a/railties/test/railties/railtie_test.rb
+++ b/railties/test/railties/railtie_test.rb
@@ -103,6 +103,30 @@ module RailtiesTest
assert $ran_block
end
+ test "rake_tasks block defined in superclass of railtie is also executed" do
+ $ran_block = []
+
+ class Rails::Railtie
+ rake_tasks do
+ $ran_block << railtie_name
+ end
+ end
+
+ class MyTie < Rails::Railtie
+ railtie_name "my_tie"
+ end
+
+ require "#{app_path}/config/environment"
+
+ assert_equal [], $ran_block
+ require 'rake'
+ require 'rake/testtask'
+ require 'rake/rdoctask'
+
+ AppTemplate::Application.load_tasks
+ assert $ran_block.include?("my_tie")
+ end
+
test "generators block is executed when MyApp.load_generators is called" do
$ran_block = false
diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb
index 9b62f88fd7..31ba2eaca2 100644
--- a/railties/test/railties/shared_tests.rb
+++ b/railties/test/railties/shared_tests.rb
@@ -10,6 +10,44 @@ module RailtiesTest
@app ||= Rails.application
end
+ def test_install_migrations_and_assets
+ @plugin.write "public/javascripts/foo.js", "doSomething()"
+
+ @plugin.write "db/migrate/1_create_users.rb", <<-RUBY
+ class CreateUsers < ActiveRecord::Migration
+ end
+ RUBY
+
+ app_file "db/migrate/1_create_sessions.rb", <<-RUBY
+ class CreateSessions < ActiveRecord::Migration
+ end
+ RUBY
+
+ add_to_config "ActiveRecord::Base.timestamped_migrations = false"
+
+ Dir.chdir(app_path) do
+ `rake bukkits:install`
+ assert File.exists?("#{app_path}/db/migrate/2_create_users.rb")
+ assert File.exists?(app_path("public/bukkits/javascripts/foo.js"))
+ end
+ end
+
+ def test_copying_assets
+ @plugin.write "public/javascripts/foo.js", "doSomething()"
+ @plugin.write "public/stylesheets/foo.css", "h1 { font-size: 10000px }"
+ @plugin.write "public/images/img.png", ""
+
+ Dir.chdir(app_path) do
+ `rake bukkits:install:assets --trace`
+
+ assert File.exists?(app_path("public/bukkits/javascripts/foo.js"))
+ assert_equal "doSomething()\n", File.read(app_path("public/bukkits/javascripts/foo.js"))
+ assert File.exists?(app_path("public/bukkits/stylesheets/foo.css"))
+ assert_equal "h1 { font-size: 10000px }\n", File.read(app_path("public/bukkits/stylesheets/foo.css"))
+ assert File.exists?(app_path("public/bukkits/images/img.png"))
+ end
+ end
+
def test_copying_migrations
@plugin.write "db/migrate/1_create_users.rb", <<-RUBY
class CreateUsers < ActiveRecord::Migration
@@ -21,6 +59,11 @@ module RailtiesTest
end
RUBY
+ @plugin.write "db/migrate/3_create_sessions.rb", <<-RUBY
+ class CreateSessions < ActiveRecord::Migration
+ end
+ RUBY
+
app_file "db/migrate/1_create_sessions.rb", <<-RUBY
class CreateSessions < ActiveRecord::Migration
end
@@ -38,24 +81,26 @@ module RailtiesTest
add_to_config "ActiveRecord::Base.timestamped_migrations = false"
Dir.chdir(app_path) do
- output = `rake railties:copy_migrations FROM=bukkits`
+ output = `rake bukkits:install:migrations`
- assert File.exists?("#{app_path}/db/migrate/2_create_users.bukkits.rb")
- assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.bukkits.rb")
- assert_match /2_create_users/, output
- assert_match /3_add_last_name_to_users/, output
+ assert File.exists?("#{app_path}/db/migrate/2_create_users.rb")
+ assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.rb")
+ assert_match /Copied migration 2_create_users.rb from bukkits/, output
+ assert_match /Copied migration 3_add_last_name_to_users.rb from bukkits/, output
+ assert_match /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output
assert_equal 3, Dir["#{app_path}/db/migrate/*.rb"].length
- output = `rake railties:copy_migrations`
+ output = `rake railties:install:migrations`
- assert File.exists?("#{app_path}/db/migrate/4_create_yaffles.acts_as_yaffle.rb")
- assert_match /4_create_yaffles/, output
+ assert File.exists?("#{app_path}/db/migrate/4_create_yaffles.rb")
+ assert_match /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output
+ assert_match /Copied migration 4_create_yaffles.rb from acts_as_yaffle/, output
+ assert_no_match /2_create_users/, output
migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length
- output = `rake railties:copy_migrations`
+ output = `rake railties:install:migrations`
assert_equal migrations_count, Dir["#{app_path}/db/migrate/*.rb"].length
- assert_match /No migrations were copied/, output
end
end