aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--Gemfile2
-rw-r--r--Rakefile56
-rw-r--r--actionmailer/CHANGELOG4
-rw-r--r--actionmailer/lib/action_mailer/version.rb4
-rw-r--r--actionpack/CHANGELOG4
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb32
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb3
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb250
-rw-r--r--actionpack/lib/action_dispatch/routing/route.rb3
-rw-r--r--actionpack/lib/action_pack/version.rb4
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helper.rb501
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb133
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb153
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb173
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb144
-rw-r--r--actionpack/lib/action_view/helpers/date_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb21
-rw-r--r--actionpack/lib/action_view/helpers/text_helper.rb18
-rw-r--r--actionpack/lib/action_view/railtie.rb4
-rw-r--r--actionpack/lib/action_view/renderer/partial_renderer.rb7
-rw-r--r--actionpack/test/activerecord/active_record_store_test.rb20
-rw-r--r--actionpack/test/controller/action_pack_assertions_test.rb8
-rw-r--r--actionpack/test/controller/filters_test.rb81
-rw-r--r--actionpack/test/controller/routing_test.rb8
-rw-r--r--actionpack/test/dispatch/request_test.rb3
-rw-r--r--actionpack/test/fixtures/layouts/_partial_and_yield.erb2
-rw-r--r--actionpack/test/fixtures/layouts/_yield_only.erb1
-rw-r--r--actionpack/test/fixtures/layouts/_yield_with_params.erb1
-rw-r--r--actionpack/test/fixtures/layouts/yield_with_render_partial_inside.erb2
-rw-r--r--actionpack/test/fixtures/test/_partial_with_layout.erb2
-rw-r--r--actionpack/test/fixtures/test/_partial_with_layout_block_content.erb4
-rw-r--r--actionpack/test/fixtures/test/_partial_with_layout_block_partial.erb4
-rw-r--r--actionpack/test/fixtures/test/_partial_with_partial.erb2
-rw-r--r--actionpack/test/lib/controller/fake_models.rb10
-rw-r--r--actionpack/test/template/asset_tag_helper_test.rb16
-rw-r--r--actionpack/test/template/date_helper_test.rb41
-rw-r--r--actionpack/test/template/form_helper_test.rb21
-rw-r--r--actionpack/test/template/render_test.rb45
-rw-r--r--activemodel/CHANGELOG4
-rw-r--r--activemodel/lib/active_model/attribute_methods.rb10
-rw-r--r--activemodel/lib/active_model/version.rb4
-rw-r--r--activerecord/CHANGELOG29
-rw-r--r--activerecord/activerecord.gemspec2
-rw-r--r--activerecord/lib/active_record/aggregations.rb2
-rw-r--r--activerecord/lib/active_record/associations.rb2
-rw-r--r--activerecord/lib/active_record/associations/association_collection.rb50
-rw-r--r--activerecord/lib/active_record/associations/association_proxy.rb10
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_association.rb6
-rw-r--r--activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb2
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb5
-rw-r--r--activerecord/lib/active_record/associations/has_one_association.rb12
-rw-r--r--activerecord/lib/active_record/associations/has_one_through_association.rb2
-rw-r--r--activerecord/lib/active_record/attribute_methods/primary_key.rb7
-rw-r--r--activerecord/lib/active_record/autosave_association.rb14
-rw-r--r--activerecord/lib/active_record/base.rb28
-rw-r--r--activerecord/lib/active_record/locking/optimistic.rb2
-rw-r--r--activerecord/lib/active_record/locking/pessimistic.rb2
-rw-r--r--activerecord/lib/active_record/migration.rb2
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb2
-rw-r--r--activerecord/lib/active_record/persistence.rb11
-rw-r--r--activerecord/lib/active_record/railtie.rb2
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb39
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb2
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb5
-rw-r--r--activerecord/lib/active_record/session_store.rb9
-rw-r--r--activerecord/lib/active_record/transactions.rb12
-rw-r--r--activerecord/lib/active_record/validations.rb2
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb2
-rw-r--r--activerecord/lib/active_record/version.rb4
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb12
-rw-r--r--activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb2
-rw-r--r--activerecord/test/cases/associations/eager_test.rb12
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb32
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb60
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb7
-rw-r--r--activerecord/test/cases/associations/has_one_associations_test.rb4
-rw-r--r--activerecord/test/cases/associations/inverse_associations_test.rb4
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb16
-rw-r--r--activerecord/test/cases/associations_test.rb2
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb2
-rw-r--r--activerecord/test/cases/autosave_association_test.rb92
-rw-r--r--activerecord/test/cases/base_test.rb24
-rw-r--r--activerecord/test/cases/calculations_test.rb13
-rw-r--r--activerecord/test/cases/finder_test.rb54
-rw-r--r--activerecord/test/cases/fixtures_test.rb6
-rw-r--r--activerecord/test/cases/migration_test.rb23
-rw-r--r--activerecord/test/cases/named_scope_test.rb2
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb24
-rw-r--r--activerecord/test/cases/persistence_test.rb12
-rw-r--r--activerecord/test/cases/query_cache_test.rb1
-rw-r--r--activerecord/test/cases/relation_scoping_test.rb2
-rw-r--r--activerecord/test/cases/relations_test.rb35
-rw-r--r--activerecord/test/cases/session_store/sql_bypass.rb4
-rw-r--r--activerecord/test/cases/timestamp_test.rb2
-rw-r--r--activerecord/test/cases/transactions_test.rb18
-rw-r--r--activerecord/test/cases/validations/association_validation_test.rb4
-rw-r--r--activerecord/test/cases/validations/uniqueness_validation_test.rb4
-rw-r--r--activerecord/test/models/eye.rb2
-rw-r--r--activerecord/test/models/pirate.rb2
-rw-r--r--activerecord/test/models/subject.rb2
-rw-r--r--activerecord/test/models/topic.rb2
-rw-r--r--activeresource/CHANGELOG4
-rw-r--r--activeresource/lib/active_resource/version.rb4
-rw-r--r--activesupport/CHANGELOG4
-rw-r--r--activesupport/lib/active_support/core_ext/cgi.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb19
-rw-r--r--activesupport/lib/active_support/core_ext/hash.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/hash/deep_dup.rb11
-rw-r--r--activesupport/lib/active_support/core_ext/object/instance_variables.rb31
-rw-r--r--activesupport/lib/active_support/core_ext/object/try.rb14
-rw-r--r--activesupport/lib/active_support/hash_with_indifferent_access.rb2
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb2
-rw-r--r--activesupport/lib/active_support/version.rb4
-rw-r--r--activesupport/lib/active_support/xml_mini/nokogirisax.rb3
-rw-r--r--activesupport/test/core_ext/cgi_ext_test.rb15
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb32
-rw-r--r--activesupport/test/core_ext/object_and_class_ext_test.rb41
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb11
-rw-r--r--rails.gemspec2
-rw-r--r--railties/CHANGELOG4
-rw-r--r--railties/guides/source/action_controller_overview.textile9
-rw-r--r--railties/guides/source/action_mailer_basics.textile4
-rw-r--r--railties/guides/source/active_support_core_extensions.textile39
-rw-r--r--railties/guides/source/api_documentation_guidelines.textile14
-rw-r--r--railties/guides/source/configuring.textile6
-rw-r--r--railties/guides/source/debugging_rails_applications.textile8
-rw-r--r--railties/guides/source/form_helpers.textile30
-rw-r--r--railties/guides/source/getting_started.textile8
-rw-r--r--railties/guides/source/initialization.textile10
-rw-r--r--railties/guides/source/layouts_and_rendering.textile2
-rw-r--r--railties/guides/source/plugins.textile2
-rw-r--r--railties/guides/source/routing.textile20
-rw-r--r--railties/lib/rails/application.rb1
-rw-r--r--railties/lib/rails/cli.rb10
-rw-r--r--railties/lib/rails/commands.rb20
-rw-r--r--railties/lib/rails/commands/plugin_new.rb10
-rw-r--r--railties/lib/rails/configuration.rb8
-rw-r--r--railties/lib/rails/engine.rb7
-rw-r--r--railties/lib/rails/engine/configuration.rb1
-rw-r--r--railties/lib/rails/generators/app_base.rb176
-rw-r--r--railties/lib/rails/generators/named_base.rb39
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb137
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile21
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js984
-rw-r--r--railties/lib/rails/generators/rails/plugin/plugin_generator.rb7
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/USAGE10
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb249
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec9
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/Gemfile11
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE20
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/README.rdoc3
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/Rakefile18
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt4
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt4
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb3
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/gitignore6
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb6
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb7
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake4
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb16
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb10
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb4
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/script/rails.tt5
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb7
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb11
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb15
-rw-r--r--railties/lib/rails/generators/rails/resource/resource_generator.rb4
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb2
-rw-r--r--railties/lib/rails/generators/resource_helpers.rb6
-rw-r--r--railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb2
-rw-r--r--railties/lib/rails/info.rb1
-rw-r--r--railties/lib/rails/version.rb4
-rw-r--r--railties/test/application/generators_test.rb12
-rw-r--r--railties/test/application/rake_test.rb9
-rw-r--r--railties/test/fixtures/lib/app_builders/empty_builder.rb (renamed from railties/test/fixtures/lib/empty_builder.rb)0
-rw-r--r--railties/test/fixtures/lib/app_builders/simple_builder.rb7
-rw-r--r--railties/test/fixtures/lib/app_builders/tweak_builder.rb7
-rw-r--r--railties/test/fixtures/lib/create_test_dummy_template.rb1
-rw-r--r--railties/test/fixtures/lib/plugin_builders/empty_builder.rb2
-rw-r--r--railties/test/fixtures/lib/plugin_builders/simple_builder.rb7
-rw-r--r--railties/test/fixtures/lib/plugin_builders/spec_builder.rb19
-rw-r--r--railties/test/fixtures/lib/plugin_builders/tweak_builder.rb7
-rw-r--r--railties/test/fixtures/lib/simple_builder.rb7
-rw-r--r--railties/test/fixtures/lib/tweak_builder.rb7
-rw-r--r--railties/test/generators/app_generator_test.rb171
-rw-r--r--railties/test/generators/namespaced_generators_test.rb153
-rw-r--r--railties/test/generators/plugin_generator_test.rb18
-rw-r--r--railties/test/generators/plugin_new_generator_test.rb196
-rw-r--r--railties/test/generators/resource_generator_test.rb5
-rw-r--r--railties/test/generators/shared_generator_tests.rb187
-rw-r--r--railties/test/railties/engine_test.rb56
-rw-r--r--release.rb11
-rw-r--r--tasks/release.rb96
-rw-r--r--version.rb4
196 files changed, 3968 insertions, 1793 deletions
diff --git a/.gitignore b/.gitignore
index 2dfdf96e7f..a18fba3780 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,6 +13,7 @@ activesupport/doc
activemodel/test/fixtures/fixture_database.sqlite3
actionpack/test/tmp
activesupport/test/fixtures/isolation_test
+dist
railties/test/500.html
railties/test/fixtures/tmp
railties/test/initializer/root/log
diff --git a/Gemfile b/Gemfile
index 3aaf9a6123..4e13331626 100644
--- a/Gemfile
+++ b/Gemfile
@@ -39,7 +39,7 @@ end
platforms :ruby do
gem 'json'
gem 'yajl-ruby'
- gem "nokogiri", ">= 1.4.3.1"
+ gem "nokogiri", ">= 1.4.4"
# AR
gem "sqlite3-ruby", "~> 1.3.1", :require => 'sqlite3'
diff --git a/Rakefile b/Rakefile
index 5065fb286b..7dc884f27b 100644
--- a/Rakefile
+++ b/Rakefile
@@ -3,7 +3,16 @@ require 'rdoc'
require 'rake'
require 'rdoc/task'
-require 'rake/gempackagetask'
+require 'net/http'
+
+$:.unshift File.expand_path('..', __FILE__)
+require "tasks/release"
+
+desc "Build gem files for all projects"
+task :build => "all:build"
+
+desc "Release all gems to gemcutter and create a tag"
+task :release => "all:release"
# RDoc skips some files in the Rails tree due to its binary? predicate. This is a quick
# hack for edge docs, until we decide which is the correct way to address this issue.
@@ -54,27 +63,6 @@ task :smoke do
system %(cd activerecord && #{$0} sqlite3:isolated_test)
end
-spec = eval(File.read('rails.gemspec'))
-Rake::GemPackageTask.new(spec) do |pkg|
- pkg.gem_spec = spec
-end
-
-desc "Release all gems to gemcutter. Package rails, package & push components, then push rails"
-task :release => :release_projects do
- require 'rake/gemcutter'
- Rake::Gemcutter::Tasks.new(spec).define
- Rake::Task['gem:push'].invoke
-end
-
-desc "Release all components to gemcutter."
-task :release_projects => :package do
- errors = []
- PROJECTS.each do |project|
- system(%(cd #{project} && #{$0} release)) || errors << project
- end
- fail("Errors in #{errors.join(', ')}") unless errors.empty?
-end
-
desc "Install gems for all projects."
task :install => :gem do
version = File.read("RAILS_VERSION").strip
@@ -172,3 +160,27 @@ task :update_versions do
end
end
end
+
+#
+# We have a webhook configured in Github that gets invoked after pushes.
+# This hook triggers the following tasks:
+#
+# * updates the local checkout
+# * updates Rails Contributors
+# * generates and publishes edge docs
+# * if there's a new stable tag, generates and publishes stable docs
+#
+# Everything is automated and you do NOT need to run this task normally.
+#
+# We publish a new verion by tagging, and pushing a tag does not trigger
+# that webhook. Stable docs would be updated by any subsequent regular
+# push, but if you want that to happen right away just run this.
+#
+desc 'Publishes docs, run this AFTER a new stable tag has been pushed'
+task :publish_docs do
+ Net::HTTP.new('rails-hooks.hashref.com').start do |http|
+ request = Net::HTTP::Post.new('/rails-master-hook')
+ response = http.request(request)
+ puts response.body
+ end
+end
diff --git a/actionmailer/CHANGELOG b/actionmailer/CHANGELOG
index 9c073dce1f..167c1da9c5 100644
--- a/actionmailer/CHANGELOG
+++ b/actionmailer/CHANGELOG
@@ -2,6 +2,10 @@
* No changes
+*Rails 3.0.2 (unreleased)*
+
+* No changes
+
*Rails 3.0.1 (October 15, 2010)*
* No Changes, just a version bump.
diff --git a/actionmailer/lib/action_mailer/version.rb b/actionmailer/lib/action_mailer/version.rb
index 7dd3d401b1..27eb6c2b9b 100644
--- a/actionmailer/lib/action_mailer/version.rb
+++ b/actionmailer/lib/action_mailer/version.rb
@@ -3,8 +3,8 @@ module ActionMailer
MAJOR = 3
MINOR = 1
TINY = 0
- BUILD = "beta"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
index 2d133ca0b2..db02beee35 100644
--- a/actionpack/CHANGELOG
+++ b/actionpack/CHANGELOG
@@ -23,6 +23,10 @@
* Add Rack::Cache to the default stack. Create a Rails store that delegates to the Rails cache, so by default, whatever caching layer you are using will be used for HTTP caching. Note that Rack::Cache will be used if you use #expires_in, #fresh_when or #stale with :public => true. Otherwise, the caching rules will apply to the browser only. [Yehuda Katz, Carl Lerche]
+*Rails 3.0.2 (unreleased)*
+
+* The helper number_to_currency accepts a new :negative_format option to be able to configure how to render negative amounts. [Don Wilson]
+
*Rails 3.0.1 (October 15, 2010)*
* No Changes, just a version bump.
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index 7b0d80614d..f169ab7c3a 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -81,27 +81,29 @@ module AbstractController
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
# Append a before, after or around filter. See _insert_callbacks
# for details on the allowed parameters.
- def #{filter}_filter(*names, &blk) # def before_filter(*names, &blk)
- _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options}
- set_callback(:process_action, :#{filter}, name, options) # set_callback(:process_action, :before_filter, name, options)
- end # end
- end # end
+ def #{filter}_filter(*names, &blk)
+ _insert_callbacks(names, blk) do |name, options|
+ options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after}
+ set_callback(:process_action, :#{filter}, name, options)
+ end
+ end
# Prepend a before, after or around filter. See _insert_callbacks
# for details on the allowed parameters.
- def prepend_#{filter}_filter(*names, &blk) # def prepend_before_filter(*names, &blk)
- _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
- set_callback(:process_action, :#{filter}, name, options.merge(:prepend => true)) # set_callback(:process_action, :before, name, options.merge(:prepend => true))
- end # end
- end # end
+ def prepend_#{filter}_filter(*names, &blk)
+ _insert_callbacks(names, blk) do |name, options|
+ options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after}
+ set_callback(:process_action, :#{filter}, name, options.merge(:prepend => true))
+ end
+ end
# Skip a before, after or around filter. See _insert_callbacks
# for details on the allowed parameters.
- def skip_#{filter}_filter(*names, &blk) # def skip_before_filter(*names, &blk)
- _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
- skip_callback(:process_action, :#{filter}, name, options) # skip_callback(:process_action, :before, name, options)
- end # end
- end # end
+ def skip_#{filter}_filter(*names, &blk)
+ _insert_callbacks(names, blk) do |name, options|
+ skip_callback(:process_action, :#{filter}, name, options)
+ end
+ end
# *_filter is the same as append_*_filter
alias_method :append_#{filter}_filter, :#{filter}_filter
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index 4da82f958a..9c9eed2c6d 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -2,6 +2,7 @@ module ActionDispatch
module Http
module URL
mattr_accessor :tld_length
+ self.tld_length = 1
# Returns the complete URL used for this request.
def url
@@ -67,7 +68,7 @@ module ActionDispatch
# Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify
# a different <tt>tld_length</tt>, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk".
- def domain(tld_length = 1)
+ def domain(tld_length = @@tld_length)
return nil unless named_host?(host)
host.split('.').last(1 + tld_length).join('.')
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index 1bbb4f1f92..879ccc5791 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -66,6 +66,18 @@ module ActionDispatch
end
@options.merge!(default_controller_and_action(to_shorthand))
+
+ requirements.each do |name, requirement|
+ # segment_keys.include?(k.to_s) || k == :controller
+ next unless Regexp === requirement && !constraints[name]
+
+ if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
+ raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
+ end
+ if requirement.multiline?
+ raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
+ end
+ end
end
# match "account/overview"
@@ -113,15 +125,6 @@ module ActionDispatch
@requirements ||= (@options[:constraints].is_a?(Hash) ? @options[:constraints] : {}).tap do |requirements|
requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints]
@options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) }
-
- requirements.each do |_, requirement|
- if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
- raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
- end
- if requirement.multiline?
- raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
- end
- end
end
end
@@ -164,10 +167,10 @@ module ActionDispatch
raise ArgumentError, "missing :action"
end
- { :controller => controller, :action => action }.tap do |hash|
- hash.delete(:controller) if hash[:controller].blank?
- hash.delete(:action) if hash[:action].blank?
- end
+ hash = {}
+ hash[:controller] = controller unless controller.blank?
+ hash[:action] = action unless action.blank?
+ hash
end
end
@@ -263,6 +266,23 @@ module ActionDispatch
self
end
+ # Mount a Rack-based application to be used within the application.
+ #
+ # mount SomeRackApp, :at => "some_route"
+ #
+ # Alternatively:
+ #
+ # mount(SomeRackApp => "some_route")
+ #
+ # All mounted applications come with routing helpers to access them.
+ # These are named after the class specified, so for the above example
+ # the helper is either +some_rack_app_path+ or +some_rack_app_url+.
+ # To customize this helper's name, use the +:as+ option:
+ #
+ # mount(SomeRackApp => "some_route", :as => "exciting")
+ #
+ # This will generate the +exciting_path+ and +exciting_url+ helpers
+ # which can be used to navigate to this mounted app.
def mount(app, options = nil)
if options
path = options.delete(:at)
@@ -324,21 +344,41 @@ module ActionDispatch
module HttpHelpers
# Define a route that only recognizes HTTP GET.
+ # For supported arguments, see +match+.
+ #
+ # Example:
+ #
+ # get 'bacon', :to => 'food#bacon'
def get(*args, &block)
map_method(:get, *args, &block)
end
# Define a route that only recognizes HTTP POST.
+ # For supported arguments, see +match+.
+ #
+ # Example:
+ #
+ # post 'bacon', :to => 'food#bacon'
def post(*args, &block)
map_method(:post, *args, &block)
end
# Define a route that only recognizes HTTP PUT.
+ # For supported arguments, see +match+.
+ #
+ # Example:
+ #
+ # put 'bacon', :to => 'food#bacon'
def put(*args, &block)
map_method(:put, *args, &block)
end
- # Define a route that only recognizes HTTP DELETE.
+ # Define a route that only recognizes HTTP PUT.
+ # For supported arguments, see +match+.
+ #
+ # Example:
+ #
+ # delete 'broccoli', :to => 'food#broccoli'
def delete(*args, &block)
map_method(:delete, *args, &block)
end
@@ -407,22 +447,22 @@ module ActionDispatch
# PUT /admin/photos/1
# DELETE /admin/photos/1
#
- # If you want to route /photos (without the prefix /admin) to
+ # If you want to route /posts (without the prefix /admin) to
# Admin::PostsController, you could use
#
# scope :module => "admin" do
- # resources :posts, :comments
+ # resources :posts
# end
#
# or, for a single case
#
# resources :posts, :module => "admin"
#
- # If you want to route /admin/photos to PostsController
+ # If you want to route /admin/posts to PostsController
# (without the Admin:: module prefix), you could use
#
# scope "/admin" do
- # resources :posts, :comments
+ # resources :posts
# end
#
# or, for a single case
@@ -448,10 +488,51 @@ module ActionDispatch
# Used to route <tt>/photos</tt> (without the prefix <tt>/admin</tt>)
# to Admin::PostsController:
+ # === Supported options
+ # [:module]
+ # If you want to route /posts (without the prefix /admin) to
+ # Admin::PostsController, you could use
#
- # scope :module => "admin" do
- # resources :posts
- # end
+ # scope :module => "admin" do
+ # resources :posts
+ # end
+ #
+ # [:path]
+ # If you want to prefix the route, you could use
+ #
+ # scope :path => "/admin" do
+ # resources :posts
+ # end
+ #
+ # This will prefix all of the +posts+ resource's requests with '/admin'
+ #
+ # [:as]
+ # Prefixes the routing helpers in this scope with the specified label.
+ #
+ # scope :as => "sekret" do
+ # resources :posts
+ # end
+ #
+ # Helpers such as +posts_path+ will now be +sekret_posts_path+
+ #
+ # [:shallow_path]
+ #
+ # Prefixes nested shallow routes with the specified path.
+ #
+ # scope :shallow_path => "sekret" do
+ # resources :posts do
+ # resources :comments, :shallow => true
+ # end
+ #
+ # The +comments+ resource here will have the following routes generated for it:
+ #
+ # post_comments GET /sekret/posts/:post_id/comments(.:format)
+ # post_comments POST /sekret/posts/:post_id/comments(.:format)
+ # new_post_comment GET /sekret/posts/:post_id/comments/new(.:format)
+ # edit_comment GET /sekret/comments/:id/edit(.:format)
+ # comment GET /sekret/comments/:id(.:format)
+ # comment PUT /sekret/comments/:id(.:format)
+ # comment DELETE /sekret/comments/:id(.:format)
def scope(*args)
options = args.extract_options!
options = options.dup
@@ -488,22 +569,139 @@ module ActionDispatch
@scope[:blocks] = recover[:block]
end
+ # Scopes routes to a specific controller
+ #
+ # Example:
+ # controller "food" do
+ # match "bacon", :action => "bacon"
+ # end
def controller(controller, options={})
options[:controller] = controller
scope(options) { yield }
end
+ # Scopes routes to a specific namespace. For example:
+ #
+ # namespace :admin do
+ # resources :posts
+ # end
+ #
+ # This generates the following routes:
+ #
+ # admin_posts GET /admin/posts(.:format) {:action=>"index", :controller=>"admin/posts"}
+ # admin_posts POST /admin/posts(.:format) {:action=>"create", :controller=>"admin/posts"}
+ # new_admin_post GET /admin/posts/new(.:format) {:action=>"new", :controller=>"admin/posts"}
+ # edit_admin_post GET /admin/posts/:id/edit(.:format) {:action=>"edit", :controller=>"admin/posts"}
+ # admin_post GET /admin/posts/:id(.:format) {:action=>"show", :controller=>"admin/posts"}
+ # admin_post PUT /admin/posts/:id(.:format) {:action=>"update", :controller=>"admin/posts"}
+ # admin_post DELETE /admin/posts/:id(.:format) {:action=>"destroy", :controller=>"admin/posts"}
+ # === Supported options
+ #
+ # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ all default to the name of the namespace.
+ #
+ # [:path]
+ # The path prefix for the routes.
+ #
+ # namespace :admin, :path => "sekret" do
+ # resources :posts
+ # end
+ #
+ # All routes for the above +resources+ will be accessible through +/sekret/posts+, rather than +/admin/posts+
+ #
+ # [:module]
+ # The namespace for the controllers.
+ #
+ # namespace :admin, :module => "sekret" do
+ # resources :posts
+ # end
+ #
+ # The +PostsController+ here should go in the +Sekret+ namespace and so it should be defined like this:
+ #
+ # class Sekret::PostsController < ApplicationController
+ # # code go here
+ # end
+ #
+ # [:as]
+ # Changes the name used in routing helpers for this namespace.
+ #
+ # namespace :admin, :as => "sekret" do
+ # resources :posts
+ # end
+ #
+ # Routing helpers such as +admin_posts_path+ will now be +sekret_posts_path+.
+ #
+ # [:shallow_path]
+ # See the +scope+ method.
def namespace(path, options = {})
path = path.to_s
options = { :path => path, :as => path, :module => path,
:shallow_path => path, :shallow_prefix => path }.merge!(options)
scope(options) { yield }
end
-
+
+ # === Parameter Restriction
+ # Allows you to constrain the nested routes based on a set of rules.
+ # For instance, in order to change the routes to allow for a dot character in the +id+ parameter:
+ #
+ # constraints(:id => /\d+\.\d+) do
+ # resources :posts
+ # end
+ #
+ # Now routes such as +/posts/1+ will no longer be valid, but +/posts/1.1+ will be.
+ # The +id+ parameter must match the constraint passed in for this example.
+ #
+ # You may use this to also resrict other parameters:
+ #
+ # resources :posts do
+ # constraints(:post_id => /\d+\.\d+) do
+ # resources :comments
+ # end
+ #
+ # === Restricting based on IP
+ #
+ # Routes can also be constrained to an IP or a certain range of IP addresses:
+ #
+ # constraints(:ip => /192.168.\d+.\d+/) do
+ # resources :posts
+ # end
+ #
+ # Any user connecting from the 192.168.* range will be able to see this resource,
+ # where as any user connecting outside of this range will be told there is no such route.
+ #
+ # === Dynamic request matching
+ #
+ # Requests to routes can be constrained based on specific critera:
+ #
+ # constraints(lambda { |req| req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do
+ # resources :iphones
+ # end
+ #
+ # You are able to move this logic out into a class if it is too complex for routes.
+ # This class must have a +matches?+ method defined on it which either returns +true+
+ # if the user should be given access to that route, or +false+ if the user should not.
+ #
+ # class Iphone
+ # def self.matches(request)
+ # request.env["HTTP_USER_AGENT"] =~ /iPhone/
+ # end
+ # end
+ #
+ # An expected place for this code would be +lib/constraints+.
+ #
+ # This class is then used like this:
+ #
+ # constraints(Iphone) do
+ # resources :iphones
+ # end
def constraints(constraints = {})
scope(:constraints => constraints) { yield }
end
+ # Allows you to set default parameters for a route, such as this:
+ # defaults :id => 'home' do
+ # match 'scoped_pages/(:id)', :to => 'pages#show'
+ # end
+ # Using this, the +:id+ parameter here will default to 'home'.
def defaults(defaults = {})
scope(:defaults => defaults) { yield }
end
@@ -771,6 +969,14 @@ module ActionDispatch
# GET /photos/:id/edit
# PUT /photos/:id
# DELETE /photos/:id
+ # === Supported options
+ # [:path_names]
+ # Allows you to change the paths of the seven default actions.
+ # Paths not specified are not changed.
+ #
+ # resources :posts, :path_names => { :new => "brand_new" }
+ #
+ # The above example will now change /posts/new to /posts/brand_new
def resources(*resources, &block)
options = resources.extract_options!
diff --git a/actionpack/lib/action_dispatch/routing/route.rb b/actionpack/lib/action_dispatch/routing/route.rb
index f91a48e16c..08a8408f25 100644
--- a/actionpack/lib/action_dispatch/routing/route.rb
+++ b/actionpack/lib/action_dispatch/routing/route.rb
@@ -30,7 +30,8 @@ module ActionDispatch
if method = conditions[:request_method]
case method
when Regexp
- method.source.upcase
+ source = method.source.upcase
+ source =~ /\A\^[-A-Z|]+\$\Z/ ? source[1..-2] : source
else
method.to_s.upcase
end
diff --git a/actionpack/lib/action_pack/version.rb b/actionpack/lib/action_pack/version.rb
index 73e16daa29..170ceb299a 100644
--- a/actionpack/lib/action_pack/version.rb
+++ b/actionpack/lib/action_pack/version.rb
@@ -3,8 +3,8 @@ module ActionPack
MAJOR = 3
MINOR = 1
TINY = 0
- BUILD = "beta"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
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 a728fde748..f6b2d4f3f4 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
@@ -1,10 +1,6 @@
-require 'thread'
-require 'cgi'
-require 'action_view/helpers/url_helper'
-require 'action_view/helpers/tag_helper'
-require 'active_support/core_ext/file'
-require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/string/output_safety'
+require 'action_view/helpers/asset_tag_helpers/javascript_tag_helpers'
+require 'action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers'
+require 'action_view/helpers/asset_tag_helpers/asset_paths'
module ActionView
# = Action View Asset Tag Helpers
@@ -195,20 +191,8 @@ module ActionView
# RewriteEngine On
# RewriteRule ^/release-\d+/(images|javascripts|stylesheets)/(.*)$ /$1/$2 [L]
module AssetTagHelper
- mattr_reader :javascript_expansions
- @@javascript_expansions = { }
-
- mattr_reader :stylesheet_expansions
- @@stylesheet_expansions = {}
-
- # You can enable or disable the asset tag timestamps cache.
- # With the cache enabled, the asset tag helper methods will make fewer
- # expensive file system calls. However this prevents you from modifying
- # any asset files while the server is running.
- #
- # ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false
- mattr_accessor :cache_asset_timestamps
-
+ include JavascriptTagHelpers
+ include StylesheetTagHelpers
# Returns a link tag that browsers and news readers can use to auto-detect
# an RSS or ATOM feed. The +type+ can either be <tt>:rss</tt> (default) or
# <tt>:atom</tt>. Control the link options in url_for format using the
@@ -242,260 +226,6 @@ module ActionView
)
end
- # Computes the path to a javascript asset in the public javascripts directory.
- # If the +source+ filename has no extension, .js will be appended (except for explicit URIs)
- # Full paths from the document root will be passed through.
- # Used internally by javascript_include_tag to build the script path.
- #
- # ==== Examples
- # javascript_path "xmlhr" # => /javascripts/xmlhr.js
- # javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js
- # javascript_path "/dir/xmlhr" # => /dir/xmlhr.js
- # javascript_path "http://www.railsapplication.com/js/xmlhr" # => http://www.railsapplication.com/js/xmlhr
- # javascript_path "http://www.railsapplication.com/js/xmlhr.js" # => http://www.railsapplication.com/js/xmlhr.js
- def javascript_path(source)
- compute_public_path(source, 'javascripts', 'js')
- end
- alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
-
- # Returns an HTML script tag for each of the +sources+ provided. You
- # can pass in the filename (.js extension is optional) of JavaScript files
- # that exist in your <tt>public/javascripts</tt> directory for inclusion into the
- # current page or you can pass the full path relative to your document
- # root. To include the Prototype and Scriptaculous JavaScript libraries in
- # your application, pass <tt>:defaults</tt> as the source. When using
- # <tt>:defaults</tt>, if an <tt>application.js</tt> file exists in
- # <tt>public/javascripts</tt> it will be included as well. You can modify the
- # HTML attributes of the script tag by passing a hash as the last argument.
- #
- # ==== Examples
- # javascript_include_tag "xmlhr" # =>
- # <script type="text/javascript" src="/javascripts/xmlhr.js?1284139606"></script>
- #
- # javascript_include_tag "xmlhr.js" # =>
- # <script type="text/javascript" src="/javascripts/xmlhr.js?1284139606"></script>
- #
- # javascript_include_tag "common.javascript", "/elsewhere/cools" # =>
- # <script type="text/javascript" src="/javascripts/common.javascript?1284139606"></script>
- # <script type="text/javascript" src="/elsewhere/cools.js?1423139606"></script>
- #
- # javascript_include_tag "http://www.railsapplication.com/xmlhr" # =>
- # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js?1284139606"></script>
- #
- # javascript_include_tag "http://www.railsapplication.com/xmlhr.js" # =>
- # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js?1284139606"></script>
- #
- # javascript_include_tag :defaults # =>
- # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
- # <script type="text/javascript" src="/javascripts/effects.js?1284139606"></script>
- # ...
- # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
- #
- # * = The application.js file is only referenced if it exists
- #
- # You can also include all javascripts in the +javascripts+ directory using <tt>:all</tt> as the source:
- #
- # javascript_include_tag :all # =>
- # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
- # <script type="text/javascript" src="/javascripts/effects.js?1284139606"></script>
- # ...
- # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
- # <script type="text/javascript" src="/javascripts/shop.js?1284139606"></script>
- # <script type="text/javascript" src="/javascripts/checkout.js?1284139606"></script>
- #
- # Note that the default javascript files will be included first. So Prototype and Scriptaculous are available to
- # all subsequently included files.
- #
- # If you want Rails to search in all the subdirectories under javascripts, you should explicitly set <tt>:recursive</tt>:
- #
- # javascript_include_tag :all, :recursive => true
- #
- # == Caching multiple javascripts into one
- #
- # You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be
- # compressed by gzip (leading to faster transfers). Caching will only happen if config.perform_caching
- # is set to <tt>true</tt> (which is the case by default for the Rails production environment, but not for the development
- # environment).
- #
- # ==== Examples
- # javascript_include_tag :all, :cache => true # when config.perform_caching is false =>
- # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
- # <script type="text/javascript" src="/javascripts/effects.js?1284139606"></script>
- # ...
- # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
- # <script type="text/javascript" src="/javascripts/shop.js?1284139606"></script>
- # <script type="text/javascript" src="/javascripts/checkout.js?1284139606"></script>
- #
- # javascript_include_tag :all, :cache => true # when config.perform_caching is true =>
- # <script type="text/javascript" src="/javascripts/all.js?1344139789"></script>
- #
- # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when config.perform_caching is false =>
- # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
- # <script type="text/javascript" src="/javascripts/cart.js?1289139157"></script>
- # <script type="text/javascript" src="/javascripts/checkout.js?1299139816"></script>
- #
- # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when config.perform_caching is true =>
- # <script type="text/javascript" src="/javascripts/shop.js?1299139816"></script>
- #
- # The <tt>:recursive</tt> option is also available for caching:
- #
- # javascript_include_tag :all, :cache => true, :recursive => true
- def javascript_include_tag(*sources)
- options = sources.extract_options!.stringify_keys
- concat = options.delete("concat")
- cache = concat || options.delete("cache")
- recursive = options.delete("recursive")
-
- if concat || (config.perform_caching && cache)
- joined_javascript_name = (cache == true ? "all" : cache) + ".js"
- joined_javascript_path = File.join(joined_javascript_name[/^#{File::SEPARATOR}/] ? config.assets_dir : config.javascripts_dir, joined_javascript_name)
-
- unless config.perform_caching && File.exists?(joined_javascript_path)
- write_asset_file_contents(joined_javascript_path, compute_javascript_paths(sources, recursive))
- end
- javascript_src_tag(joined_javascript_name, options)
- else
- sources = expand_javascript_sources(sources, recursive)
- ensure_javascript_sources!(sources) if cache
- sources.collect { |source| javascript_src_tag(source, options) }.join("\n").html_safe
- end
- end
-
- # Register one or more javascript files to be included when <tt>symbol</tt>
- # is passed to <tt>javascript_include_tag</tt>. This method is typically intended
- # to be called from plugin initialization to register javascript files
- # that the plugin installed in <tt>public/javascripts</tt>.
- #
- # ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
- #
- # javascript_include_tag :monkey # =>
- # <script type="text/javascript" src="/javascripts/head.js"></script>
- # <script type="text/javascript" src="/javascripts/body.js"></script>
- # <script type="text/javascript" src="/javascripts/tail.js"></script>
- def self.register_javascript_expansion(expansions)
- @@javascript_expansions.merge!(expansions)
- end
-
- # Register one or more stylesheet files to be included when <tt>symbol</tt>
- # is passed to <tt>stylesheet_link_tag</tt>. This method is typically intended
- # to be called from plugin initialization to register stylesheet files
- # that the plugin installed in <tt>public/stylesheets</tt>.
- #
- # ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
- #
- # stylesheet_link_tag :monkey # =>
- # <link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
- def self.register_stylesheet_expansion(expansions)
- @@stylesheet_expansions.merge!(expansions)
- end
-
- # Computes the path to a stylesheet asset in the public stylesheets directory.
- # If the +source+ filename has no extension, <tt>.css</tt> will be appended (except for explicit URIs).
- # Full paths from the document root will be passed through.
- # Used internally by +stylesheet_link_tag+ to build the stylesheet path.
- #
- # ==== Examples
- # stylesheet_path "style" # => /stylesheets/style.css
- # stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css
- # stylesheet_path "/dir/style.css" # => /dir/style.css
- # stylesheet_path "http://www.railsapplication.com/css/style" # => http://www.railsapplication.com/css/style
- # stylesheet_path "http://www.railsapplication.com/css/style.css" # => http://www.railsapplication.com/css/style.css
- def stylesheet_path(source)
- compute_public_path(source, 'stylesheets', 'css')
- end
- alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
-
- # Returns a stylesheet link tag for the sources specified as arguments. If
- # you don't specify an extension, <tt>.css</tt> will be appended automatically.
- # You can modify the link attributes by passing a hash as the last argument.
- #
- # ==== Examples
- # stylesheet_link_tag "style" # =>
- # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "style.css" # =>
- # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "http://www.railsapplication.com/style.css" # =>
- # <link href="http://www.railsapplication.com/style.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "style", :media => "all" # =>
- # <link href="/stylesheets/style.css" media="all" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "style", :media => "print" # =>
- # <link href="/stylesheets/style.css" media="print" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "random.styles", "/css/stylish" # =>
- # <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # You can also include all styles in the stylesheets directory using <tt>:all</tt> as the source:
- #
- # stylesheet_link_tag :all # =>
- # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # If you want Rails to search in all the subdirectories under stylesheets, you should explicitly set <tt>:recursive</tt>:
- #
- # stylesheet_link_tag :all, :recursive => true
- #
- # == Caching multiple stylesheets into one
- #
- # You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be
- # compressed by gzip (leading to faster transfers). Caching will only happen if config.perform_caching
- # is set to true (which is the case by default for the Rails production environment, but not for the development
- # environment). Examples:
- #
- # ==== Examples
- # stylesheet_link_tag :all, :cache => true # when config.perform_caching is false =>
- # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag :all, :cache => true # when config.perform_caching is true =>
- # <link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is false =>
- # <link href="/stylesheets/shop.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/cart.css" media="screen" rel="stylesheet" type="text/css" />
- # <link href="/stylesheets/checkout.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is true =>
- # <link href="/stylesheets/payment.css" media="screen" rel="stylesheet" type="text/css" />
- #
- # The <tt>:recursive</tt> option is also available for caching:
- #
- # stylesheet_link_tag :all, :cache => true, :recursive => true
- #
- # To force concatenation (even in development mode) set <tt>:concat</tt> to true. This is useful if
- # you have too many stylesheets for IE to load.
- #
- # stylesheet_link_tag :all, :concat => true
- #
- def stylesheet_link_tag(*sources)
- options = sources.extract_options!.stringify_keys
- concat = options.delete("concat")
- cache = concat || options.delete("cache")
- recursive = options.delete("recursive")
-
- if concat || (config.perform_caching && cache)
- joined_stylesheet_name = (cache == true ? "all" : cache) + ".css"
- joined_stylesheet_path = File.join(joined_stylesheet_name[/^#{File::SEPARATOR}/] ? config.assets_dir : config.stylesheets_dir, joined_stylesheet_name)
-
- unless config.perform_caching && File.exists?(joined_stylesheet_path)
- write_asset_file_contents(joined_stylesheet_path, compute_stylesheet_paths(sources, recursive))
- end
- stylesheet_tag(joined_stylesheet_name, options)
- else
- sources = expand_stylesheet_sources(sources, recursive)
- ensure_stylesheet_sources!(sources) if cache
- sources.collect { |source| stylesheet_tag(source, options) }.join("\n").html_safe
- end
- end
-
# Web browsers cache favicons. If you just throw a <tt>favicon.ico</tt> into the document
# root of your application and it changes later, clients that have it in their cache
# won't see the update. Using this helper prevents that because it appends an asset ID:
@@ -544,7 +274,7 @@ module ActionView
# The alias +path_to_image+ is provided to avoid that. Rails uses the alias internally, and
# plugin authors are encouraged to do so.
def image_path(source)
- compute_public_path(source, 'images')
+ asset_paths.compute_public_path(source, 'images')
end
alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
@@ -559,7 +289,7 @@ module ActionView
# video_path("/trailers/hd.avi") # => /trailers/hd.avi
# video_path("http://www.railsapplication.com/vid/hd.avi") # => http://www.railsapplication.com/vid/hd.avi
def video_path(source)
- compute_public_path(source, 'videos')
+ asset_paths.compute_public_path(source, 'videos')
end
alias_method :path_to_video, :video_path # aliased to avoid conflicts with a video_path named route
@@ -569,12 +299,12 @@ module ActionView
#
# ==== Examples
# audio_path("horse") # => /audios/horse
- # audio_path("horse.wav") # => /audios/horse.avi
- # audio_path("sounds/horse.wav") # => /audios/sounds/horse.avi
- # audio_path("/sounds/horse.wav") # => /sounds/horse.avi
+ # audio_path("horse.wav") # => /audios/horse.wav
+ # audio_path("sounds/horse.wav") # => /audios/sounds/horse.wav
+ # audio_path("/sounds/horse.wav") # => /sounds/horse.wav
# audio_path("http://www.railsapplication.com/sounds/horse.wav") # => http://www.railsapplication.com/sounds/horse.wav
def audio_path(source)
- compute_public_path(source, 'audios')
+ asset_paths.compute_public_path(source, 'audios')
end
alias_method :path_to_audio, :audio_path # aliased to avoid conflicts with an audio_path named route
@@ -703,213 +433,8 @@ module ActionView
private
- def rewrite_extension(source, dir, ext)
- source_ext = File.extname(source)
-
- if source_ext.empty?
- "#{source}.#{ext}"
- elsif ext != source_ext[1..-1]
- with_ext = "#{source}.#{ext}"
- with_ext if File.exist?(File.join(config.assets_dir, dir, with_ext))
- end || source
- end
-
- def rewrite_host_and_protocol(source, has_request)
- host = compute_asset_host(source)
- if has_request && host && !is_uri?(host)
- host = "#{controller.request.protocol}#{host}"
- end
- "#{host}#{source}"
- end
-
- def rewrite_relative_url_root(source, relative_url_root)
- relative_url_root && !source.starts_with?("#{relative_url_root}/") ? "#{relative_url_root}#{source}" : source
- end
-
- # Add the the extension +ext+ if not present. Return full URLs otherwise untouched.
- # Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL
- # roots. Rewrite the asset path for cache-busting asset ids. Include
- # asset host, if configured, with the correct request protocol.
- def compute_public_path(source, dir, ext = nil, include_host = true)
- return source if is_uri?(source)
-
- source = rewrite_extension(source, dir, ext) if ext
- source = "/#{dir}/#{source}" unless source[0] == ?/
- if controller.respond_to?(:env) && controller.env["action_dispatch.asset_path"]
- source = rewrite_asset_path(source, controller.env["action_dispatch.asset_path"])
- end
- source = rewrite_asset_path(source, config.asset_path)
-
- has_request = controller.respond_to?(:request)
- source = rewrite_relative_url_root(source, controller.config.relative_url_root) if has_request && include_host
- source = rewrite_host_and_protocol(source, has_request) if include_host
-
- source
- end
-
- def is_uri?(path)
- path =~ %r{^[-a-z]+://|^cid:}
- end
-
- # Pick an asset host for this source. Returns +nil+ if no host is set,
- # the host if no wildcard is set, the host interpolated with the
- # numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4),
- # or the value returned from invoking the proc if it's a proc or the value from
- # invoking call if it's an object responding to call.
- def compute_asset_host(source)
- if host = config.asset_host
- if host.is_a?(Proc) || host.respond_to?(:call)
- case host.is_a?(Proc) ? host.arity : host.method(:call).arity
- when 2
- request = controller.respond_to?(:request) && controller.request
- host.call(source, request)
- else
- host.call(source)
- end
- else
- (host =~ /%d/) ? host % (source.hash % 4) : host
- end
- end
- end
-
- @@asset_timestamps_cache = {}
- @@asset_timestamps_cache_guard = Mutex.new
-
- # Use the RAILS_ASSET_ID environment variable or the source's
- # modification time as its cache-busting asset id.
- def rails_asset_id(source)
- if asset_id = ENV["RAILS_ASSET_ID"]
- asset_id
- else
- if @@cache_asset_timestamps && (asset_id = @@asset_timestamps_cache[source])
- asset_id
- else
- path = File.join(config.assets_dir, source)
- asset_id = File.exist?(path) ? File.mtime(path).to_i.to_s : ''
-
- if @@cache_asset_timestamps
- @@asset_timestamps_cache_guard.synchronize do
- @@asset_timestamps_cache[source] = asset_id
- end
- end
-
- asset_id
- end
- end
- end
-
- # Break out the asset path rewrite in case plugins wish to put the asset id
- # someplace other than the query string.
- def rewrite_asset_path(source, path = nil)
- if path && path.respond_to?(:call)
- return path.call(source)
- elsif path && path.is_a?(String)
- return path % [source]
- end
-
- asset_id = rails_asset_id(source)
- if asset_id.empty?
- source
- else
- "#{source}?#{asset_id}"
- end
- end
-
- def javascript_src_tag(source, options)
- content_tag("script", "", { "type" => Mime::JS, "src" => path_to_javascript(source) }.merge(options))
- end
-
- def stylesheet_tag(source, options)
- tag("link", { "rel" => "stylesheet", "type" => Mime::CSS, "media" => "screen", "href" => ERB::Util.html_escape(path_to_stylesheet(source)) }.merge(options), false, false)
- end
-
- def compute_javascript_paths(*args)
- expand_javascript_sources(*args).collect { |source| compute_public_path(source, 'javascripts', 'js', false) }
- end
-
- def compute_stylesheet_paths(*args)
- expand_stylesheet_sources(*args).collect { |source| compute_public_path(source, 'stylesheets', 'css', false) }
- end
-
- def expand_javascript_sources(sources, recursive = false)
- if sources.include?(:all)
- all_javascript_files = (collect_asset_files(config.javascripts_dir, ('**' if recursive), '*.js') - ['application']) << 'application'
- ((determine_source(:defaults, @@javascript_expansions).dup & all_javascript_files) + all_javascript_files).uniq
- else
- expanded_sources = sources.collect do |source|
- determine_source(source, @@javascript_expansions)
- end.flatten
- expanded_sources << "application" if sources.include?(:defaults) && File.exist?(File.join(config.javascripts_dir, "application.js"))
- expanded_sources
- end
- end
-
- def expand_stylesheet_sources(sources, recursive)
- if sources.first == :all
- collect_asset_files(config.stylesheets_dir, ('**' if recursive), '*.css')
- else
- sources.collect do |source|
- determine_source(source, @@stylesheet_expansions)
- end.flatten
- end
- end
-
- def determine_source(source, collection)
- case source
- when Symbol
- collection[source] || raise(ArgumentError, "No expansion found for #{source.inspect}")
- else
- source
- end
- end
-
- def ensure_stylesheet_sources!(sources)
- sources.each do |source|
- asset_file_path!(path_to_stylesheet(source))
- end
- return sources
- end
-
- def ensure_javascript_sources!(sources)
- sources.each do |source|
- asset_file_path!(path_to_javascript(source))
- end
- return sources
- end
-
- def join_asset_file_contents(paths)
- paths.collect { |path| File.read(asset_file_path!(path)) }.join("\n\n")
- end
-
- def write_asset_file_contents(joined_asset_path, asset_paths)
-
- FileUtils.mkdir_p(File.dirname(joined_asset_path))
- File.atomic_write(joined_asset_path) { |cache| cache.write(join_asset_file_contents(asset_paths)) }
-
- # Set mtime to the latest of the combined files to allow for
- # consistent ETag without a shared filesystem.
- mt = asset_paths.map { |p| File.mtime(asset_file_path(p)) }.max
- File.utime(mt, mt, joined_asset_path)
- end
-
- def asset_file_path(path)
- File.join(config.assets_dir, path.split('?').first)
- end
-
- def asset_file_path!(path)
- unless is_uri?(path)
- absolute_path = asset_file_path(path)
- raise(Errno::ENOENT, "Asset file not found at '#{absolute_path}'" ) unless File.exist?(absolute_path)
- return absolute_path
- end
- end
-
- def collect_asset_files(*path)
- dir = path.first
-
- Dir[File.join(*path.compact)].collect do |file|
- file[-(file.size - dir.size - 1)..-1].sub(/\.\w+$/, '')
- end.sort
+ def asset_paths
+ @asset_paths ||= AssetPaths.new(config, controller)
end
end
end
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb
new file mode 100644
index 0000000000..3bc81ae068
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb
@@ -0,0 +1,133 @@
+require 'active_support/core_ext/class/attribute'
+require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/file'
+require 'action_view/helpers/tag_helper'
+
+module ActionView
+ module Helpers
+ module AssetTagHelper
+
+ class AssetIncludeTag
+ attr_reader :config, :asset_paths
+
+ class_attribute :expansions
+ self.expansions = { }
+
+ def initialize(config, asset_paths)
+ @config = config
+ @asset_paths = asset_paths
+ end
+
+ def asset_name
+ raise NotImplementedError
+ end
+
+ def extension
+ raise NotImplementedError
+ end
+
+ def custom_dir
+ raise NotImplementedError
+ end
+
+ def asset_tag(source, options)
+ raise NotImplementedError
+ end
+
+ def include_tag(*sources)
+ options = sources.extract_options!.stringify_keys
+ concat = options.delete("concat")
+ cache = concat || options.delete("cache")
+ recursive = options.delete("recursive")
+
+ if concat || (config.perform_caching && cache)
+ joined_name = (cache == true ? "all" : cache) + ".#{extension}"
+ joined_path = File.join((joined_name[/^#{File::SEPARATOR}/] ? config.assets_dir : custom_dir), joined_name)
+ unless config.perform_caching && File.exists?(joined_path)
+ write_asset_file_contents(joined_path, compute_paths(sources, recursive))
+ end
+ asset_tag(joined_name, options)
+ else
+ sources = expand_sources(sources, recursive)
+ ensure_sources!(sources) if cache
+ sources.collect { |source| asset_tag(source, options) }.join("\n").html_safe
+ end
+ end
+
+
+ private
+
+ def path_to_asset(source)
+ asset_paths.compute_public_path(source, asset_name.to_s.pluralize, extension)
+ end
+
+ def compute_paths(*args)
+ expand_sources(*args).collect { |source| asset_paths.compute_public_path(source, asset_name.pluralize, extension, false) }
+ end
+
+ def expand_sources(sources, recursive)
+ if sources.first == :all
+ collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}")
+ else
+ sources.collect do |source|
+ determine_source(source, expansions)
+ end.flatten
+ end
+ end
+
+ def ensure_sources!(sources)
+ sources.each do |source|
+ asset_file_path!(path_to_asset(source))
+ end
+ return sources
+ end
+
+ def collect_asset_files(*path)
+ dir = path.first
+
+ Dir[File.join(*path.compact)].collect do |file|
+ file[-(file.size - dir.size - 1)..-1].sub(/\.\w+$/, '')
+ end.sort
+ end
+
+ def determine_source(source, collection)
+ case source
+ when Symbol
+ collection[source] || raise(ArgumentError, "No expansion found for #{source.inspect}")
+ else
+ source
+ end
+ end
+
+ def join_asset_file_contents(paths)
+ paths.collect { |path| File.read(asset_file_path!(path, true)) }.join("\n\n")
+ end
+
+ def write_asset_file_contents(joined_asset_path, asset_paths)
+ FileUtils.mkdir_p(File.dirname(joined_asset_path))
+ File.atomic_write(joined_asset_path) { |cache| cache.write(join_asset_file_contents(asset_paths)) }
+
+ # Set mtime to the latest of the combined files to allow for
+ # consistent ETag without a shared filesystem.
+ mt = asset_paths.map { |p| File.mtime(asset_file_path(p)) }.max
+ File.utime(mt, mt, joined_asset_path)
+ end
+
+ def asset_file_path(path)
+ File.join(config.assets_dir, path.split('?').first)
+ end
+
+ def asset_file_path!(path, error_if_file_is_uri = false)
+ if asset_paths.is_uri?(path)
+ raise(Errno::ENOENT, "Asset file #{path} is uri and cannot be merged into single file") if error_if_file_is_uri
+ else
+ absolute_path = asset_file_path(path)
+ raise(Errno::ENOENT, "Asset file not found at '#{absolute_path}'" ) unless File.exist?(absolute_path)
+ return absolute_path
+ end
+ end
+ end
+
+ end
+ end
+end
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb
new file mode 100644
index 0000000000..b4e61f2034
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb
@@ -0,0 +1,153 @@
+require 'active_support/core_ext/file'
+
+module ActionView
+ module Helpers
+ module AssetTagHelper
+
+ class AssetPaths
+ # You can enable or disable the asset tag ids cache.
+ # With the cache enabled, the asset tag helper methods will make fewer
+ # expensive file system calls (the default implementation checks the file
+ # system timestamp). However this prevents you from modifying any asset
+ # files while the server is running.
+ #
+ # ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false
+ mattr_accessor :cache_asset_ids
+
+ attr_reader :config, :controller
+
+ def initialize(config, controller)
+ @config = config
+ @controller = controller
+ end
+
+ # Add the the extension +ext+ if not present. Return full URLs otherwise untouched.
+ # Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL
+ # roots. Rewrite the asset path for cache-busting asset ids. Include
+ # asset host, if configured, with the correct request protocol.
+ def compute_public_path(source, dir, ext = nil, include_host = true)
+ return source if is_uri?(source)
+
+ source = rewrite_extension(source, dir, ext) if ext
+ source = "/#{dir}/#{source}" unless source[0] == ?/
+ if controller.respond_to?(:env) && controller.env["action_dispatch.asset_path"]
+ source = rewrite_asset_path(source, controller.env["action_dispatch.asset_path"])
+ end
+ source = rewrite_asset_path(source, config.asset_path)
+
+ has_request = controller.respond_to?(:request)
+ source = rewrite_relative_url_root(source, controller.config.relative_url_root) if has_request && include_host
+ source = rewrite_host_and_protocol(source, has_request) if include_host
+
+ source
+ end
+
+ # Add or change an asset id in the asset id cache. This can be used
+ # for SASS on Heroku.
+ # :api: public
+ def add_to_asset_ids_cache(source, asset_id)
+ self.asset_ids_cache_guard.synchronize do
+ self.asset_ids_cache[source] = asset_id
+ end
+ end
+
+ def is_uri?(path)
+ path =~ %r{^[-a-z]+://|^cid:}
+ end
+
+ private
+
+ def rewrite_extension(source, dir, ext)
+ source_ext = File.extname(source)
+
+ source_with_ext = if source_ext.empty?
+ "#{source}.#{ext}"
+ elsif ext != source_ext[1..-1]
+ with_ext = "#{source}.#{ext}"
+ with_ext if File.exist?(File.join(config.assets_dir, dir, with_ext))
+ end
+
+ source_with_ext || source
+ end
+
+ # Break out the asset path rewrite in case plugins wish to put the asset id
+ # someplace other than the query string.
+ def rewrite_asset_path(source, path = nil)
+ if path && path.respond_to?(:call)
+ return path.call(source)
+ elsif path && path.is_a?(String)
+ return path % [source]
+ end
+
+ asset_id = rails_asset_id(source)
+ if asset_id.empty?
+ source
+ else
+ "#{source}?#{asset_id}"
+ end
+ end
+
+ mattr_accessor :asset_ids_cache
+ self.asset_ids_cache = {}
+
+ mattr_accessor :asset_ids_cache_guard
+ self.asset_ids_cache_guard = Mutex.new
+
+ # Use the RAILS_ASSET_ID environment variable or the source's
+ # modification time as its cache-busting asset id.
+ def rails_asset_id(source)
+ if asset_id = ENV["RAILS_ASSET_ID"]
+ asset_id
+ else
+ if self.cache_asset_ids && (asset_id = self.asset_ids_cache[source])
+ asset_id
+ else
+ path = File.join(config.assets_dir, source)
+ asset_id = File.exist?(path) ? File.mtime(path).to_i.to_s : ''
+
+ if self.cache_asset_ids
+ add_to_asset_ids_cache(source, asset_id)
+ end
+
+ asset_id
+ end
+ end
+ end
+
+ def rewrite_relative_url_root(source, relative_url_root)
+ relative_url_root && !source.starts_with?("#{relative_url_root}/") ? "#{relative_url_root}#{source}" : source
+ end
+
+ def rewrite_host_and_protocol(source, has_request)
+ host = compute_asset_host(source)
+ if has_request && host && !is_uri?(host)
+ host = "#{controller.request.protocol}#{host}"
+ end
+ "#{host}#{source}"
+ end
+
+ # Pick an asset host for this source. Returns +nil+ if no host is set,
+ # the host if no wildcard is set, the host interpolated with the
+ # numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4),
+ # or the value returned from invoking the proc if it's a proc or the value from
+ # invoking call if it's an object responding to call.
+ def compute_asset_host(source)
+ if host = config.asset_host
+ if host.is_a?(Proc) || host.respond_to?(:call)
+ case host.is_a?(Proc) ? host.arity : host.method(:call).arity
+ when 2
+ request = controller.respond_to?(:request) && controller.request
+ host.call(source, request)
+ else
+ host.call(source)
+ end
+ else
+ (host =~ /%d/) ? host % (source.hash % 4) : host
+ end
+ end
+ end
+ end
+
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb
new file mode 100644
index 0000000000..6581e1d6f2
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb
@@ -0,0 +1,173 @@
+require 'active_support/concern'
+require 'active_support/core_ext/file'
+require 'action_view/helpers/tag_helper'
+require 'action_view/helpers/asset_tag_helpers/asset_include_tag'
+
+module ActionView
+ module Helpers
+ module AssetTagHelper
+
+ class JavascriptIncludeTag < AssetIncludeTag
+ include TagHelper
+
+ def asset_name
+ 'javascript'
+ end
+
+ def extension
+ 'js'
+ end
+
+ def asset_tag(source, options)
+ content_tag("script", "", { "type" => Mime::JS, "src" => path_to_asset(source) }.merge(options))
+ end
+
+ def custom_dir
+ config.javascripts_dir
+ end
+
+ private
+
+ def expand_sources(sources, recursive = false)
+ if sources.include?(:all)
+ all_asset_files = (collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") - ['application']) << 'application'
+ ((determine_source(:defaults, expansions).dup & all_asset_files) + all_asset_files).uniq
+ else
+ expanded_sources = sources.collect do |source|
+ determine_source(source, expansions)
+ end.flatten
+ expanded_sources << "application" if sources.include?(:defaults) && File.exist?(File.join(custom_dir, "application.#{extension}"))
+ expanded_sources
+ end
+ end
+ end
+
+
+ module JavascriptTagHelpers
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ # Register one or more javascript files to be included when <tt>symbol</tt>
+ # is passed to <tt>javascript_include_tag</tt>. This method is typically intended
+ # to be called from plugin initialization to register javascript files
+ # that the plugin installed in <tt>public/javascripts</tt>.
+ #
+ # ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
+ #
+ # javascript_include_tag :monkey # =>
+ # <script type="text/javascript" src="/javascripts/head.js"></script>
+ # <script type="text/javascript" src="/javascripts/body.js"></script>
+ # <script type="text/javascript" src="/javascripts/tail.js"></script>
+ def register_javascript_expansion(expansions)
+ JavascriptIncludeTag.expansions.merge!(expansions)
+ end
+ end
+
+ # Computes the path to a javascript asset in the public javascripts directory.
+ # If the +source+ filename has no extension, .js will be appended (except for explicit URIs)
+ # Full paths from the document root will be passed through.
+ # Used internally by javascript_include_tag to build the script path.
+ #
+ # ==== Examples
+ # javascript_path "xmlhr" # => /javascripts/xmlhr.js
+ # javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js
+ # javascript_path "/dir/xmlhr" # => /dir/xmlhr.js
+ # javascript_path "http://www.railsapplication.com/js/xmlhr" # => http://www.railsapplication.com/js/xmlhr
+ # javascript_path "http://www.railsapplication.com/js/xmlhr.js" # => http://www.railsapplication.com/js/xmlhr.js
+ def javascript_path(source)
+ asset_paths.compute_public_path(source, 'javascripts', 'js')
+ end
+ alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
+
+ # Returns an HTML script tag for each of the +sources+ provided. You
+ # can pass in the filename (.js extension is optional) of JavaScript files
+ # that exist in your <tt>public/javascripts</tt> directory for inclusion into the
+ # current page or you can pass the full path relative to your document
+ # root. To include the Prototype and Scriptaculous JavaScript libraries in
+ # your application, pass <tt>:defaults</tt> as the source. When using
+ # <tt>:defaults</tt>, if an <tt>application.js</tt> file exists in
+ # <tt>public/javascripts</tt> it will be included as well. You can modify the
+ # HTML attributes of the script tag by passing a hash as the last argument.
+ #
+ # ==== Examples
+ # javascript_include_tag "xmlhr" # =>
+ # <script type="text/javascript" src="/javascripts/xmlhr.js?1284139606"></script>
+ #
+ # javascript_include_tag "xmlhr.js" # =>
+ # <script type="text/javascript" src="/javascripts/xmlhr.js?1284139606"></script>
+ #
+ # javascript_include_tag "common.javascript", "/elsewhere/cools" # =>
+ # <script type="text/javascript" src="/javascripts/common.javascript?1284139606"></script>
+ # <script type="text/javascript" src="/elsewhere/cools.js?1423139606"></script>
+ #
+ # javascript_include_tag "http://www.railsapplication.com/xmlhr" # =>
+ # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js?1284139606"></script>
+ #
+ # javascript_include_tag "http://www.railsapplication.com/xmlhr.js" # =>
+ # <script type="text/javascript" src="http://www.railsapplication.com/xmlhr.js?1284139606"></script>
+ #
+ # javascript_include_tag :defaults # =>
+ # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/effects.js?1284139606"></script>
+ # ...
+ # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
+ #
+ # * = The application.js file is only referenced if it exists
+ #
+ # You can also include all javascripts in the +javascripts+ directory using <tt>:all</tt> as the source:
+ #
+ # javascript_include_tag :all # =>
+ # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/effects.js?1284139606"></script>
+ # ...
+ # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/shop.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/checkout.js?1284139606"></script>
+ #
+ # Note that the default javascript files will be included first. So Prototype and Scriptaculous are available to
+ # all subsequently included files.
+ #
+ # If you want Rails to search in all the subdirectories under javascripts, you should explicitly set <tt>:recursive</tt>:
+ #
+ # javascript_include_tag :all, :recursive => true
+ #
+ # == Caching multiple javascripts into one
+ #
+ # You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be
+ # compressed by gzip (leading to faster transfers). Caching will only happen if config.perform_caching
+ # is set to <tt>true</tt> (which is the case by default for the Rails production environment, but not for the development
+ # environment).
+ #
+ # ==== Examples
+ # javascript_include_tag :all, :cache => true # when config.perform_caching is false =>
+ # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/effects.js?1284139606"></script>
+ # ...
+ # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/shop.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/checkout.js?1284139606"></script>
+ #
+ # javascript_include_tag :all, :cache => true # when config.perform_caching is true =>
+ # <script type="text/javascript" src="/javascripts/all.js?1344139789"></script>
+ #
+ # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when config.perform_caching is false =>
+ # <script type="text/javascript" src="/javascripts/prototype.js?1284139606"></script>
+ # <script type="text/javascript" src="/javascripts/cart.js?1289139157"></script>
+ # <script type="text/javascript" src="/javascripts/checkout.js?1299139816"></script>
+ #
+ # javascript_include_tag "prototype", "cart", "checkout", :cache => "shop" # when config.perform_caching is true =>
+ # <script type="text/javascript" src="/javascripts/shop.js?1299139816"></script>
+ #
+ # The <tt>:recursive</tt> option is also available for caching:
+ #
+ # javascript_include_tag :all, :cache => true, :recursive => true
+ def javascript_include_tag(*sources)
+ @javascript_include ||= JavascriptIncludeTag.new(config, asset_paths)
+ @javascript_include.include_tag(*sources)
+ end
+
+ end
+
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb
new file mode 100644
index 0000000000..d02b28d7f6
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb
@@ -0,0 +1,144 @@
+require 'active_support/concern'
+require 'active_support/core_ext/file'
+require 'action_view/helpers/tag_helper'
+require 'action_view/helpers/asset_tag_helpers/asset_include_tag'
+
+module ActionView
+ module Helpers
+ module AssetTagHelper
+
+ class StylesheetIncludeTag < AssetIncludeTag
+ include TagHelper
+
+ def asset_name
+ 'stylesheet'
+ end
+
+ def extension
+ 'css'
+ end
+
+ def asset_tag(source, options)
+ tag("link", { "rel" => "stylesheet", "type" => Mime::CSS, "media" => "screen", "href" => ERB::Util.html_escape(path_to_asset(source)) }.merge(options), false, false)
+ end
+
+ def custom_dir
+ config.stylesheets_dir
+ end
+ end
+
+
+ module StylesheetTagHelpers
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ # Register one or more stylesheet files to be included when <tt>symbol</tt>
+ # is passed to <tt>stylesheet_link_tag</tt>. This method is typically intended
+ # to be called from plugin initialization to register stylesheet files
+ # that the plugin installed in <tt>public/stylesheets</tt>.
+ #
+ # ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
+ #
+ # stylesheet_link_tag :monkey # =>
+ # <link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
+ def register_stylesheet_expansion(expansions)
+ StylesheetIncludeTag.expansions.merge!(expansions)
+ end
+ end
+
+ # Computes the path to a stylesheet asset in the public stylesheets directory.
+ # If the +source+ filename has no extension, <tt>.css</tt> will be appended (except for explicit URIs).
+ # Full paths from the document root will be passed through.
+ # Used internally by +stylesheet_link_tag+ to build the stylesheet path.
+ #
+ # ==== Examples
+ # stylesheet_path "style" # => /stylesheets/style.css
+ # stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css
+ # stylesheet_path "/dir/style.css" # => /dir/style.css
+ # stylesheet_path "http://www.railsapplication.com/css/style" # => http://www.railsapplication.com/css/style
+ # stylesheet_path "http://www.railsapplication.com/css/style.css" # => http://www.railsapplication.com/css/style.css
+ def stylesheet_path(source)
+ asset_paths.compute_public_path(source, 'stylesheets', 'css')
+ end
+ alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
+
+ # Returns a stylesheet link tag for the sources specified as arguments. If
+ # you don't specify an extension, <tt>.css</tt> will be appended automatically.
+ # You can modify the link attributes by passing a hash as the last argument.
+ #
+ # ==== Examples
+ # stylesheet_link_tag "style" # =>
+ # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "style.css" # =>
+ # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "http://www.railsapplication.com/style.css" # =>
+ # <link href="http://www.railsapplication.com/style.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "style", :media => "all" # =>
+ # <link href="/stylesheets/style.css" media="all" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "style", :media => "print" # =>
+ # <link href="/stylesheets/style.css" media="print" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "random.styles", "/css/stylish" # =>
+ # <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # You can also include all styles in the stylesheets directory using <tt>:all</tt> as the source:
+ #
+ # stylesheet_link_tag :all # =>
+ # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # If you want Rails to search in all the subdirectories under stylesheets, you should explicitly set <tt>:recursive</tt>:
+ #
+ # stylesheet_link_tag :all, :recursive => true
+ #
+ # == Caching multiple stylesheets into one
+ #
+ # You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be
+ # compressed by gzip (leading to faster transfers). Caching will only happen if config.perform_caching
+ # is set to true (which is the case by default for the Rails production environment, but not for the development
+ # environment). Examples:
+ #
+ # ==== Examples
+ # stylesheet_link_tag :all, :cache => true # when config.perform_caching is false =>
+ # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag :all, :cache => true # when config.perform_caching is true =>
+ # <link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is false =>
+ # <link href="/stylesheets/shop.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/cart.css" media="screen" rel="stylesheet" type="text/css" />
+ # <link href="/stylesheets/checkout.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is true =>
+ # <link href="/stylesheets/payment.css" media="screen" rel="stylesheet" type="text/css" />
+ #
+ # The <tt>:recursive</tt> option is also available for caching:
+ #
+ # stylesheet_link_tag :all, :cache => true, :recursive => true
+ #
+ # To force concatenation (even in development mode) set <tt>:concat</tt> to true. This is useful if
+ # you have too many stylesheets for IE to load.
+ #
+ # stylesheet_link_tag :all, :concat => true
+ #
+ def stylesheet_link_tag(*sources)
+ @stylesheet_include ||= StylesheetIncludeTag.new(config, asset_paths)
+ @stylesheet_include.include_tag(*sources)
+ end
+
+ end
+
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb
index c1214bc44e..875ec9b77b 100644
--- a/actionpack/lib/action_view/helpers/date_helper.rb
+++ b/actionpack/lib/action_view/helpers/date_helper.rb
@@ -882,6 +882,8 @@ module ActionView
# Returns the separator for a given datetime component
def separator(type)
case type
+ when :year
+ @options[:discard_year] ? "" : @options[:date_separator]
when :month
@options[:discard_month] ? "" : @options[:date_separator]
when :day
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index 80a872068d..8c300ec745 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -112,6 +112,7 @@ module ActionView
# <%= f.text_field :version %><br />
# <%= f.label :author, 'Author' %>:
# <%= f.text_field :author %><br />
+ # <%= f.submit %>
# <% end %>
#
# There, +form_for+ is able to generate the rest of RESTful form
@@ -129,6 +130,7 @@ module ActionView
# Last name : <%= f.text_field :last_name %><br />
# Biography : <%= f.text_area :biography %><br />
# Admin? : <%= f.check_box :admin %><br />
+ # <%= f.submit %>
# <% end %>
#
# There, the argument is a symbol or string with the name of the
@@ -160,6 +162,7 @@ module ActionView
# Last name : <%= f.text_field :last_name %>
# Biography : <%= text_area :person, :biography %>
# Admin? : <%= check_box_tag "person[admin]", @person.company.admin? %>
+ # <%= f.submit %>
# <% end %>
#
# This also works for the methods in FormOptionHelper and DateHelper that
@@ -269,8 +272,9 @@ module ActionView
# <%= form_for @person, :url => { :action => "create" }, :builder => LabellingFormBuilder do |f| %>
# <%= f.text_field :first_name %>
# <%= f.text_field :last_name %>
- # <%= text_area :person, :biography %>
- # <%= check_box_tag "person[admin]", @person.company.admin? %>
+ # <%= f.text_area :biography %>
+ # <%= f.check_box :admin %>
+ # <%= f.submit %>
# <% end %>
#
# In this case, if you use this:
@@ -347,6 +351,8 @@ module ActionView
# <%= fields_for @person.permission do |permission_fields| %>
# Admin? : <%= permission_fields.check_box :admin %>
# <% end %>
+ #
+ # <%= f.submit %>
# <% end %>
#
# ...or if you have an object that needs to be represented as a different
@@ -408,6 +414,7 @@ module ActionView
# Street : <%= address_fields.text_field :street %>
# Zip code: <%= address_fields.text_field :zip_code %>
# <% end %>
+ # ...
# <% end %>
#
# When address is already an association on a Person you can use
@@ -437,6 +444,7 @@ module ActionView
# ...
# Delete: <%= address_fields.check_box :_destroy %>
# <% end %>
+ # ...
# <% end %>
#
# ==== One-to-many
@@ -466,6 +474,7 @@ module ActionView
# Name: <%= project_fields.text_field :name %>
# <% end %>
# <% end %>
+ # ...
# <% end %>
#
# It's also possible to specify the instance to be used:
@@ -479,6 +488,7 @@ module ActionView
# <% end %>
# <% end %>
# <% end %>
+ # ...
# <% end %>
#
# Or a collection to be used:
@@ -488,6 +498,7 @@ module ActionView
# <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
# Name: <%= project_fields.text_field :name %>
# <% end %>
+ # ...
# <% end %>
#
# When projects is already an association on Person you can use
@@ -517,6 +528,7 @@ module ActionView
# <%= person_form.fields_for :projects do |project_fields| %>
# Delete: <%= project_fields.check_box :_destroy %>
# <% end %>
+ # ...
# <% end %>
def fields_for(record, record_object = nil, options = nil, &block)
capture(instantiate_builder(record, record_object, options, &block), &block)
@@ -1205,6 +1217,7 @@ module ActionView
self.multipart = true
@template.file_field(@object_name, method, objectify_options(options))
end
+
# Add the submit button for the given form. When no value is given, it checks
# if the object is a new resource or not to create the proper label:
#
@@ -1277,11 +1290,11 @@ module ActionView
if association.respond_to?(:persisted?)
association = [association] if @object.send(association_name).is_a?(Array)
- elsif !association.is_a?(Array)
+ elsif !association.respond_to?(:to_ary)
association = @object.send(association_name)
end
- if association.is_a?(Array)
+ if association.respond_to?(:to_ary)
explicit_child_index = options[:child_index]
output = ActiveSupport::SafeBuffer.new
association.each do |child|
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index 7c877a0f57..3d276000a1 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -9,6 +9,24 @@ module ActionView
# and transforming strings, which can reduce the amount of inline Ruby code in
# your views. These helper methods extend Action View making them callable
# within your template files.
+ #
+ # ==== Sanitization
+ #
+ # Most text helpers by default sanitize the given content, but do not escape it.
+ # This means HTML tags will appear in the page but all malicious code will be removed.
+ # Let's look at some examples using the +simple_format+ method:
+ #
+ # simple_format('<a href="http://example.com/">Example</a>')
+ # # => "<p><a href=\"http://example.com/\">Example</a></p>"
+ #
+ # simple_format('<a href="javascript:alert('no!')">Example</a>')
+ # # => "<p><a>Example</a></p>"
+ #
+ # If you want to escape all content, you should invoke the +h+ method before
+ # calling the text helper.
+ #
+ # simple_format h('<a href="http://example.com/">Example</a>')
+ # # => "<p>&lt;a href=\"http://example.com/\"&gt;Example&lt;/a&gt;</p>"
module TextHelper
extend ActiveSupport::Concern
diff --git a/actionpack/lib/action_view/railtie.rb b/actionpack/lib/action_view/railtie.rb
index 33dfcbb803..71cd1a788a 100644
--- a/actionpack/lib/action_view/railtie.rb
+++ b/actionpack/lib/action_view/railtie.rb
@@ -8,10 +8,10 @@ module ActionView
config.action_view.stylesheet_expansions = {}
config.action_view.javascript_expansions = { :defaults => ['prototype', 'effects', 'dragdrop', 'controls', 'rails'] }
- initializer "action_view.cache_asset_timestamps" do |app|
+ initializer "action_view.cache_asset_ids" do |app|
unless app.config.cache_classes
ActiveSupport.on_load(:action_view) do
- ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false
+ ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false
end
end
end
diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb
index c580397cad..317479ad4c 100644
--- a/actionpack/lib/action_view/renderer/partial_renderer.rb
+++ b/actionpack/lib/action_view/renderer/partial_renderer.rb
@@ -90,13 +90,14 @@ module ActionView
def collection
if @options.key?(:collection)
- @options[:collection] || []
+ collection = @options[:collection]
+ collection.respond_to?(:to_ary) ? collection.to_ary : []
end
end
def collection_from_object
if @object.respond_to?(:to_ary)
- @object
+ @object.to_ary
end
end
@@ -163,4 +164,4 @@ module ActionView
[variable, variable_counter]
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb
index f5811a1530..7c595d1b89 100644
--- a/actionpack/test/activerecord/active_record_store_test.rb
+++ b/actionpack/test/activerecord/active_record_store_test.rb
@@ -27,6 +27,12 @@ class ActiveRecordStoreTest < ActionDispatch::IntegrationTest
head :ok
end
+ def renew
+ env["rack.session.options"][:renew] = true
+ session[:foo] = "baz"
+ head :ok
+ end
+
def rescue_action(e) raise end
end
@@ -64,6 +70,20 @@ class ActiveRecordStoreTest < ActionDispatch::IntegrationTest
end
end
end
+
+ define_method("test_renewing_with_#{class_name}_store") do
+ with_store class_name do
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+
+ get '/renew'
+ assert_response :success
+ assert_not_equal [], headers['Set-Cookie']
+ end
+ end
+ end
end
def test_getting_nil_session_value
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index 5a210aa9ec..22ccd2e6b3 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -171,6 +171,14 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
end
end
+ def test_string_constraint
+ with_routing do |set|
+ set.draw do |map|
+ match "photos", :to => 'action_pack_assertions#nothing', :constraints => {:subdomain => "admin"}
+ end
+ end
+ end
+
def test_assert_redirect_to_named_route_failure
with_routing do |set|
set.draw do
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index 3a8a37d967..68febf425d 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -78,7 +78,8 @@ class FilterTest < ActionController::TestCase
end
class RenderingController < ActionController::Base
- before_filter :render_something_else
+ before_filter :before_filter_rendering
+ after_filter :unreached_after_filter
def show
@ran_action = true
@@ -86,9 +87,59 @@ class FilterTest < ActionController::TestCase
end
private
- def render_something_else
+ def before_filter_rendering
+ @ran_filter ||= []
+ @ran_filter << "before_filter_rendering"
render :inline => "something else"
end
+
+ def unreached_after_filter
+ @ran_filter << "unreached_after_filter_after_render"
+ end
+ end
+
+ class RenderingForPrependAfterFilterController < RenderingController
+ prepend_after_filter :unreached_prepend_after_filter
+
+ private
+ def unreached_prepend_after_filter
+ @ran_filter << "unreached_preprend_after_filter_after_render"
+ end
+ end
+
+ class BeforeFilterRedirectionController < ActionController::Base
+ before_filter :before_filter_redirects
+ after_filter :unreached_after_filter
+
+ def show
+ @ran_action = true
+ render :inline => "ran show action"
+ end
+
+ def target_of_redirection
+ @ran_target_of_redirection = true
+ render :inline => "ran target_of_redirection action"
+ end
+
+ private
+ def before_filter_redirects
+ @ran_filter ||= []
+ @ran_filter << "before_filter_redirects"
+ redirect_to(:action => 'target_of_redirection')
+ end
+
+ def unreached_after_filter
+ @ran_filter << "unreached_after_filter_after_redirection"
+ end
+ end
+
+ class BeforeFilterRedirectionForPrependAfterFilterController < BeforeFilterRedirectionController
+ prepend_after_filter :unreached_prepend_after_filter_after_redirection
+
+ private
+ def unreached_prepend_after_filter_after_redirection
+ @ran_filter << "unreached_prepend_after_filter_after_redirection"
+ end
end
class ConditionalFilterController < ActionController::Base
@@ -625,6 +676,32 @@ class FilterTest < ActionController::TestCase
assert !assigns["ran_action"]
end
+ def test_before_filter_rendering_breaks_filtering_chain_for_after_filter
+ response = test_process(RenderingController)
+ assert_equal %w( before_filter_rendering ), assigns["ran_filter"]
+ assert !assigns["ran_action"]
+ end
+
+ def test_before_filter_redirects_breaks_filtering_chain_for_after_filter
+ response = test_process(BeforeFilterRedirectionController)
+ assert_response :redirect
+ assert_equal "http://test.host/filter_test/before_filter_redirection/target_of_redirection", redirect_to_url
+ assert_equal %w( before_filter_redirects ), assigns["ran_filter"]
+ end
+
+ def test_before_filter_rendering_breaks_filtering_chain_for_preprend_after_filter
+ response = test_process(RenderingForPrependAfterFilterController)
+ assert_equal %w( before_filter_rendering ), assigns["ran_filter"]
+ assert !assigns["ran_action"]
+ end
+
+ def test_before_filter_redirects_breaks_filtering_chain_for_preprend_after_filter
+ response = test_process(BeforeFilterRedirectionForPrependAfterFilterController)
+ assert_response :redirect
+ assert_equal "http://test.host/filter_test/before_filter_redirection_for_prepend_after_filter/target_of_redirection", redirect_to_url
+ assert_equal %w( before_filter_redirects ), assigns["ran_filter"]
+ end
+
def test_filters_with_mixed_specialization_run_in_order
assert_nothing_raised do
response = test_process(MixedSpecializationController, 'bar')
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index ecfa13d4ba..ce5c899a19 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -834,6 +834,14 @@ class RouteSetTest < ActiveSupport::TestCase
assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10'))
end
+ def test_route_constraints_on_request_object_with_anchors_are_valid
+ assert_nothing_raised do
+ set.draw do
+ match 'page/:id' => 'pages#show', :constraints => { :host => /^foo$/ }
+ end
+ end
+ end
+
def test_route_constraints_with_anchor_chars_are_invalid
assert_raise ArgumentError do
set.draw do
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index 04709e5346..4764a8c2a8 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -96,6 +96,9 @@ class RequestTest < ActiveSupport::TestCase
request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk"
assert_equal "rubyonrails.co.uk", request.domain(2)
+ request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk", :tld_length => 2
+ assert_equal "rubyonrails.co.uk", request.domain
+
request = stub_request 'HTTP_HOST' => "192.168.1.200"
assert_nil request.domain
diff --git a/actionpack/test/fixtures/layouts/_partial_and_yield.erb b/actionpack/test/fixtures/layouts/_partial_and_yield.erb
new file mode 100644
index 0000000000..74cc428ffa
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/_partial_and_yield.erb
@@ -0,0 +1,2 @@
+<%= render :partial => 'test/partial' %>
+<%= yield %>
diff --git a/actionpack/test/fixtures/layouts/_yield_only.erb b/actionpack/test/fixtures/layouts/_yield_only.erb
new file mode 100644
index 0000000000..37f0bddbd7
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/_yield_only.erb
@@ -0,0 +1 @@
+<%= yield %>
diff --git a/actionpack/test/fixtures/layouts/_yield_with_params.erb b/actionpack/test/fixtures/layouts/_yield_with_params.erb
new file mode 100644
index 0000000000..68e6557fb8
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/_yield_with_params.erb
@@ -0,0 +1 @@
+<%= yield 'Yield!' %>
diff --git a/actionpack/test/fixtures/layouts/yield_with_render_partial_inside.erb b/actionpack/test/fixtures/layouts/yield_with_render_partial_inside.erb
new file mode 100644
index 0000000000..74cc428ffa
--- /dev/null
+++ b/actionpack/test/fixtures/layouts/yield_with_render_partial_inside.erb
@@ -0,0 +1,2 @@
+<%= render :partial => 'test/partial' %>
+<%= yield %>
diff --git a/actionpack/test/fixtures/test/_partial_with_layout.erb b/actionpack/test/fixtures/test/_partial_with_layout.erb
new file mode 100644
index 0000000000..2a50c834fe
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_with_layout.erb
@@ -0,0 +1,2 @@
+<%= render :partial => 'test/partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Bar!' } %>
+partial with layout
diff --git a/actionpack/test/fixtures/test/_partial_with_layout_block_content.erb b/actionpack/test/fixtures/test/_partial_with_layout_block_content.erb
new file mode 100644
index 0000000000..65dafd93a8
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_with_layout_block_content.erb
@@ -0,0 +1,4 @@
+<%= render :layout => 'test/layout_for_partial', :locals => { :name => 'Bar!' } do %>
+ Content from inside layout!
+<% end %>
+partial with layout
diff --git a/actionpack/test/fixtures/test/_partial_with_layout_block_partial.erb b/actionpack/test/fixtures/test/_partial_with_layout_block_partial.erb
new file mode 100644
index 0000000000..444197a7d0
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_with_layout_block_partial.erb
@@ -0,0 +1,4 @@
+<%= render :layout => 'test/layout_for_partial', :locals => { :name => 'Bar!' } do %>
+ <%= render 'test/partial' %>
+<% end %>
+partial with layout
diff --git a/actionpack/test/fixtures/test/_partial_with_partial.erb b/actionpack/test/fixtures/test/_partial_with_partial.erb
new file mode 100644
index 0000000000..ee0d5037b6
--- /dev/null
+++ b/actionpack/test/fixtures/test/_partial_with_partial.erb
@@ -0,0 +1,2 @@
+<%= render 'test/partial' %>
+partial with partial
diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb
index dba632e6df..ae0c38184d 100644
--- a/actionpack/test/lib/controller/fake_models.rb
+++ b/actionpack/test/lib/controller/fake_models.rb
@@ -184,3 +184,13 @@ module Blog
end
end
end
+
+class ArelLike
+ def to_ary
+ true
+ end
+ def each
+ a = Array.new(2) { |id| Comment.new(id + 1) }
+ a.each { |i| yield i }
+ end
+end
diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb
index 3abcdfbc1e..139d832c5f 100644
--- a/actionpack/test/template/asset_tag_helper_test.rb
+++ b/actionpack/test/template/asset_tag_helper_test.rb
@@ -274,7 +274,7 @@ class AssetTagHelperTest < ActionView::TestCase
end
def test_reset_javascript_expansions
- ActionView::Helpers::AssetTagHelper.javascript_expansions.clear
+ JavascriptIncludeTag.expansions.clear
assert_raise(ArgumentError) { javascript_include_tag(:defaults) }
end
@@ -306,7 +306,6 @@ class AssetTagHelperTest < ActionView::TestCase
ENV["RAILS_ASSET_ID"] = ""
assert stylesheet_link_tag('dir/file').html_safe?
assert stylesheet_link_tag('dir/other/file', 'dir/file2').html_safe?
- assert stylesheet_tag('dir/file', {}).html_safe?
end
def test_custom_stylesheet_expansions
@@ -727,6 +726,17 @@ class AssetTagHelperTest < ActionView::TestCase
assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'money.js'))
end
+ def test_caching_javascript_include_tag_when_caching_on_and_javascript_file_is_uri
+ ENV["RAILS_ASSET_ID"] = ""
+ config.perform_caching = true
+
+ assert_raise(Errno::ENOENT) {
+ javascript_include_tag('bank', 'robber', 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.js', :cache => true)
+ }
+
+ assert !File.exist?(File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR, 'all.js'))
+ end
+
def test_caching_javascript_include_tag_when_caching_off_and_missing_javascript_file
ENV["RAILS_ASSET_ID"] = ""
config.perform_caching = false
@@ -938,7 +948,7 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase
@request = Struct.new(:protocol).new("gopher://")
@controller.request = @request
- ActionView::Helpers::AssetTagHelper.javascript_expansions.clear
+ JavascriptIncludeTag.expansions.clear
end
def url_for(options)
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
index 0cf7885772..55c384e68f 100644
--- a/actionpack/test/template/date_helper_test.rb
+++ b/actionpack/test/template/date_helper_test.rb
@@ -1584,6 +1584,47 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, date_select("post", "written_on", { :date_separator => " / " })
end
+ def test_date_select_with_separator_and_order
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n}
+ expected << "</select>\n"
+
+ expected << " / "
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << " / "
+
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", { :order => [:day, :month, :year], :date_separator => " / " })
+ end
+
+ def test_date_select_with_separator_and_order_and_year_discarded
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}
+ expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n}
+ expected << "</select>\n"
+
+ expected << " / "
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+ expected << %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}
+
+ assert_dom_equal expected, date_select("post", "written_on", { :order => [:day, :month, :year], :discard_year => true, :date_separator => " / " })
+ end
+
def test_date_select_with_default_prompt
@post = Post.new
@post.written_on = Date.new(2004, 6, 15)
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index acb6e7aa64..2c60096475 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -1230,6 +1230,27 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
+ def test_nested_fields_for_arel_like
+ @post.comments = ArelLike.new
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:comments, @post.comments) { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
def test_nested_fields_for_with_existing_records_on_a_supplied_nested_attributes_collection_different_from_record_one
comments = Array.new(2) { |id| Comment.new(id + 1) }
@post.comments = []
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 17bb610b6a..d2bf45a63a 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -247,6 +247,51 @@ module RenderTestCases
@view.render(:file => "test/hello_world.erb", :layout => "layouts/yield_with_render_inline_inside")
end
+ def test_render_with_layout_which_renders_another_partial
+ assert_equal %(partial html\nHello world!\n),
+ @view.render(:file => "test/hello_world.erb", :layout => "layouts/yield_with_render_partial_inside")
+ end
+
+ def test_render_layout_with_block_and_yield
+ assert_equal %(Content from block!\n),
+ @view.render(:layout => "layouts/yield_only") { "Content from block!" }
+ end
+
+ def test_render_layout_with_block_and_yield_with_params
+ assert_equal %(Yield! Content from block!\n),
+ @view.render(:layout => "layouts/yield_with_params") { |param| "#{param} Content from block!" }
+ end
+
+ def test_render_layout_with_block_which_renders_another_partial_and_yields
+ assert_equal %(partial html\nContent from block!\n),
+ @view.render(:layout => "layouts/partial_and_yield") { "Content from block!" }
+ end
+
+ def test_render_partial_and_layout_without_block_with_locals
+ assert_equal %(Before (Foo!)\npartial html\nAfter),
+ @view.render(:partial => 'test/partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'})
+ end
+
+ def test_render_partial_and_layout_without_block_with_locals_and_rendering_another_partial
+ assert_equal %(Before (Foo!)\npartial html\npartial with partial\n\nAfter),
+ @view.render(:partial => 'test/partial_with_partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'})
+ end
+
+ def test_render_layout_with_a_nested_render_layout_call
+ assert_equal %(Before (Foo!)\nBefore (Bar!)\npartial html\nAfter\npartial with layout\n\nAfter),
+ @view.render(:partial => 'test/partial_with_layout', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'})
+ end
+
+ def test_render_layout_with_a_nested_render_layout_call_using_block_with_render_partial
+ assert_equal %(Before (Foo!)\nBefore (Bar!)\n\n partial html\n\nAfterpartial with layout\n\nAfter),
+ @view.render(:partial => 'test/partial_with_layout_block_partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'})
+ end
+
+ def test_render_layout_with_a_nested_render_layout_call_using_block_with_render_content
+ assert_equal %(Before (Foo!)\nBefore (Bar!)\n\n Content from inside layout!\n\nAfterpartial with layout\n\nAfter),
+ @view.render(:partial => 'test/partial_with_layout_block_content', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'})
+ end
+
def test_render_with_nested_layout
assert_equal %(<title>title</title>\n\n<div id="column">column</div>\n<div id="content">content</div>\n),
@view.render(:file => "test/nested_layout.erb", :layout => "layouts/yield")
diff --git a/activemodel/CHANGELOG b/activemodel/CHANGELOG
index e93d84ab59..4e963c77b0 100644
--- a/activemodel/CHANGELOG
+++ b/activemodel/CHANGELOG
@@ -2,6 +2,10 @@
* No changes
+*Rails 3.0.2 (unreleased)*
+
+* No changes
+
*Rails 3.0.1 (October 15, 2010)*
* No Changes, just a version bump.
diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb
index 44e3e64a9e..c1c5640616 100644
--- a/activemodel/lib/active_model/attribute_methods.rb
+++ b/activemodel/lib/active_model/attribute_methods.rb
@@ -98,10 +98,10 @@ module ActiveModel
def define_attr_method(name, value=nil, &block)
sing = singleton_class
sing.class_eval <<-eorb, __FILE__, __LINE__ + 1
- if method_defined?(:original_#{name})
- undef :original_#{name}
+ if method_defined?(:'original_#{name}')
+ undef :'original_#{name}'
end
- alias_method :original_#{name}, :#{name}
+ alias_method :'original_#{name}', :'#{name}'
eorb
if block_given?
sing.send :define_method, name, &block
@@ -274,8 +274,8 @@ module ActiveModel
method_name = matcher.method_name(attr_name)
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
- if method_defined?(:#{method_name})
- undef :#{method_name}
+ if method_defined?(:'#{method_name}')
+ undef :'#{method_name}'
end
def #{method_name}(*args)
send(:#{matcher.method_missing_target}, '#{attr_name}', *args)
diff --git a/activemodel/lib/active_model/version.rb b/activemodel/lib/active_model/version.rb
index ece4431225..23ba42bf35 100644
--- a/activemodel/lib/active_model/version.rb
+++ b/activemodel/lib/active_model/version.rb
@@ -3,8 +3,8 @@ module ActiveModel
MAJOR = 3
MINOR = 1
TINY = 0
- BUILD = "beta"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG
index 06c1428217..29f06dc06a 100644
--- a/activerecord/CHANGELOG
+++ b/activerecord/CHANGELOG
@@ -20,6 +20,35 @@
[Aaron Patterson]
+*Rails 3.0.2 (unreleased)*
+
+* reorder is deprecated in favor of except(:order).order(...) [Santiago Pastorino]
+
+* except is now AR public API
+
+ Model.order('name').except(:order).order('salary')
+
+ generates:
+
+ SELECT * FROM models ORDER BY salary
+
+ [Santiago Pastorino]
+
+* The following code:
+
+ Model.limit(10).scoping { Model.count }
+
+ now generates the following SQL:
+
+ SELECT COUNT(*) FROM models LIMIT 10
+
+ This may not return what you want. Instead, you may with to do something
+ like this:
+
+ Model.limit(10).scoping { Model.all.size }
+
+ [Aaron Patterson]
+
*Rails 3.0.1 (October 15, 2010)*
* Introduce a fix for CVE-2010-3993
diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec
index b8a980b1fb..b1df24844a 100644
--- a/activerecord/activerecord.gemspec
+++ b/activerecord/activerecord.gemspec
@@ -23,6 +23,6 @@ Gem::Specification.new do |s|
s.add_dependency('activesupport', version)
s.add_dependency('activemodel', version)
- s.add_dependency('arel', '~> 2.0.0')
+ s.add_dependency('arel', '~> 2.0.2')
s.add_dependency('tzinfo', '~> 0.3.23')
end
diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb
index 16206c1056..8cd7389005 100644
--- a/activerecord/lib/active_record/aggregations.rb
+++ b/activerecord/lib/active_record/aggregations.rb
@@ -6,7 +6,7 @@ module ActiveRecord
def clear_aggregation_cache #:nodoc:
self.class.reflect_on_all_aggregations.to_a.each do |assoc|
instance_variable_set "@#{assoc.name}", nil
- end unless self.new_record?
+ end if self.persisted?
end
# Active Record implements aggregation through a macro-like class method called +composed_of+
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index 577a807e3c..e82cbd0aa6 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -117,7 +117,7 @@ module ActiveRecord
def clear_association_cache #:nodoc:
self.class.reflect_on_all_associations.to_a.each do |assoc|
instance_variable_set "@#{assoc.name}", nil
- end unless self.new_record?
+ end if self.persisted?
end
private
diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb
index 896e18af01..6090376bb8 100644
--- a/activerecord/lib/active_record/associations/association_collection.rb
+++ b/activerecord/lib/active_record/associations/association_collection.rb
@@ -75,6 +75,7 @@ module ActiveRecord
find(:first, *args)
else
load_target unless loaded?
+ args = args[1..-1] if args.first.kind_of?(Hash) && args.first.empty?
@target.first(*args)
end
end
@@ -120,13 +121,13 @@ module ActiveRecord
# Since << flattens its argument list and inserts each record, +push+ and +concat+ behave identically.
def <<(*records)
result = true
- load_target if @owner.new_record?
+ load_target unless @owner.persisted?
transaction do
flatten_deeper(records).each do |record|
raise_on_type_mismatch(record)
add_record_to_target_with_callbacks(record) do |r|
- result &&= insert_record(record) unless @owner.new_record?
+ result &&= insert_record(record) if @owner.persisted?
end
end
end
@@ -181,7 +182,7 @@ module ActiveRecord
unless options.blank?
raise ArgumentError, "If finder_sql/counter_sql is used then options cannot be passed"
end
-
+
@reflection.klass.count_by_sql(custom_counter_sql)
else
@@ -285,12 +286,12 @@ module ActiveRecord
# This method is abstract in the sense that it relies on
# +count_records+, which is a method descendants have to provide.
def size
- if @owner.new_record? || (loaded? && !@reflection.options[:uniq])
+ if !@owner.persisted? || (loaded? && !@reflection.options[:uniq])
@target.size
elsif !loaded? && @reflection.options[:group]
load_target.size
elsif !loaded? && !@reflection.options[:uniq] && @target.is_a?(Array)
- unsaved_records = @target.select { |r| r.new_record? }
+ unsaved_records = @target.reject { |r| r.persisted? }
unsaved_records.size + count_records
else
count_records
@@ -331,13 +332,10 @@ module ActiveRecord
end
def uniq(collection = self)
- seen = Set.new
- collection.map do |record|
- unless seen.include?(record.id)
- seen << record.id
- record
- end
- end.compact
+ seen = {}
+ collection.find_all do |record|
+ seen[record.id] = true unless seen.key?(record.id)
+ end
end
# Replace this collection with +other_array+
@@ -357,7 +355,7 @@ module ActiveRecord
def include?(record)
return false unless record.is_a?(@reflection.klass)
- return include_in_memory?(record) if record.new_record?
+ return include_in_memory?(record) unless record.persisted?
load_target if @reflection.options[:finder_sql] && !loaded?
return @target.include?(record) if loaded?
exists?(record)
@@ -372,16 +370,18 @@ module ActiveRecord
end
def load_target
- if !@owner.new_record? || foreign_key_present
+ if @owner.persisted? || foreign_key_present
begin
- if !loaded?
+ unless loaded?
if @target.is_a?(Array) && @target.any?
@target = find_target.map do |f|
i = @target.index(f)
if i
@target.delete_at(i).tap do |t|
keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names)
- t.attributes = f.attributes.except(*keys)
+ f.attributes.except(*keys).each do |k,v|
+ t.send("#{k}=", v)
+ end
end
else
f
@@ -408,11 +408,7 @@ module ActiveRecord
end
if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
- if block_given?
- super { |*block_args| yield(*block_args) }
- else
- super
- end
+ super
elsif @reflection.klass.scopes[method]
@_named_scopes_cache ||= {}
@_named_scopes_cache[method] ||= {}
@@ -435,10 +431,10 @@ module ActiveRecord
# replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
counter_sql = @reflection.options[:finder_sql].sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
end
-
+
interpolate_sql(counter_sql)
end
-
+
def custom_finder_sql
interpolate_sql(@reflection.options[:finder_sql])
end
@@ -513,7 +509,7 @@ module ActiveRecord
transaction do
records.each { |record| callback(:before_remove, record) }
- old_records = records.reject { |r| r.new_record? }
+ old_records = records.select { |r| r.persisted? }
yield(records, old_records)
records.each { |record| callback(:after_remove, record) }
end
@@ -538,14 +534,14 @@ module ActiveRecord
end
def ensure_owner_is_not_new
- if @owner.new_record?
+ unless @owner.persisted?
raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
end
end
def fetch_first_or_last_using_find?(args)
- args.first.kind_of?(Hash) || !(loaded? || @owner.new_record? || @reflection.options[:finder_sql] ||
- @target.any? { |record| record.new_record? } || args.first.kind_of?(Integer))
+ (args.first.kind_of?(Hash) && !args.first.empty?) || !(loaded? || !@owner.persisted? || @reflection.options[:finder_sql] ||
+ !@target.all? { |record| record.persisted? } || args.first.kind_of?(Integer))
end
def include_in_memory?(record)
diff --git a/activerecord/lib/active_record/associations/association_proxy.rb b/activerecord/lib/active_record/associations/association_proxy.rb
index ac2aa46edf..7cd04a1ad5 100644
--- a/activerecord/lib/active_record/associations/association_proxy.rb
+++ b/activerecord/lib/active_record/associations/association_proxy.rb
@@ -175,10 +175,10 @@ module ActiveRecord
# If the association is polymorphic the type of the owner is also set.
def set_belongs_to_association_for(record)
if @reflection.options[:as]
- record["#{@reflection.options[:as]}_id"] = @owner.id unless @owner.new_record?
+ record["#{@reflection.options[:as]}_id"] = @owner.id if @owner.persisted?
record["#{@reflection.options[:as]}_type"] = @owner.class.base_class.name.to_s
else
- unless @owner.new_record?
+ if @owner.persisted?
primary_key = @reflection.options[:primary_key] || :id
record[@reflection.primary_key_name] = @owner.send(primary_key)
end
@@ -211,12 +211,12 @@ module ActiveRecord
:create => construct_create_scope
}
end
-
+
# Implemented by subclasses
def construct_find_scope
raise NotImplementedError
end
-
+
# Implemented by (some) subclasses
def construct_create_scope
{}
@@ -252,7 +252,7 @@ module ActiveRecord
def load_target
return nil unless defined?(@loaded)
- if !loaded? and (!@owner.new_record? || foreign_key_present)
+ if !loaded? and (@owner.persisted? || foreign_key_present)
@target = find_target
end
diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb
index 34b6cd5576..b624951cd9 100644
--- a/activerecord/lib/active_record/associations/belongs_to_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -14,7 +14,7 @@ module ActiveRecord
counter_cache_name = @reflection.counter_cache_column
if record.nil?
- if counter_cache_name && !@owner.new_record?
+ if counter_cache_name && @owner.persisted?
@reflection.klass.decrement_counter(counter_cache_name, previous_record_id) if @owner[@reflection.primary_key_name]
end
@@ -22,13 +22,13 @@ module ActiveRecord
else
raise_on_type_mismatch(record)
- if counter_cache_name && !@owner.new_record? && record.id != @owner[@reflection.primary_key_name]
+ if counter_cache_name && @owner.persisted? && record.id != @owner[@reflection.primary_key_name]
@reflection.klass.increment_counter(counter_cache_name, record.id)
@reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
end
@target = (AssociationProxy === record ? record.target : record)
- @owner[@reflection.primary_key_name] = record_id(record) unless record.new_record?
+ @owner[@reflection.primary_key_name] = record_id(record) if record.persisted?
@updated = true
end
diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
index 1fc9aba5cf..da742fa668 100644
--- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
@@ -34,7 +34,7 @@ module ActiveRecord
end
def insert_record(record, force = true, validate = true)
- if record.new_record?
+ unless record.persisted?
if force
record.save!
else
diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb
index c45f2ee224..c1fc16b0ed 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -67,7 +67,7 @@ module ActiveRecord
def insert_record(record, force = true, validate = true)
ensure_not_nested
- if record.new_record?
+ unless record.persisted?
if force
record.save!
else
@@ -76,8 +76,7 @@ module ActiveRecord
end
through_association = @owner.send(@reflection.through_reflection.name)
- through_record = through_association.create!(construct_join_attributes(record))
- through_association.proxy_target << through_record
+ through_association.create!(construct_join_attributes(record))
end
# TODO - add dependent option support
diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb
index c6bcfec275..0ccf07f15e 100644
--- a/activerecord/lib/active_record/associations/has_one_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_association.rb
@@ -30,18 +30,18 @@ module ActiveRecord
if dependent? && !dont_save
case @reflection.options[:dependent]
when :delete
- @target.delete unless @target.new_record?
+ @target.delete if @target.persisted?
@owner.clear_association_cache
when :destroy
- @target.destroy unless @target.new_record?
+ @target.destroy if @target.persisted?
@owner.clear_association_cache
when :nullify
@target[@reflection.primary_key_name] = nil
- @target.save unless @owner.new_record? || @target.new_record?
+ @target.save if @owner.persisted? && @target.persisted?
end
else
@target[@reflection.primary_key_name] = nil
- @target.save unless @owner.new_record? || @target.new_record?
+ @target.save if @owner.persisted? && @target.persisted?
end
end
@@ -56,7 +56,7 @@ module ActiveRecord
set_inverse_instance(obj, @owner)
@loaded = true
- unless @owner.new_record? or obj.nil? or dont_save
+ unless !@owner.persisted? or obj.nil? or dont_save
return (obj.save ? self : false)
else
return (obj.nil? ? nil : self)
@@ -113,7 +113,7 @@ module ActiveRecord
if replace_existing
replace(record, true)
else
- record[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
+ record[@reflection.primary_key_name] = @owner.id if @owner.persisted?
self.target = record
set_inverse_instance(record, @owner)
end
diff --git a/activerecord/lib/active_record/associations/has_one_through_association.rb b/activerecord/lib/active_record/associations/has_one_through_association.rb
index e9dc32efd3..cfd4637e8e 100644
--- a/activerecord/lib/active_record/associations/has_one_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_through_association.rb
@@ -23,7 +23,7 @@ module ActiveRecord
if current_object
new_value ? current_object.update_attributes(construct_join_attributes(new_value)) : current_object.destroy
elsif new_value
- if @owner.new_record?
+ unless @owner.persisted?
self.target = new_value
through_association = @owner.send(:association_instance_get, @reflection.through_reflection.name)
through_association.build(construct_join_attributes(new_value))
diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb
index 82d94b848a..75ae06f5e9 100644
--- a/activerecord/lib/active_record/attribute_methods/primary_key.rb
+++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -3,10 +3,11 @@ module ActiveRecord
module PrimaryKey
extend ActiveSupport::Concern
- # Returns this record's primary key value wrapped in an Array
- # or nil if the record is a new_record?
+ # Returns this record's primary key value wrapped in an Array or nil if
+ # the record is not persisted? or has just been destroyed.
def to_key
- new_record? ? nil : [ id ]
+ key = send(self.class.primary_key)
+ [key] if key
end
module ClassMethods
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index 0b89a49896..cb5bc06580 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -217,7 +217,7 @@ module ActiveRecord
# Returns whether or not this record has been changed in any way (including whether
# any of its nested autosave associations are likewise changed)
def changed_for_autosave?
- new_record? || changed? || marked_for_destruction? || nested_records_changed_for_autosave?
+ !persisted? || changed? || marked_for_destruction? || nested_records_changed_for_autosave?
end
private
@@ -231,7 +231,7 @@ module ActiveRecord
elsif autosave
association.target.find_all { |record| record.changed_for_autosave? }
else
- association.target.find_all { |record| record.new_record? }
+ association.target.find_all { |record| !record.persisted? }
end
end
@@ -257,7 +257,7 @@ module ActiveRecord
# +reflection+.
def validate_collection_association(reflection)
if association = association_instance_get(reflection.name)
- if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave])
+ if records = associated_records_to_validate_or_save(association, !persisted?, reflection.options[:autosave])
records.each { |record| association_valid?(reflection, record) }
end
end
@@ -286,7 +286,7 @@ module ActiveRecord
# Is used as a before_save callback to check while saving a collection
# association whether or not the parent was a new record before saving.
def before_save_collection_association
- @new_record_before_save = new_record?
+ @new_record_before_save = !persisted?
true
end
@@ -308,7 +308,7 @@ module ActiveRecord
if autosave && record.marked_for_destruction?
association.destroy(record)
- elsif autosave != false && (@new_record_before_save || record.new_record?)
+ elsif autosave != false && (@new_record_before_save || !record.persisted?)
if autosave
saved = association.send(:insert_record, record, false, false)
else
@@ -343,7 +343,7 @@ module ActiveRecord
association.destroy
else
key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
- if autosave != false && (new_record? || association.new_record? || association[reflection.primary_key_name] != key || autosave)
+ if autosave != false && (!persisted? || !association.persisted? || association[reflection.primary_key_name] != key || autosave)
association[reflection.primary_key_name] = key
saved = association.save(:validate => !autosave)
raise ActiveRecord::Rollback if !saved && autosave
@@ -363,7 +363,7 @@ module ActiveRecord
if autosave && association.marked_for_destruction?
association.destroy
elsif autosave != false
- saved = association.save(:validate => !autosave) if association.new_record? || autosave
+ saved = association.save(:validate => !autosave) if !association.persisted? || autosave
if association.updated?
association_id = association.send(reflection.options[:primary_key] || :id)
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 06a388cd21..b35f59d6df 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -204,7 +204,7 @@ module ActiveRecord #:nodoc:
#
# # No 'Winter' tag exists
# winter = Tag.find_or_initialize_by_name("Winter")
- # winter.new_record? # true
+ # winter.persisted? # false
#
# To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
# a list of parameters.
@@ -1368,7 +1368,7 @@ MSG
def initialize(attributes = nil)
@attributes = attributes_from_column_definition
@attributes_cache = {}
- @new_record = true
+ @persisted = false
@readonly = false
@destroyed = false
@marked_for_destruction = false
@@ -1403,7 +1403,7 @@ MSG
clear_aggregation_cache
clear_association_cache
@attributes_cache = {}
- @new_record = true
+ @persisted = false
ensure_proper_type
populate_with_current_scope_attributes
@@ -1422,7 +1422,8 @@ MSG
def init_with(coder)
@attributes = coder['attributes']
@attributes_cache, @previously_changed, @changed_attributes = {}, {}, {}
- @new_record = @readonly = @destroyed = @marked_for_destruction = false
+ @readonly = @destroyed = @marked_for_destruction = false
+ @persisted = true
_run_find_callbacks
_run_initialize_callbacks
end
@@ -1463,7 +1464,7 @@ MSG
# Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
def cache_key
case
- when new_record?
+ when !persisted?
"#{self.class.model_name.cache_key}/new"
when timestamp = self[:updated_at]
"#{self.class.model_name.cache_key}/#{id}-#{timestamp.to_s(:number)}"
@@ -1581,11 +1582,20 @@ MSG
self.class.columns_hash[name.to_s]
end
- # Returns true if the +comparison_object+ is the same object, or is of the same type and has the same id.
+ # Returns true if +comparison_object+ is the same exact object, or +comparison_object+
+ # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
+ #
+ # Note that new records are different from any other record by definition, unless the
+ # other record is the receiver itself. Besides, if you fetch existing records with
+ # +select+ and leave the ID out, you're on your own, this predicate will return false.
+ #
+ # Note also that destroying a record preserves its ID in the model instance, so deleted
+ # models are still comparable.
def ==(comparison_object)
comparison_object.equal?(self) ||
- (comparison_object.instance_of?(self.class) &&
- comparison_object.id == id && !comparison_object.new_record?)
+ comparison_object.instance_of?(self.class) &&
+ id.present? &&
+ comparison_object.id == id
end
# Delegates to ==
@@ -1630,7 +1640,7 @@ MSG
# Returns the contents of the record as a nicely formatted string.
def inspect
attributes_as_nice_string = self.class.column_names.collect { |name|
- if has_attribute?(name) || new_record?
+ if has_attribute?(name) || !persisted?
"#{name}: #{attribute_for_inspect(name)}"
end
}.compact.join(", ")
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index b6f87a57b8..bf626301f1 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -109,7 +109,7 @@ module ActiveRecord
def destroy #:nodoc:
return super unless locking_enabled?
- unless new_record?
+ if persisted?
lock_col = self.class.locking_column
previous_value = send(lock_col).to_i
diff --git a/activerecord/lib/active_record/locking/pessimistic.rb b/activerecord/lib/active_record/locking/pessimistic.rb
index 9ad6a2baf7..d900831e13 100644
--- a/activerecord/lib/active_record/locking/pessimistic.rb
+++ b/activerecord/lib/active_record/locking/pessimistic.rb
@@ -47,7 +47,7 @@ module ActiveRecord
# or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
# the locked record.
def lock!(lock = true)
- reload(:lock => lock) unless new_record?
+ reload(:lock => lock) if persisted?
self
end
end
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index a4c09b654a..2c306d233a 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -387,6 +387,8 @@ module ActiveRecord
def copy(destination, sources, options = {})
copied = []
+ FileUtils.mkdir_p(destination) unless File.exists?(destination)
+
destination_migrations = ActiveRecord::Migrator.migrations(destination)
last = destination_migrations.last
sources.each do |name, path|
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index aca91c907d..0c3392263a 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -323,7 +323,7 @@ module ActiveRecord
(options[:update_only] || record.id.to_s == attributes['id'].to_s)
assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
- elsif attributes['id']
+ elsif attributes['id'].present?
raise_nested_attributes_record_not_found(association_name, attributes['id'])
elsif !reject_new_record?(association_name, attributes)
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index 707c1a05be..594a2214bb 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -4,7 +4,7 @@ module ActiveRecord
# Returns true if this object hasn't been saved yet -- that is, a record
# for the object doesn't exist in the data store yet; otherwise, returns false.
def new_record?
- @new_record
+ !@persisted
end
# Returns true if this object has been destroyed, otherwise returns false.
@@ -15,7 +15,7 @@ module ActiveRecord
# Returns if the record is persisted, i.e. it's not a new record and it was
# not destroyed.
def persisted?
- !(new_record? || destroyed?)
+ @persisted && !destroyed?
end
# Saves the model.
@@ -94,8 +94,9 @@ module ActiveRecord
became = klass.new
became.instance_variable_set("@attributes", @attributes)
became.instance_variable_set("@attributes_cache", @attributes_cache)
- became.instance_variable_set("@new_record", new_record?)
+ became.instance_variable_set("@persisted", persisted?)
became.instance_variable_set("@destroyed", destroyed?)
+ became.type = klass.name unless self.class.descends_from_active_record?
became
end
@@ -240,7 +241,7 @@ module ActiveRecord
private
def create_or_update
raise ReadOnlyRecord if readonly?
- result = new_record? ? create : update
+ result = persisted? ? update : create
result != false
end
@@ -269,7 +270,7 @@ module ActiveRecord
self.id ||= new_id
- @new_record = false
+ @persisted = true
id
end
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index 868fd6c3ff..dfe255ad7c 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -14,7 +14,7 @@ module ActiveRecord
config.active_record = ActiveSupport::OrderedOptions.new
config.app_generators.orm :active_record, :migration => true,
- :timestamps => true
+ :timestamps => true
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
"ActiveRecord::QueryCache"
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index 6bf698fe97..c8adaddfca 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -208,14 +208,16 @@ module ActiveRecord
end
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
- group_field = associated ? association.primary_key_name : group_attr
- group_alias = column_alias_for(group_field)
- group_column = column_for(group_field)
+ group_attr = @group_values
+ association = @klass.reflect_on_association(group_attr.first.to_sym)
+ associated = group_attr.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
+ group_fields = Array(associated ? association.primary_key_name : group_attr)
+ group_aliases = group_fields.map { |field| column_alias_for(field) }
+ group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
+ [aliaz, column_for(field)]
+ }
- group = @klass.connection.adapter_name == 'FrontBase' ? group_alias : group_field
+ group = @klass.connection.adapter_name == 'FrontBase' ? group_aliases : group_fields
if operation == 'count' && column_name == :all
aggregate_alias = 'count_all'
@@ -223,22 +225,33 @@ module ActiveRecord
aggregate_alias = column_alias_for(operation, column_name)
end
- relation = except(:group).group(group)
- relation.select_values = [
- operation_over_aggregate_column(aggregate_column(column_name), operation, distinct).as(aggregate_alias),
- "#{group_field} AS #{group_alias}"
+ select_values = [
+ operation_over_aggregate_column(
+ aggregate_column(column_name),
+ operation,
+ distinct).as(aggregate_alias)
]
+ select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
+ "#{field} AS #{aliaz}"
+ }
+
+ relation = except(:group).group(group.join(','))
+ relation.select_values = select_values
+
calculated_data = @klass.connection.select_all(relation.to_sql)
if association
- key_ids = calculated_data.collect { |row| row[group_alias] }
+ key_ids = calculated_data.collect { |row| row[group_aliases.first] }
key_records = association.klass.base_class.find(key_ids)
key_records = Hash[key_records.map { |r| [r.id, r] }]
end
ActiveSupport::OrderedHash[calculated_data.map do |row|
- key = type_cast_calculated_value(row[group_alias], group_column)
+ key = group_columns.map { |aliaz, column|
+ type_cast_calculated_value(row[aliaz], column)
+ }
+ key = key.first if key.size == 1
key = key_records[key] if associated
[key, type_cast_calculated_value(row[aggregate_alias], column_for(column_name), operation)]
end]
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index e9e9c85122..4192456447 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -300,7 +300,7 @@ module ActiveRecord
unless record
conditions = arel.where_sql
conditions = " [#{conditions}]" if conditions
- raise RecordNotFound, "Couldn't find #{@klass.name} with ID=#{id}#{conditions}"
+ raise RecordNotFound, "Couldn't find #{@klass.name} with #{@klass.primary_key}=#{id}#{conditions}"
end
record
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
index c5428dccd6..32c7d08daa 100644
--- a/activerecord/lib/active_record/relation/predicate_builder.rb
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -25,6 +25,11 @@ module ActiveRecord
attribute.in(values)
when Range, Arel::Relation
attribute.in(value)
+ when ActiveRecord::Base
+ attribute.eq(value.quoted_id)
+ when Class
+ # FIXME: I think we need to deprecate this behavior
+ attribute.eq(value.name)
else
attribute.eq(value)
end
diff --git a/activerecord/lib/active_record/session_store.rb b/activerecord/lib/active_record/session_store.rb
index 3fc596e02a..ba99800fb2 100644
--- a/activerecord/lib/active_record/session_store.rb
+++ b/activerecord/lib/active_record/session_store.rb
@@ -228,7 +228,7 @@ module ActiveRecord
@session_id = attributes[:session_id]
@data = attributes[:data]
@marshaled_data = attributes[:marshaled_data]
- @new_record = @marshaled_data.nil?
+ @persisted = !@marshaled_data.nil?
end
# Lazy-unmarshal session state.
@@ -252,8 +252,8 @@ module ActiveRecord
marshaled_data = self.class.marshal(data)
connect = connection
- if @new_record
- @new_record = false
+ unless @persisted
+ @persisted = true
connect.update <<-end_sql, 'Create session'
INSERT INTO #{table_name} (
#{connect.quote_column_name(session_id_column)},
@@ -272,7 +272,7 @@ module ActiveRecord
end
def destroy
- return if @new_record
+ return unless @persisted
connect = connection
connect.delete <<-end_sql, 'Destroy session'
@@ -321,6 +321,7 @@ module ActiveRecord
if sid = current_session_id(env)
Base.silence do
get_session_model(env, sid).destroy
+ env[SESSION_RECORD_KEY] = nil
end
end
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb
index ab737f0f88..8c94d1a2bc 100644
--- a/activerecord/lib/active_record/transactions.rb
+++ b/activerecord/lib/active_record/transactions.rb
@@ -242,7 +242,7 @@ module ActiveRecord
with_transaction_returning_status { super }
end
- # Reset id and @new_record if the transaction rolls back.
+ # Reset id and @persisted if the transaction rolls back.
def rollback_active_record_state!
remember_transaction_record_state
yield
@@ -297,9 +297,9 @@ module ActiveRecord
# Save the new record state and id of a record so it can be restored later if a transaction fails.
def remember_transaction_record_state #:nodoc
@_start_transaction_state ||= {}
- unless @_start_transaction_state.include?(:new_record)
+ unless @_start_transaction_state.include?(:persisted)
@_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
- @_start_transaction_state[:new_record] = @new_record
+ @_start_transaction_state[:persisted] = @persisted
end
unless @_start_transaction_state.include?(:destroyed)
@_start_transaction_state[:destroyed] = @destroyed
@@ -323,7 +323,7 @@ module ActiveRecord
restore_state = remove_instance_variable(:@_start_transaction_state)
if restore_state
@attributes = @attributes.dup if @attributes.frozen?
- @new_record = restore_state[:new_record]
+ @persisted = restore_state[:persisted]
@destroyed = restore_state[:destroyed]
if restore_state[:id]
self.id = restore_state[:id]
@@ -345,11 +345,11 @@ module ActiveRecord
def transaction_include_action?(action) #:nodoc
case action
when :create
- transaction_record_state(:new_record)
+ transaction_record_state(:new_record) || !transaction_record_state(:persisted)
when :destroy
destroyed?
when :update
- !(transaction_record_state(:new_record) || destroyed?)
+ !(transaction_record_state(:new_record) || !transaction_record_state(:persisted) || destroyed?)
end
end
end
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index f367315b22..ee45fcdf35 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -51,7 +51,7 @@ module ActiveRecord
# Runs all the specified validations and returns true if no errors were added otherwise false.
def valid?(context = nil)
- context ||= (new_record? ? :create : :update)
+ context ||= (persisted? ? :update : :create)
output = super(context)
errors.empty? && output
end
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index a25558bd80..3eba7510ac 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -31,7 +31,7 @@ module ActiveRecord
relation = relation.where(scope_item => scope_value)
end
- unless record.new_record?
+ if record.persisted?
# TODO : This should be in Arel
relation = relation.where("#{record.class.quoted_table_name}.#{record.class.primary_key} <> ?", record.send(:id))
end
diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb
index 89eba15be1..0667be7d23 100644
--- a/activerecord/lib/active_record/version.rb
+++ b/activerecord/lib/active_record/version.rb
@@ -3,8 +3,8 @@ module ActiveRecord
MAJOR = 3
MINOR = 1
TINY = 0
- BUILD = "beta"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 0fa4328826..1b0c00bd5a 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -285,10 +285,10 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
final_cut = Client.new("name" => "Final Cut")
firm = Firm.find(1)
final_cut.firm = firm
- assert final_cut.new_record?
+ assert !final_cut.persisted?
assert final_cut.save
- assert !final_cut.new_record?
- assert !firm.new_record?
+ assert final_cut.persisted?
+ assert firm.persisted?
assert_equal firm, final_cut.firm
assert_equal firm, final_cut.firm(true)
end
@@ -297,10 +297,10 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
final_cut = Client.new("name" => "Final Cut")
firm = Firm.find(1)
final_cut.firm_with_primary_key = firm
- assert final_cut.new_record?
+ assert !final_cut.persisted?
assert final_cut.save
- assert !final_cut.new_record?
- assert !firm.new_record?
+ assert final_cut.persisted?
+ assert firm.persisted?
assert_equal firm, final_cut.firm_with_primary_key
assert_equal firm, final_cut.firm_with_primary_key(true)
end
diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
index b124a2bfc3..fb59f63f91 100644
--- a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
+++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
@@ -17,7 +17,7 @@ class EagerLoadIncludeFullStiClassNamesTest < ActiveRecord::TestCase
def generate_test_objects
post = Namespaced::Post.create( :title => 'Great stuff', :body => 'This is not', :author_id => 1 )
- tagging = Tagging.create( :taggable => post )
+ Tagging.create( :taggable => post )
end
def test_class_names
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index cae51ee211..10fb80f822 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -323,7 +323,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_many_through_a_belongs_to_association
author = authors(:mary)
- post = Post.create!(:author => author, :title => "TITLE", :body => "BODY")
+ Post.create!(:author => author, :title => "TITLE", :body => "BODY")
author.author_favorites.create(:favorite_author_id => 1)
author.author_favorites.create(:favorite_author_id => 2)
posts_with_author_favorites = author.posts.find(:all, :include => :author_favorites)
@@ -521,7 +521,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_inheritance
- posts = SpecialPost.find(:all, :include => [ :comments ])
+ SpecialPost.find(:all, :include => [ :comments ])
end
def test_eager_has_one_with_association_inheritance
@@ -561,16 +561,16 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_invalid_association_reference
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- post = Post.find(6, :include=> :monkeys )
+ Post.find(6, :include=> :monkeys )
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- post = Post.find(6, :include=>[ :monkeys ])
+ Post.find(6, :include=>[ :monkeys ])
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- post = Post.find(6, :include=>[ 'monkeys' ])
+ Post.find(6, :include=>[ 'monkeys' ])
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys, :elephants") {
- post = Post.find(6, :include=>[ :monkeys, :elephants ])
+ Post.find(6, :include=>[ :monkeys, :elephants ])
}
end
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index c6777d0cb3..513f76255c 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -251,10 +251,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
no_of_projects = Project.count
aredridel = Developer.new("name" => "Aredridel")
aredridel.projects.concat([Project.find(1), p = Project.new("name" => "Projekt")])
- assert aredridel.new_record?
- assert p.new_record?
+ assert !aredridel.persisted?
+ assert !p.persisted?
assert aredridel.save
- assert !aredridel.new_record?
+ assert aredridel.persisted?
assert_equal no_of_devels+1, Developer.count
assert_equal no_of_projects+1, Project.count
assert_equal 2, aredridel.projects.size
@@ -288,22 +288,22 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal devel.projects.last, proj
assert devel.projects.loaded?
- assert proj.new_record?
+ assert !proj.persisted?
devel.save
- assert !proj.new_record?
+ assert proj.persisted?
assert_equal devel.projects.last, proj
assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated
end
def test_build_by_new_record
devel = Developer.new(:name => "Marcel", :salary => 75000)
- proj1 = devel.projects.build(:name => "Make bed")
+ devel.projects.build(:name => "Make bed")
proj2 = devel.projects.build(:name => "Lie in it")
assert_equal devel.projects.last, proj2
- assert proj2.new_record?
+ assert !proj2.persisted?
devel.save
- assert !devel.new_record?
- assert !proj2.new_record?
+ assert devel.persisted?
+ assert proj2.persisted?
assert_equal devel.projects.last, proj2
assert_equal Developer.find_by_name("Marcel").projects.last, proj2 # prove join table is updated
end
@@ -316,19 +316,19 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal devel.projects.last, proj
assert !devel.projects.loaded?
- assert !proj.new_record?
+ assert proj.persisted?
assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated
end
def test_create_by_new_record
devel = Developer.new(:name => "Marcel", :salary => 75000)
- proj1 = devel.projects.build(:name => "Make bed")
+ devel.projects.build(:name => "Make bed")
proj2 = devel.projects.build(:name => "Lie in it")
assert_equal devel.projects.last, proj2
- assert proj2.new_record?
+ assert !proj2.persisted?
devel.save
- assert !devel.new_record?
- assert !proj2.new_record?
+ assert devel.persisted?
+ assert proj2.persisted?
assert_equal devel.projects.last, proj2
assert_equal Developer.find_by_name("Marcel").projects.last, proj2 # prove join table is updated
end
@@ -343,7 +343,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
# in Oracle '' is saved as null therefore need to save ' ' in not null column
another_post = categories(:general).post_with_conditions.create(:body => ' ')
- assert !another_post.new_record?
+ assert another_post.persisted?
assert_equal 'Yet Another Testing Title', another_post.title
end
@@ -559,8 +559,6 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_dynamic_find_should_respect_association_order
# Developers are ordered 'name DESC, id DESC'
- low_id_jamis = developers(:jamis)
- middle_id_jamis = developers(:poor_jamis)
high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis')
assert_equal high_id_jamis, projects(:active_record).developers.find(:first, :conditions => "name = 'Jamis'")
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index c9f00fd737..33c53e695b 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -66,6 +66,17 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal 'exotic', bulb.name
end
+ def test_no_sql_should_be_fired_if_association_already_loaded
+ car = Car.create(:name => 'honda')
+ bulb = car.bulbs.create
+ bulbs = Car.first.bulbs
+ bulbs.inspect # to load all instances of bulbs
+ assert_no_queries do
+ bulbs.first()
+ bulbs.first({})
+ end
+ end
+
def test_create_resets_cached_counters
person = Person.create!(:first_name => 'tenderlove')
post = Post.first
@@ -73,7 +84,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [], person.readers
assert_nil person.readers.find_by_post_id(post.id)
- reader = person.readers.create(:post_id => post.id)
+ person.readers.create(:post_id => post.id)
assert_equal 1, person.readers.count
assert_equal 1, person.readers.length
@@ -88,7 +99,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [], person.readers
assert_nil person.readers.find_by_post_id(post.id)
- reader = person.readers.find_or_create_by_post_id(post.id)
+ person.readers.find_or_create_by_post_id(post.id)
assert_equal 1, person.readers.count
assert_equal 1, person.readers.length
@@ -187,7 +198,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
another = author.posts.find_or_create_by_title_and_body("Another Post", "This is the Body")
assert_equal number_of_posts + 1, Post.count
assert_equal another, author.posts.find_or_create_by_title_and_body("Another Post", "This is the Body")
- assert !another.new_record?
+ assert another.persisted?
end
def test_cant_save_has_many_readonly_association
@@ -402,7 +413,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_adding_using_create
first_firm = companies(:first_firm)
assert_equal 2, first_firm.plain_clients.size
- natural = first_firm.plain_clients.create(:name => "Natural Company")
+ first_firm.plain_clients.create(:name => "Natural Company")
assert_equal 3, first_firm.plain_clients.length
assert_equal 3, first_firm.plain_clients.size
end
@@ -453,7 +464,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !company.clients_of_firm.loaded?
assert_equal "Another Client", new_client.name
- assert new_client.new_record?
+ assert !new_client.persisted?
assert_equal new_client, company.clients_of_firm.last
end
@@ -483,7 +494,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_build_followed_by_save_does_not_load_target
- new_client = companies(:first_firm).clients_of_firm.build("name" => "Another Client")
+ companies(:first_firm).clients_of_firm.build("name" => "Another Client")
assert companies(:first_firm).save
assert !companies(:first_firm).clients_of_firm.loaded?
end
@@ -508,7 +519,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !company.clients_of_firm.loaded?
assert_equal "Another Client", new_client.name
- assert new_client.new_record?
+ assert !new_client.persisted?
assert_equal new_client, company.clients_of_firm.last
end
@@ -543,7 +554,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_create
force_signal37_to_load_all_clients_of_firm
new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
- assert !new_client.new_record?
+ assert new_client.persisted?
assert_equal new_client, companies(:first_firm).clients_of_firm.last
assert_equal new_client, companies(:first_firm).clients_of_firm(true).last
end
@@ -554,7 +565,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_create_followed_by_save_does_not_load_target
- new_client = companies(:first_firm).clients_of_firm.create("name" => "Another Client")
+ companies(:first_firm).clients_of_firm.create("name" => "Another Client")
assert companies(:first_firm).save
assert !companies(:first_firm).clients_of_firm.loaded?
end
@@ -563,7 +574,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
the_client = companies(:first_firm).clients.find_or_initialize_by_name("Yet another client")
assert_equal companies(:first_firm).id, the_client.firm_id
assert_equal "Yet another client", the_client.name
- assert the_client.new_record?
+ assert !the_client.persisted?
end
def test_find_or_create_updates_size
@@ -752,7 +763,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create
- assert !another_ms_client.new_record?
+ assert another_ms_client.persisted?
assert_equal 'Microsoft', another_ms_client.name
end
@@ -852,7 +863,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_dependence_for_associations_with_hash_condition
david = authors(:david)
- post = posts(:thinking).id
assert_difference('Post.count', -1) { assert david.destroy }
end
@@ -872,7 +882,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_three_levels_of_dependence
topic = Topic.create "title" => "neat and simple"
reply = topic.replies.create "title" => "neat and simple", "content" => "still digging it"
- silly_reply = reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
+ reply.replies.create "title" => "neat and simple", "content" => "ain't complaining"
assert_nothing_raised { topic.destroy }
end
@@ -897,7 +907,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_depends_and_nullify
num_accounts = Account.count
- num_companies = Company.count
core = companies(:rails_core)
assert_equal accounts(:rails_core_account), core.account
@@ -914,7 +923,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_restrict
firm = RestrictedFirm.new(:name => 'restrict')
firm.save!
- child_firm = firm.companies.create(:name => 'child')
+ firm.companies.create(:name => 'child')
assert !firm.companies.empty?
assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
end
@@ -1273,4 +1282,25 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
comment = post.comments.build
assert post.comments.include?(comment)
end
+
+ def test_load_target_respects_protected_attributes
+ topic = Topic.create!
+ reply = topic.replies.create(:title => "reply 1")
+ reply.approved = false
+ reply.save!
+
+ # Save with a different object instance, so the instance that's still held
+ # in topic.relies doesn't know about the changed attribute.
+ reply2 = Reply.find(reply.id)
+ reply2.approved = true
+ reply2.save!
+
+ # Force loading the collection from the db. This will merge the existing
+ # object (reply) with what gets loaded from the db (which includes the
+ # changed approved attribute). approved is a protected attribute, so if mass
+ # assignment is used, it won't get updated and will still be false.
+ first = topic.replies.to_a.first
+ assert_equal reply.id, first.id
+ assert_equal true, first.approved?
+ end
end
diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb
index 4e398751d2..7c3d20e8bd 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -472,4 +472,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
authors = Author.joins(:essay_categories_2).where('categories.id' => categories(:general).id)
assert_equal authors(:david), authors.first
end
+
+ def test_size_of_through_association_should_increase_correctly_when_has_many_association_is_added
+ post = posts(:thinking)
+ readers = post.readers.size
+ post.people << people(:michael)
+ assert_equal readers + 1, post.readers.size
+ end
end
diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb
index b522be3fe0..6fbeff8aa9 100644
--- a/activerecord/test/cases/associations/has_one_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_associations_test.rb
@@ -268,7 +268,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_assignment_before_child_saved
firm = Firm.find(1)
firm.account = a = Account.new("credit_limit" => 1000)
- assert !a.new_record?
+ assert a.persisted?
assert_equal a, firm.account
assert_equal a, firm.account
assert_equal a, firm.account(true)
@@ -323,7 +323,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_create_respects_hash_condition
account = companies(:first_firm).create_account_limit_500_with_hash_conditions
- assert !account.new_record?
+ assert account.persisted?
assert_equal 500, account.credit_limit
end
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
index fa5c2e49df..081583038f 100644
--- a/activerecord/test/cases/associations/inverse_associations_test.rb
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -551,8 +551,8 @@ class InverseMultipleHasManyInversesForSameModel < ActiveRecord::TestCase
def test_that_we_can_load_associations_that_have_the_same_reciprocal_name_from_different_models
assert_nothing_raised(ActiveRecord::AssociationTypeMismatch) do
i = Interest.find(:first)
- z = i.zine
- m = i.man
+ i.zine
+ i.man
end
end
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index 385505b109..217d06f3d9 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -442,11 +442,11 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
new_tag = Tag.new(:name => "new")
saved_post.tags << new_tag
- assert !new_tag.new_record? #consistent with habtm!
- assert !saved_post.new_record?
+ assert new_tag.persisted? #consistent with habtm!
+ assert saved_post.persisted?
assert saved_post.tags.include?(new_tag)
- assert !new_tag.new_record?
+ assert new_tag.persisted?
assert saved_post.reload.tags(true).include?(new_tag)
@@ -454,16 +454,16 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
saved_tag = tags(:general)
new_post.tags << saved_tag
- assert new_post.new_record?
- assert !saved_tag.new_record?
+ assert !new_post.persisted?
+ assert saved_tag.persisted?
assert new_post.tags.include?(saved_tag)
new_post.save!
- assert !new_post.new_record?
+ assert new_post.persisted?
assert new_post.reload.tags(true).include?(saved_tag)
- assert posts(:thinking).tags.build.new_record?
- assert posts(:thinking).tags.new.new_record?
+ assert !posts(:thinking).tags.build.persisted?
+ assert !posts(:thinking).tags.new.persisted?
end
def test_create_associate_when_adding_to_has_many_through
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index dd8152b219..93a51d3606 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -120,7 +120,7 @@ class AssociationsTest < ActiveRecord::TestCase
def test_force_reload_is_uncached
firm = Firm.create!("name" => "A New Firm, Inc")
- client = Client.create!("name" => "TheClient.com", :firm => firm)
+ Client.create!("name" => "TheClient.com", :firm => firm)
ActiveRecord::Base.cache do
firm.clients.each {}
assert_queries(0) { assert_not_nil firm.clients.each {} }
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index ab9a65944f..bb0166a60c 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -568,7 +568,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
def test_bulk_update_respects_access_control
privatize("title=(value)")
- assert_raise(ActiveRecord::UnknownAttributeError) { topic = @target.new(:title => "Rants about pants") }
+ assert_raise(ActiveRecord::UnknownAttributeError) { @target.new(:title => "Rants about pants") }
assert_raise(ActiveRecord::UnknownAttributeError) { @target.new.attributes = { :title => "Ants in pants" } }
end
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 89be94c81f..b13cb2d7a2 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -83,7 +83,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
assert !firm.build_account_using_primary_key.valid?
assert firm.save
- assert firm.account_using_primary_key.new_record?
+ assert !firm.account_using_primary_key.persisted?
end
def test_save_fails_for_invalid_has_one
@@ -114,10 +114,10 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
account = firm.account.build("credit_limit" => 1000)
assert_equal account, firm.account
- assert account.new_record?
+ assert !account.persisted?
assert firm.save
assert_equal account, firm.account
- assert !account.new_record?
+ assert account.persisted?
end
def test_build_before_either_saved
@@ -125,16 +125,16 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
firm.account = account = Account.new("credit_limit" => 1000)
assert_equal account, firm.account
- assert account.new_record?
+ assert !account.persisted?
assert firm.save
assert_equal account, firm.account
- assert !account.new_record?
+ assert account.persisted?
end
def test_assignment_before_parent_saved
firm = Firm.new("name" => "GlobalMegaCorp")
firm.account = a = Account.find(1)
- assert firm.new_record?
+ assert !firm.persisted?
assert_equal a, firm.account
assert firm.save
assert_equal a, firm.account
@@ -144,12 +144,12 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
def test_assignment_before_either_saved
firm = Firm.new("name" => "GlobalMegaCorp")
firm.account = a = Account.new("credit_limit" => 1000)
- assert firm.new_record?
- assert a.new_record?
+ assert !firm.persisted?
+ assert !a.persisted?
assert_equal a, firm.account
assert firm.save
- assert !firm.new_record?
- assert !a.new_record?
+ assert firm.persisted?
+ assert a.persisted?
assert_equal a, firm.account
assert_equal a, firm.account(true)
end
@@ -203,7 +203,7 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
assert !client.firm.valid?
assert client.save
- assert client.firm.new_record?
+ assert !client.firm.persisted?
end
def test_save_fails_for_invalid_belongs_to
@@ -232,10 +232,10 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
apple = Firm.new("name" => "Apple")
client.firm = apple
assert_equal apple, client.firm
- assert apple.new_record?
+ assert !apple.persisted?
assert client.save
assert apple.save
- assert !apple.new_record?
+ assert apple.persisted?
assert_equal apple, client.firm
assert_equal apple, client.firm(true)
end
@@ -244,11 +244,11 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
final_cut = Client.new("name" => "Final Cut")
apple = Firm.new("name" => "Apple")
final_cut.firm = apple
- assert final_cut.new_record?
- assert apple.new_record?
+ assert !final_cut.persisted?
+ assert !apple.persisted?
assert final_cut.save
- assert !final_cut.new_record?
- assert !apple.new_record?
+ assert final_cut.persisted?
+ assert apple.persisted?
assert_equal apple, final_cut.firm
assert_equal apple, final_cut.firm(true)
end
@@ -348,23 +348,21 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
def test_invalid_adding
firm = Firm.find(1)
assert !(firm.clients_of_firm << c = Client.new)
- assert c.new_record?
+ assert !c.persisted?
assert !firm.valid?
assert !firm.save
- assert c.new_record?
+ assert !c.persisted?
end
def test_invalid_adding_before_save
- no_of_firms = Firm.count
- no_of_clients = Client.count
new_firm = Firm.new("name" => "A New Firm, Inc")
new_firm.clients_of_firm.concat([c = Client.new, Client.new("name" => "Apple")])
- assert c.new_record?
+ assert !c.persisted?
assert !c.valid?
assert !new_firm.valid?
assert !new_firm.save
- assert c.new_record?
- assert new_firm.new_record?
+ assert !c.persisted?
+ assert !new_firm.persisted?
end
def test_invalid_adding_with_validate_false
@@ -375,7 +373,7 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
assert firm.valid?
assert !client.valid?
assert firm.save
- assert client.new_record?
+ assert !client.persisted?
end
def test_valid_adding_with_validate_false
@@ -386,22 +384,22 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
assert firm.valid?
assert client.valid?
- assert client.new_record?
+ assert !client.persisted?
firm.unvalidated_clients_of_firm << client
assert firm.save
- assert !client.new_record?
+ assert client.persisted?
assert_equal no_of_clients + 1, Client.count
end
def test_invalid_build
new_client = companies(:first_firm).clients_of_firm.build
- assert new_client.new_record?
+ assert !new_client.persisted?
assert !new_client.valid?
assert_equal new_client, companies(:first_firm).clients_of_firm.last
assert !companies(:first_firm).save
- assert new_client.new_record?
+ assert !new_client.persisted?
assert_equal 1, companies(:first_firm).clients_of_firm(true).size
end
@@ -420,8 +418,8 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
assert_equal no_of_firms, Firm.count # Firm was not saved to database.
assert_equal no_of_clients, Client.count # Clients were not saved to database.
assert new_firm.save
- assert !new_firm.new_record?
- assert !c.new_record?
+ assert new_firm.persisted?
+ assert c.persisted?
assert_equal new_firm, c.firm
assert_equal no_of_firms + 1, Firm.count # Firm was saved to database.
assert_equal no_of_clients + 2, Client.count # Clients were saved to database.
@@ -455,13 +453,13 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
company.name += '-changed'
assert_queries(2) { assert company.save }
- assert !new_client.new_record?
+ assert new_client.persisted?
assert_equal 2, company.clients_of_firm(true).size
end
def test_build_many_before_save
company = companies(:first_firm)
- new_clients = assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
+ assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
company.name += '-changed'
assert_queries(3) { assert company.save }
@@ -475,13 +473,13 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
company.name += '-changed'
assert_queries(2) { assert company.save }
- assert !new_client.new_record?
+ assert new_client.persisted?
assert_equal 2, company.clients_of_firm(true).size
end
def test_build_many_via_block_before_save
company = companies(:first_firm)
- new_clients = assert_no_queries do
+ assert_no_queries do
company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) do |client|
client.name = "changed"
end
@@ -507,62 +505,62 @@ class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase
new_account = Account.new("credit_limit" => 1000)
new_firm = Firm.new("name" => "some firm")
- assert new_firm.new_record?
+ assert !new_firm.persisted?
new_account.firm = new_firm
new_account.save!
- assert !new_firm.new_record?
+ assert new_firm.persisted?
new_account = Account.new("credit_limit" => 1000)
new_autosaved_firm = Firm.new("name" => "some firm")
- assert new_autosaved_firm.new_record?
+ assert !new_autosaved_firm.persisted?
new_account.unautosaved_firm = new_autosaved_firm
new_account.save!
- assert new_autosaved_firm.new_record?
+ assert !new_autosaved_firm.persisted?
end
def test_autosave_new_record_on_has_one_can_be_disabled_per_relationship
firm = Firm.new("name" => "some firm")
account = Account.new("credit_limit" => 1000)
- assert account.new_record?
+ assert !account.persisted?
firm.account = account
firm.save!
- assert !account.new_record?
+ assert account.persisted?
firm = Firm.new("name" => "some firm")
account = Account.new("credit_limit" => 1000)
firm.unautosaved_account = account
- assert account.new_record?
+ assert !account.persisted?
firm.unautosaved_account = account
firm.save!
- assert account.new_record?
+ assert !account.persisted?
end
def test_autosave_new_record_on_has_many_can_be_disabled_per_relationship
firm = Firm.new("name" => "some firm")
account = Account.new("credit_limit" => 1000)
- assert account.new_record?
+ assert !account.persisted?
firm.accounts << account
firm.save!
- assert !account.new_record?
+ assert account.persisted?
firm = Firm.new("name" => "some firm")
account = Account.new("credit_limit" => 1000)
- assert account.new_record?
+ assert !account.persisted?
firm.unautosaved_accounts << account
firm.save!
- assert account.new_record?
+ assert !account.persisted?
end
end
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index ceb1272862..26f388ca46 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -182,7 +182,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_initialize_with_invalid_attribute
begin
- topic = Topic.new({ "title" => "test",
+ Topic.new({ "title" => "test",
"last_read(1i)" => "2005", "last_read(2i)" => "2", "last_read(3i)" => "31"})
rescue ActiveRecord::MultiparameterAssignmentErrors => ex
assert_equal(1, ex.errors.size)
@@ -397,6 +397,15 @@ class BasicsTest < ActiveRecord::TestCase
assert_not_equal Topic.new, Topic.new
end
+ def test_equality_of_destroyed_records
+ topic_1 = Topic.new(:title => 'test_1')
+ topic_1.save
+ topic_2 = Topic.find(topic_1.id)
+ topic_1.destroy
+ assert_equal topic_1, topic_2
+ assert_equal topic_2, topic_1
+ end
+
def test_hashing
assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ]
end
@@ -656,8 +665,8 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_new_record_returns_boolean
- assert_equal true, Topic.new.new_record?
- assert_equal false, Topic.find(1).new_record?
+ assert_equal false, Topic.new.persisted?
+ assert_equal true, Topic.find(1).persisted?
end
def test_clone
@@ -665,7 +674,7 @@ class BasicsTest < ActiveRecord::TestCase
cloned_topic = nil
assert_nothing_raised { cloned_topic = topic.clone }
assert_equal topic.title, cloned_topic.title
- assert cloned_topic.new_record?
+ assert !cloned_topic.persisted?
# test if the attributes have been cloned
topic.title = "a"
@@ -684,7 +693,7 @@ class BasicsTest < ActiveRecord::TestCase
# test if saved clone object differs from original
cloned_topic.save
- assert !cloned_topic.new_record?
+ assert cloned_topic.persisted?
assert_not_equal cloned_topic.id, topic.id
cloned_topic.reload
@@ -700,7 +709,7 @@ class BasicsTest < ActiveRecord::TestCase
assert_nothing_raised { clone = dev.clone }
assert_kind_of DeveloperSalary, clone.salary
assert_equal dev.salary.amount, clone.salary.amount
- assert clone.new_record?
+ assert !clone.persisted?
# test if the attributes have been cloned
original_amount = clone.salary.amount
@@ -708,7 +717,7 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal original_amount, clone.salary.amount
assert clone.save
- assert !clone.new_record?
+ assert clone.persisted?
assert_not_equal clone.id, dev.id
end
@@ -963,7 +972,6 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_nil_serialized_attribute_with_class_constraint
- myobj = MyObject.new('value1', 'value2')
topic = Topic.new
assert_nil topic.content
end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 61fbf01a50..5cb8485b4b 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -54,6 +54,19 @@ class CalculationsTest < ActiveRecord::TestCase
c = Account.sum(:credit_limit, :group => :firm_id)
[1,6,2].each { |firm_id| assert c.keys.include?(firm_id) }
end
+
+ def test_should_group_by_multiple_fields
+ c = Account.count(:all, :group => ['firm_id', :credit_limit])
+ [ [nil, 50], [1, 50], [6, 50], [6, 55], [9, 53], [2, 60] ].each { |firm_and_limit| assert c.keys.include?(firm_and_limit) }
+ end
+
+ def test_should_group_by_multiple_fields_having_functions
+ c = Topic.group(:author_name, 'COALESCE(type, title)').count(:all)
+ assert_equal 1, c[["Carl", "The Third Topic of the day"]]
+ assert_equal 1, c[["Mary", "Reply"]]
+ assert_equal 1, c[["David", "The First Topic"]]
+ assert_equal 1, c[["Carl", "Reply"]]
+ end
def test_should_group_by_summed_field
c = Account.sum(:credit_limit, :group => :firm_id)
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 4c9475f1cd..f4af6506c5 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -10,6 +10,7 @@ require 'models/entrant'
require 'models/project'
require 'models/developer'
require 'models/customer'
+require 'models/toy'
class FinderTest < ActiveRecord::TestCase
fixtures :companies, :topics, :entrants, :developers, :developers_projects, :posts, :comments, :accounts, :authors, :customers, :categories, :categorizations
@@ -728,7 +729,7 @@ class FinderTest < ActiveRecord::TestCase
sig38 = Company.find_or_create_by_name("38signals")
assert_equal number_of_companies + 1, Company.count
assert_equal sig38, Company.find_or_create_by_name("38signals")
- assert !sig38.new_record?
+ assert sig38.persisted?
end
def test_find_or_create_from_two_attributes
@@ -736,7 +737,7 @@ class FinderTest < ActiveRecord::TestCase
another = Topic.find_or_create_by_title_and_author_name("Another topic","John")
assert_equal number_of_topics + 1, Topic.count
assert_equal another, Topic.find_or_create_by_title_and_author_name("Another topic", "John")
- assert !another.new_record?
+ assert another.persisted?
end
def test_find_or_create_from_two_attributes_with_one_being_an_aggregate
@@ -744,7 +745,7 @@ class FinderTest < ActiveRecord::TestCase
created_customer = Customer.find_or_create_by_balance_and_name(Money.new(123), "Elizabeth")
assert_equal number_of_customers + 1, Customer.count
assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123), "Elizabeth")
- assert !created_customer.new_record?
+ assert created_customer.persisted?
end
def test_find_or_create_from_one_attribute_and_hash
@@ -752,7 +753,7 @@ class FinderTest < ActiveRecord::TestCase
sig38 = Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
assert_equal number_of_companies + 1, Company.count
assert_equal sig38, Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
- assert !sig38.new_record?
+ assert sig38.persisted?
assert_equal "38signals", sig38.name
assert_equal 17, sig38.firm_id
assert_equal 23, sig38.client_of
@@ -763,7 +764,7 @@ class FinderTest < ActiveRecord::TestCase
created_customer = Customer.find_or_create_by_balance(Money.new(123))
assert_equal number_of_customers + 1, Customer.count
assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123))
- assert !created_customer.new_record?
+ assert created_customer.persisted?
end
def test_find_or_create_from_one_aggregate_attribute_and_hash
@@ -773,7 +774,7 @@ class FinderTest < ActiveRecord::TestCase
created_customer = Customer.find_or_create_by_balance({:balance => balance, :name => name})
assert_equal number_of_customers + 1, Customer.count
assert_equal created_customer, Customer.find_or_create_by_balance({:balance => balance, :name => name})
- assert !created_customer.new_record?
+ assert created_customer.persisted?
assert_equal balance, created_customer.balance
assert_equal name, created_customer.name
end
@@ -781,13 +782,13 @@ class FinderTest < ActiveRecord::TestCase
def test_find_or_initialize_from_one_attribute
sig38 = Company.find_or_initialize_by_name("38signals")
assert_equal "38signals", sig38.name
- assert sig38.new_record?
+ assert !sig38.persisted?
end
def test_find_or_initialize_from_one_aggregate_attribute
new_customer = Customer.find_or_initialize_by_balance(Money.new(123))
assert_equal 123, new_customer.balance.amount
- assert new_customer.new_record?
+ assert !new_customer.persisted?
end
def test_find_or_initialize_from_one_attribute_should_not_set_attribute_even_when_protected
@@ -795,7 +796,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_not_equal 1000, c.rating
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_from_one_attribute_should_not_set_attribute_even_when_protected
@@ -803,7 +804,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_not_equal 1000, c.rating
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_initialize_from_one_attribute_should_set_attribute_even_when_protected
@@ -811,7 +812,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_from_one_attribute_should_set_attribute_even_when_protected
@@ -819,7 +820,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_initialize_from_one_attribute_should_set_attribute_even_when_protected_and_also_set_the_hash
@@ -827,7 +828,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_from_one_attribute_should_set_attribute_even_when_protected_and_also_set_the_hash
@@ -835,7 +836,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000, c.rating
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_initialize_should_set_protected_attributes_if_given_as_block
@@ -843,7 +844,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000.to_f, c.rating.to_f
assert c.valid?
- assert c.new_record?
+ assert !c.persisted?
end
def test_find_or_create_should_set_protected_attributes_if_given_as_block
@@ -851,7 +852,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000.to_f, c.rating.to_f
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_create_should_work_with_block_on_first_call
@@ -862,21 +863,21 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "Fortune 1000", c.name
assert_equal 1000.to_f, c.rating.to_f
assert c.valid?
- assert !c.new_record?
+ assert c.persisted?
end
def test_find_or_initialize_from_two_attributes
another = Topic.find_or_initialize_by_title_and_author_name("Another topic","John")
assert_equal "Another topic", another.title
assert_equal "John", another.author_name
- assert another.new_record?
+ assert !another.persisted?
end
def test_find_or_initialize_from_one_aggregate_attribute_and_one_not
new_customer = Customer.find_or_initialize_by_balance_and_name(Money.new(123), "Elizabeth")
assert_equal 123, new_customer.balance.amount
assert_equal "Elizabeth", new_customer.name
- assert new_customer.new_record?
+ assert !new_customer.persisted?
end
def test_find_or_initialize_from_one_attribute_and_hash
@@ -884,7 +885,7 @@ class FinderTest < ActiveRecord::TestCase
assert_equal "38signals", sig38.name
assert_equal 17, sig38.firm_id
assert_equal 23, sig38.client_of
- assert sig38.new_record?
+ assert !sig38.persisted?
end
def test_find_or_initialize_from_one_aggregate_attribute_and_hash
@@ -893,7 +894,7 @@ class FinderTest < ActiveRecord::TestCase
new_customer = Customer.find_or_initialize_by_balance({:balance => balance, :name => name})
assert_equal balance, new_customer.balance
assert_equal name, new_customer.name
- assert new_customer.new_record?
+ assert !new_customer.persisted?
end
def test_find_with_bad_sql
@@ -950,7 +951,7 @@ class FinderTest < ActiveRecord::TestCase
# http://dev.rubyonrails.org/ticket/6778
def test_find_ignores_previously_inserted_record
- post = Post.create!(:title => 'test', :body => 'it out')
+ Post.create!(:title => 'test', :body => 'it out')
assert_equal [], Post.find_all_by_id(nil)
end
@@ -1012,6 +1013,15 @@ class FinderTest < ActiveRecord::TestCase
end
end
+ def test_find_one_message_with_custom_primary_key
+ Toy.set_primary_key :name
+ begin
+ Toy.find 'Hello World!'
+ rescue ActiveRecord::RecordNotFound => e
+ assert_equal 'Couldn\'t find Toy with name=Hello World!', e.message
+ end
+ end
+
protected
def bind(statement, *vars)
if vars.first.is_a?(Hash)
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index d5ef30e137..9ce163a00f 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -58,7 +58,7 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_inserts
- topics = create_fixtures("topics")
+ create_fixtures("topics")
first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'David'")
assert_equal("The First Topic", first_row["title"])
@@ -114,7 +114,7 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_insert_with_datetime
- topics = create_fixtures("tasks")
+ create_fixtures("tasks")
first = Task.find(1)
assert first
end
@@ -240,7 +240,7 @@ if Account.connection.respond_to?(:reset_pk_sequence!)
def test_create_fixtures_resets_sequences_when_not_cached
@instances.each do |instance|
- max_id = create_fixtures(instance.class.table_name).inject(0) do |_max_id, (name, fixture)|
+ max_id = create_fixtures(instance.class.table_name).inject(0) do |_max_id, (_, fixture)|
fixture_id = fixture['id'].to_i
fixture_id > _max_id ? fixture_id : _max_id
end
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index e6eef805cf..ab9b35172b 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -1947,7 +1947,7 @@ if ActiveRecord::Base.connection.supports_migrations?
@migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
@existing_migrations = Dir[@migrations_path + "/*.rb"]
- Time.travel_to(created_at = Time.utc(2010, 7, 26, 10, 10, 10)) do
+ Time.travel_to(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.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
@@ -1972,7 +1972,7 @@ if ActiveRecord::Base.connection.supports_migrations?
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
+ Time.travel_to(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.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
@@ -1992,7 +1992,7 @@ if ActiveRecord::Base.connection.supports_migrations?
@migrations_path = MIGRATIONS_ROOT + "/valid_with_timestamps"
@existing_migrations = Dir[@migrations_path + "/*.rb"]
- Time.travel_to(created_at = Time.utc(2010, 2, 20, 10, 10, 10)) do
+ Time.travel_to(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.rb")
assert File.exists?(@migrations_path + "/20100301010103_people_have_descriptions.rb")
@@ -2024,11 +2024,26 @@ if ActiveRecord::Base.connection.supports_migrations?
clear
end
+ def test_copying_migrations_to_non_existing_directory
+ @migrations_path = MIGRATIONS_ROOT + "/non_existing"
+ @existing_migrations = []
+
+ Time.travel_to(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.rb")
+ assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
+ assert_equal 2, copied.length
+ end
+ ensure
+ clear
+ Dir.delete(@migrations_path)
+ 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
+ Time.travel_to(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.rb")
assert File.exists?(@migrations_path + "/20100726101011_people_have_descriptions.rb")
diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb
index fb24c65fff..6ac3e3fc56 100644
--- a/activerecord/test/cases/named_scope_test.rb
+++ b/activerecord/test/cases/named_scope_test.rb
@@ -122,7 +122,7 @@ class NamedScopeTest < ActiveRecord::TestCase
:joins => 'JOIN authors ON authors.id = posts.author_id',
:conditions => [ 'authors.author_address_id = ?', address.id ]
)
- assert_equal posts_with_authors_at_address_titles, Post.with_authors_at_address(address).find(:all, :select => 'title')
+ assert_equal posts_with_authors_at_address_titles.map(&:title), Post.with_authors_at_address(address).find(:all, :select => 'title').map(&:title)
end
def test_scope_with_object
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 60f89da95e..92af53d56f 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -139,6 +139,14 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
assert_equal 'gardening', interest.reload.topic
end
+ def test_reject_if_with_blank_nested_attributes_id
+ # When using a select list to choose an existing 'ship' id, with :include_blank => true
+ Pirate.accepts_nested_attributes_for :ship, :reject_if => proc {|attributes| attributes[:id].blank? }
+
+ pirate = Pirate.new(:catchphrase => "Stop wastin' me time")
+ pirate.ship_attributes = { :id => "" }
+ assert_nothing_raised(ActiveRecord::RecordNotFound) { pirate.save! }
+ end
end
class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
@@ -163,7 +171,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
@ship.destroy
@pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger' }
- assert @pirate.ship.new_record?
+ assert !@pirate.ship.persisted?
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
end
@@ -184,7 +192,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_replace_an_existing_record_if_there_is_no_id
@pirate.reload.ship_attributes = { :name => 'Davy Jones Gold Dagger' }
- assert @pirate.ship.new_record?
+ assert !@pirate.ship.persisted?
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
assert_equal 'Nights Dirty Lightning', @ship.name
end
@@ -256,7 +264,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_also_work_with_a_HashWithIndifferentAccess
@pirate.ship_attributes = HashWithIndifferentAccess.new(:id => @ship.id, :name => 'Davy Jones Gold Dagger')
- assert !@pirate.ship.new_record?
+ assert @pirate.ship.persisted?
assert_equal 'Davy Jones Gold Dagger', @pirate.ship.name
end
@@ -348,7 +356,7 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
@pirate.destroy
@ship.reload.pirate_attributes = { :catchphrase => 'Arr' }
- assert @ship.pirate.new_record?
+ assert !@ship.pirate.persisted?
assert_equal 'Arr', @ship.pirate.catchphrase
end
@@ -369,7 +377,7 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
def test_should_replace_an_existing_record_if_there_is_no_id
@ship.reload.pirate_attributes = { :catchphrase => 'Arr' }
- assert @ship.pirate.new_record?
+ assert !@ship.pirate.persisted?
assert_equal 'Arr', @ship.pirate.catchphrase
assert_equal 'Aye', @pirate.catchphrase
end
@@ -458,7 +466,7 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
@pirate.delete
@ship.reload.attributes = { :update_only_pirate_attributes => { :catchphrase => 'Arr' } }
- assert @ship.update_only_pirate.new_record?
+ assert !@ship.update_only_pirate.persisted?
end
def test_should_update_existing_when_update_only_is_true_and_no_id_is_given
@@ -596,10 +604,10 @@ module NestedAttributesOnACollectionAssociationTests
association_getter => { 'foo' => { :name => 'Grace OMalley' }, 'bar' => { :name => 'Privateers Greed' }}
}
- assert @pirate.send(@association_name).first.new_record?
+ assert !@pirate.send(@association_name).first.persisted?
assert_equal 'Grace OMalley', @pirate.send(@association_name).first.name
- assert @pirate.send(@association_name).last.new_record?
+ assert !@pirate.send(@association_name).last.persisted?
assert_equal 'Privateers Greed', @pirate.send(@association_name).last.name
end
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index ffe6fb95b8..8ca9d626d1 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -192,7 +192,6 @@ class PersistencesTest < ActiveRecord::TestCase
topic = Topic.create("title" => "New Topic") do |t|
t.author_name = "David"
end
- topicReloaded = Topic.find(topic.id)
assert_equal("New Topic", topic.title)
assert_equal("David", topic.author_name)
end
@@ -241,6 +240,15 @@ class PersistencesTest < ActiveRecord::TestCase
assert_nothing_raised { minimalistic.save }
end
+ def test_update_sti_type
+ assert_instance_of Reply, topics(:second)
+
+ topic = topics(:second).becomes(Topic)
+ assert_instance_of Topic, topic
+ topic.save!
+ assert_instance_of Topic, Topic.find(topic.id)
+ end
+
def test_delete
topic = Topic.find(1)
assert_equal topic, topic.delete, 'topic.delete did not return self'
@@ -261,7 +269,7 @@ class PersistencesTest < ActiveRecord::TestCase
end
def test_record_not_found_exception
- assert_raise(ActiveRecord::RecordNotFound) { topicReloaded = Topic.find(99999) }
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(99999) }
end
def test_update_all
diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb
index 5bb21a54bd..33916c4e46 100644
--- a/activerecord/test/cases/query_cache_test.rb
+++ b/activerecord/test/cases/query_cache_test.rb
@@ -133,7 +133,6 @@ class QueryCacheExpiryTest < ActiveRecord::TestCase
def test_cache_is_expired_by_habtm_delete
ActiveRecord::Base.connection.expects(:clear_query_cache).times(2)
ActiveRecord::Base.cache do
- c = Category.find(1)
p = Post.find(1)
assert p.categories.any?
p.categories.delete_all
diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb
index bf41199b77..77d56fc058 100644
--- a/activerecord/test/cases/relation_scoping_test.rb
+++ b/activerecord/test/cases/relation_scoping_test.rb
@@ -254,13 +254,11 @@ class HasManyScopingTest< ActiveRecord::TestCase
end
def test_should_maintain_default_scope_on_associations
- person = people(:michael)
magician = BadReference.find(1)
assert_equal [magician], people(:michael).bad_references
end
def test_should_default_scope_on_associations_is_overriden_by_association_conditions
- person = people(:michael)
assert_equal [], people(:michael).fixed_bad_references
end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index f9385ab40f..7de7b95fa8 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -383,7 +383,7 @@ class RelationTest < ActiveRecord::TestCase
lifo = authors.find_or_initialize_by_name('Lifo')
assert_equal "Lifo", lifo.name
- assert lifo.new_record?
+ assert !lifo.persisted?
assert_equal authors(:david), authors.find_or_initialize_by_name(:name => 'David')
end
@@ -393,7 +393,7 @@ class RelationTest < ActiveRecord::TestCase
lifo = authors.find_or_create_by_name('Lifo')
assert_equal "Lifo", lifo.name
- assert ! lifo.new_record?
+ assert lifo.persisted?
assert_equal authors(:david), authors.find_or_create_by_name(:name => 'David')
end
@@ -426,6 +426,31 @@ class RelationTest < ActiveRecord::TestCase
assert_blank authors.all
end
+ def test_where_with_ar_object
+ author = Author.first
+ authors = Author.scoped.where(:id => author)
+ assert_equal 1, authors.all.length
+ end
+
+ def test_find_with_list_of_ar
+ author = Author.first
+ authors = Author.find([author])
+ assert_equal author, authors.first
+ end
+
+ class Mary < Author; end
+
+ def test_find_by_classname
+ Author.create!(:name => Mary.name)
+ assert_equal 1, Author.where(:name => Mary).size
+ end
+
+ def test_find_by_id_with_list_of_ar
+ author = Author.first
+ authors = Author.find_by_id([author])
+ assert_equal author, authors
+ end
+
def test_exists
davids = Author.where(:name => 'David')
assert davids.exists?
@@ -627,10 +652,10 @@ class RelationTest < ActiveRecord::TestCase
sparrow = birds.create
assert_kind_of Bird, sparrow
- assert sparrow.new_record?
+ assert !sparrow.persisted?
hen = birds.where(:name => 'hen').create
- assert ! hen.new_record?
+ assert hen.persisted?
assert_equal 'hen', hen.name
end
@@ -641,7 +666,7 @@ class RelationTest < ActiveRecord::TestCase
hen = birds.where(:name => 'hen').create!
assert_kind_of Bird, hen
- assert ! hen.new_record?
+ assert hen.persisted?
assert_equal 'hen', hen.name
end
diff --git a/activerecord/test/cases/session_store/sql_bypass.rb b/activerecord/test/cases/session_store/sql_bypass.rb
index f0ba166465..7402b2afd6 100644
--- a/activerecord/test/cases/session_store/sql_bypass.rb
+++ b/activerecord/test/cases/session_store/sql_bypass.rb
@@ -18,9 +18,9 @@ module ActiveRecord
assert !Session.table_exists?
end
- def test_new_record?
+ def test_persisted?
s = SqlBypass.new :data => 'foo', :session_id => 10
- assert s.new_record?, 'this is a new record!'
+ assert !s.persisted?, 'this is a new record!'
end
def test_not_loaded?
diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb
index eb93761fb2..70c098bc6d 100644
--- a/activerecord/test/cases/timestamp_test.rb
+++ b/activerecord/test/cases/timestamp_test.rb
@@ -113,7 +113,7 @@ class TimestampTest < ActiveRecord::TestCase
pet = Pet.first
owner = pet.owner
- owner.update_attribute(:happy_at, (time = 3.days.ago))
+ owner.update_attribute(:happy_at, 3.days.ago)
previously_owner_updated_at = owner.updated_at
pet.name = "I'm a parrot"
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index 0fbcef4091..b0ccd71836 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -163,7 +163,7 @@ class TransactionTest < ActiveRecord::TestCase
@first.author_name += '_this_should_not_end_up_in_the_db'
@first.save!
flunk
- rescue => e
+ rescue
assert_equal original_author_name, @first.reload.author_name
assert_equal nbooks_before_save, Book.count
ensure
@@ -182,7 +182,7 @@ class TransactionTest < ActiveRecord::TestCase
:bonus_time => "2005-01-30t15:28:00.00+01:00",
:content => "Have a nice day",
:approved => false)
- new_record_snapshot = new_topic.new_record?
+ new_record_snapshot = !new_topic.persisted?
id_present = new_topic.has_attribute?(Topic.primary_key)
id_snapshot = new_topic.id
@@ -195,7 +195,7 @@ class TransactionTest < ActiveRecord::TestCase
flunk
rescue => e
assert_equal "Make the transaction rollback", e.message
- assert_equal new_record_snapshot, new_topic.new_record?, "The topic should have its old new_record value"
+ assert_equal new_record_snapshot, !new_topic.persisted?, "The topic should have its old persisted value"
assert_equal id_snapshot, new_topic.id, "The topic should have its old id"
assert_equal id_present, new_topic.has_attribute?(Topic.primary_key)
ensure
@@ -370,21 +370,21 @@ class TransactionTest < ActiveRecord::TestCase
assert topic_2.save
@first.save
@second.destroy
- assert_equal false, topic_1.new_record?
+ assert_equal true, topic_1.persisted?
assert_not_nil topic_1.id
- assert_equal false, topic_2.new_record?
+ assert_equal true, topic_2.persisted?
assert_not_nil topic_2.id
- assert_equal false, @first.new_record?
+ assert_equal true, @first.persisted?
assert_not_nil @first.id
assert_equal true, @second.destroyed?
raise ActiveRecord::Rollback
end
- assert_equal true, topic_1.new_record?
+ assert_equal false, topic_1.persisted?
assert_nil topic_1.id
- assert_equal true, topic_2.new_record?
+ assert_equal false, topic_2.persisted?
assert_nil topic_2.id
- assert_equal false, @first.new_record?
+ assert_equal true, @first.persisted?
assert_not_nil @first.id
assert_equal false, @second.destroyed?
end
diff --git a/activerecord/test/cases/validations/association_validation_test.rb b/activerecord/test/cases/validations/association_validation_test.rb
index 1246dd4276..56e345990f 100644
--- a/activerecord/test/cases/validations/association_validation_test.rb
+++ b/activerecord/test/cases/validations/association_validation_test.rb
@@ -17,7 +17,7 @@ class AssociationValidationTest < ActiveRecord::TestCase
o = Owner.new('name' => 'nopets')
assert !o.save
assert o.errors[:pets].any?
- pet = o.pets.build('name' => 'apet')
+ o.pets.build('name' => 'apet')
assert o.valid?
end
@@ -27,7 +27,7 @@ class AssociationValidationTest < ActiveRecord::TestCase
assert !o.save
assert o.errors[:pets].any?
- pet = o.pets.build('name' => 'apet')
+ o.pets.build('name' => 'apet')
assert o.valid?
2.times { o.pets.build('name' => 'apet') }
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
index 9a863c25a8..679d67553b 100644
--- a/activerecord/test/cases/validations/uniqueness_validation_test.rb
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -60,7 +60,7 @@ class UniquenessValidationTest < ActiveRecord::TestCase
def test_validates_uniqueness_with_validates
Topic.validates :title, :uniqueness => true
- t = Topic.create!('title' => 'abc')
+ Topic.create!('title' => 'abc')
t2 = Topic.new('title' => 'abc')
assert !t2.valid?
@@ -201,7 +201,7 @@ class UniquenessValidationTest < ActiveRecord::TestCase
def test_validate_case_sensitive_uniqueness_with_attribute_passed_as_integer
Topic.validates_uniqueness_of(:title, :case_sensitve => true)
- t = Topic.create!('title' => 101)
+ Topic.create!('title' => 101)
t2 = Topic.new('title' => 101)
assert !t2.valid?
diff --git a/activerecord/test/models/eye.rb b/activerecord/test/models/eye.rb
index 77f17b578e..dc8ae2b3f6 100644
--- a/activerecord/test/models/eye.rb
+++ b/activerecord/test/models/eye.rb
@@ -17,7 +17,7 @@ class Eye < ActiveRecord::Base
after_save :trace_after_save2
def trace_after_create
- (@after_create_callbacks_stack ||= []) << iris.new_record?
+ (@after_create_callbacks_stack ||= []) << !iris.persisted?
end
alias trace_after_create2 trace_after_create
diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb
index d89c8cf381..f2c45053e7 100644
--- a/activerecord/test/models/pirate.rb
+++ b/activerecord/test/models/pirate.rb
@@ -48,7 +48,7 @@ class Pirate < ActiveRecord::Base
end
def reject_empty_ships_on_create(attributes)
- attributes.delete('_reject_me_if_new').present? && new_record?
+ attributes.delete('_reject_me_if_new').present? && !persisted?
end
attr_accessor :cancel_save_from_callback
diff --git a/activerecord/test/models/subject.rb b/activerecord/test/models/subject.rb
index d4b8b91de8..8e28f8b86b 100644
--- a/activerecord/test/models/subject.rb
+++ b/activerecord/test/models/subject.rb
@@ -8,7 +8,7 @@ class Subject < ActiveRecord::Base
protected
def set_email_address
- if self.new_record?
+ unless self.persisted?
self.author_email_address = 'test@test.com'
end
end
diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb
index 82d4b5997f..6496f36f7e 100644
--- a/activerecord/test/models/topic.rb
+++ b/activerecord/test/models/topic.rb
@@ -89,7 +89,7 @@ class Topic < ActiveRecord::Base
end
def set_email_address
- if self.new_record?
+ unless self.persisted?
self.author_email_address = 'test@test.com'
end
end
diff --git a/activeresource/CHANGELOG b/activeresource/CHANGELOG
index 24fe3072e0..386bafd7de 100644
--- a/activeresource/CHANGELOG
+++ b/activeresource/CHANGELOG
@@ -2,6 +2,10 @@
* No changes
+*Rails 3.0.2 (unreleased)*
+
+* No changes
+
*Rails 3.0.1 (October 15, 2010)*
* No Changes, just a version bump.
diff --git a/activeresource/lib/active_resource/version.rb b/activeresource/lib/active_resource/version.rb
index e2e0ecccbb..82dcb5d575 100644
--- a/activeresource/lib/active_resource/version.rb
+++ b/activeresource/lib/active_resource/version.rb
@@ -3,8 +3,8 @@ module ActiveResource
MAJOR = 3
MINOR = 1
TINY = 0
- BUILD = "beta"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG
index 3b6a29f7d6..6e8cce0d27 100644
--- a/activesupport/CHANGELOG
+++ b/activesupport/CHANGELOG
@@ -4,6 +4,10 @@
* Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White]
+*Rails 3.0.2 (unreleased)*
+
+* Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White]
+
*Rails 3.0.1 (October 15, 2010)*
* No Changes, just a version bump.
diff --git a/activesupport/lib/active_support/core_ext/cgi.rb b/activesupport/lib/active_support/core_ext/cgi.rb
deleted file mode 100644
index 7279a3d4da..0000000000
--- a/activesupport/lib/active_support/core_ext/cgi.rb
+++ /dev/null
@@ -1 +0,0 @@
-require 'active_support/core_ext/cgi/escape_skipping_slashes'
diff --git a/activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb b/activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb
deleted file mode 100644
index d3c3575748..0000000000
--- a/activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-require 'cgi'
-
-class CGI #:nodoc:
- if RUBY_VERSION >= '1.9'
- def self.escape_skipping_slashes(str)
- str = str.join('/') if str.respond_to? :join
- str.gsub(/([^ \/a-zA-Z0-9_.-])/n) do
- "%#{$1.unpack('H2' * $1.bytesize).join('%').upcase}"
- end.tr(' ', '+')
- end
- else
- def self.escape_skipping_slashes(str)
- str = str.join('/') if str.respond_to? :join
- str.gsub(/([^ \/a-zA-Z0-9_.-])/n) do
- "%#{$1.unpack('H2').first.upcase}"
- end.tr(' ', '+')
- end
- end
-end
diff --git a/activesupport/lib/active_support/core_ext/hash.rb b/activesupport/lib/active_support/core_ext/hash.rb
index 501483498d..fd1cda991e 100644
--- a/activesupport/lib/active_support/core_ext/hash.rb
+++ b/activesupport/lib/active_support/core_ext/hash.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/hash/conversions'
require 'active_support/core_ext/hash/deep_merge'
+require 'active_support/core_ext/hash/deep_dup'
require 'active_support/core_ext/hash/diff'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/indifferent_access'
diff --git a/activesupport/lib/active_support/core_ext/hash/deep_dup.rb b/activesupport/lib/active_support/core_ext/hash/deep_dup.rb
new file mode 100644
index 0000000000..447142605c
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/hash/deep_dup.rb
@@ -0,0 +1,11 @@
+class Hash
+ # Returns a deep copy of hash.
+ def deep_dup
+ duplicate = self.dup
+ duplicate.each_pair do |k,v|
+ tv = duplicate[k]
+ duplicate[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_dup : v
+ end
+ duplicate
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/object/instance_variables.rb b/activesupport/lib/active_support/core_ext/object/instance_variables.rb
index 77a3cfc21d..eda9694614 100644
--- a/activesupport/lib/active_support/core_ext/object/instance_variables.rb
+++ b/activesupport/lib/active_support/core_ext/object/instance_variables.rb
@@ -30,35 +30,4 @@ class Object
else
alias_method :instance_variable_names, :instance_variables
end
-
- # Copies the instance variables of +object+ into +self+.
- #
- # Instance variable names in the +exclude+ array are ignored. If +object+
- # responds to <tt>protected_instance_variables</tt> the ones returned are
- # also ignored. For example, Rails controllers implement that method.
- #
- # In both cases strings and symbols are understood, and they have to include
- # the at sign.
- #
- # class C
- # def initialize(x, y, z)
- # @x, @y, @z = x, y, z
- # end
- #
- # def protected_instance_variables
- # %w(@z)
- # end
- # end
- #
- # a = C.new(0, 1, 2)
- # b = C.new(3, 4, 5)
- #
- # a.copy_instance_variables_from(b, [:@y])
- # # a is now: @x = 3, @y = 1, @z = 2
- def copy_instance_variables_from(object, exclude = []) #:nodoc:
- exclude += object.protected_instance_variables if object.respond_to? :protected_instance_variables
-
- vars = object.instance_variables.map(&:to_s) - exclude.map(&:to_s)
- vars.each { |name| instance_variable_set(name, object.instance_variable_get(name)) }
- end
end
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb
index 48e9d04787..4d742b9ed2 100644
--- a/activesupport/lib/active_support/core_ext/object/try.rb
+++ b/activesupport/lib/active_support/core_ext/object/try.rb
@@ -8,6 +8,8 @@ class Object
# *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
# and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass.
#
+ # If try is called without a method to call, it will yield any given block with the object.
+ #
# ==== Examples
#
# Without try
@@ -21,10 +23,20 @@ class Object
# +try+ also accepts arguments and/or a block, for the method it is trying
# Person.try(:find, 1)
# @people.try(:collect) {|p| p.name}
+ #
+ # Without a method argument try will yield to the block unless the reciever is nil.
+ # @person.try { |p| "#{p.first_name} #{p.last_name}" }
#--
# +try+ behaves like +Object#send+, unless called on +NilClass+.
- alias_method :try, :__send__
+ def try(*a, &b)
+ if a.empty? && block_given?
+ yield self
+ else
+ __send__(*a, &b)
+ end
+ end
+
end
class NilClass #:nodoc:
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb
index 06dd18966e..320f5c1c92 100644
--- a/activesupport/lib/active_support/hash_with_indifferent_access.rb
+++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb
@@ -144,7 +144,7 @@ module ActiveSupport
when Hash
self.class.new_from_hash_copying_default(value)
when Array
- value.collect { |e| e.is_a?(Hash) ? self.class.new_from_hash_copying_default(e) : e }
+ value.dup.replace(value.collect { |e| e.is_a?(Hash) ? self.class.new_from_hash_copying_default(e) : e })
else
value
end
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index 93f5d5a0cc..6a7da8266c 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -73,7 +73,7 @@ module ActiveSupport
# Returns a <tt>Time.local()</tt> instance of the simultaneous time in your system's <tt>ENV['TZ']</tt> zone
def localtime
- utc.getlocal
+ utc.respond_to?(:getlocal) ? utc.getlocal : utc.to_time.getlocal
end
alias_method :getlocal, :localtime
diff --git a/activesupport/lib/active_support/version.rb b/activesupport/lib/active_support/version.rb
index 9e8b3d7888..690fc7f0fc 100644
--- a/activesupport/lib/active_support/version.rb
+++ b/activesupport/lib/active_support/version.rb
@@ -3,8 +3,8 @@ module ActiveSupport
MAJOR = 3
MINOR = 1
TINY = 0
- BUILD = "beta"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/activesupport/lib/active_support/xml_mini/nokogirisax.rb b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
index 38c8685390..25afbfcd1c 100644
--- a/activesupport/lib/active_support/xml_mini/nokogirisax.rb
+++ b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
@@ -38,8 +38,7 @@ module ActiveSupport
end
def start_element(name, attrs = [])
- new_hash = { CONTENT_KEY => '' }
- new_hash[attrs.shift] = attrs.shift while attrs.length > 0
+ new_hash = { CONTENT_KEY => '' }.merge(Hash[attrs])
new_hash[HASH_SIZE_KEY] = new_hash.size + 1
case current_hash[name]
diff --git a/activesupport/test/core_ext/cgi_ext_test.rb b/activesupport/test/core_ext/cgi_ext_test.rb
deleted file mode 100644
index c80362e382..0000000000
--- a/activesupport/test/core_ext/cgi_ext_test.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-require 'abstract_unit'
-require 'active_support/core_ext/cgi'
-
-class EscapeSkippingSlashesTest < Test::Unit::TestCase
- def test_array
- assert_equal 'hello/world', CGI.escape_skipping_slashes(%w(hello world))
- assert_equal 'hello+world/how/are/you', CGI.escape_skipping_slashes(['hello world', 'how', 'are', 'you'])
- end
-
- def test_typical
- assert_equal 'hi', CGI.escape_skipping_slashes('hi')
- assert_equal 'hi/world', CGI.escape_skipping_slashes('hi/world')
- assert_equal 'hi/world+you+funky+thing', CGI.escape_skipping_slashes('hi/world you funky thing')
- end
-end
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index 03fbee93a2..370f26b0d7 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -8,6 +8,9 @@ require 'active_support/core_ext/object/conversions'
class HashExtTest < Test::Unit::TestCase
class IndifferentHash < HashWithIndifferentAccess
end
+
+ class SubclassingArray < Array
+ end
def setup
@strings = { 'a' => 1, 'b' => 2 }
@@ -251,6 +254,20 @@ class HashExtTest < Test::Unit::TestCase
hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] }}.with_indifferent_access
assert_equal "1", hash[:urls][:url].first[:address]
end
+
+ def test_should_preserve_array_subclass_when_value_is_array
+ array = SubclassingArray.new
+ array << { "address" => "1" }
+ hash = { "urls" => { "url" => array }}.with_indifferent_access
+ assert_equal SubclassingArray, hash[:urls][:url].class
+ end
+
+ def test_should_preserve_array_class_when_hash_value_is_frozen_array
+ array = SubclassingArray.new
+ array << { "address" => "1" }
+ hash = { "urls" => { "url" => array.freeze }}.with_indifferent_access
+ assert_equal SubclassingArray, hash[:urls][:url].class
+ end
def test_stringify_and_symbolize_keys_on_indifferent_preserves_hash
h = HashWithIndifferentAccess.new
@@ -329,6 +346,21 @@ class HashExtTest < Test::Unit::TestCase
assert_equal expected, hash_1
end
+ def test_deep_dup
+ hash = { :a => { :b => 'b' } }
+ dup = hash.deep_dup
+ dup[:a][:c] = 'c'
+ assert_equal nil, hash[:a][:c]
+ assert_equal 'c', dup[:a][:c]
+ end
+
+ def test_deep_dup_initialize
+ zero_hash = Hash.new 0
+ hash = { :a => zero_hash }
+ dup = hash.deep_dup
+ assert_equal 0, dup[:a][44]
+ end
+
def test_store_on_indifferent_access
hash = HashWithIndifferentAccess.new
hash.store(:test1, 1)
diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb
index 3ccf18f473..398e6ca9b2 100644
--- a/activesupport/test/core_ext/object_and_class_ext_test.rb
+++ b/activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -82,37 +82,6 @@ class ObjectInstanceVariableTest < Test::Unit::TestCase
assert_equal %w(@bar @baz), @source.instance_variable_names.sort
end
- def test_copy_instance_variables_from_without_explicit_excludes
- assert_equal [], @dest.instance_variables
- @dest.copy_instance_variables_from(@source)
-
- assert_equal %w(@bar @baz), @dest.instance_variables.sort.map(&:to_s)
- %w(@bar @baz).each do |name|
- assert_equal @source.instance_variable_get(name).object_id,
- @dest.instance_variable_get(name).object_id
- end
- end
-
- def test_copy_instance_variables_from_with_explicit_excludes
- @dest.copy_instance_variables_from(@source, ['@baz'])
- assert !@dest.instance_variable_defined?('@baz')
- assert_equal 'bar', @dest.instance_variable_get('@bar')
- end
-
- def test_copy_instance_variables_automatically_excludes_protected_instance_variables
- @source.instance_variable_set(:@quux, 'quux')
- class << @source
- def protected_instance_variables
- ['@bar', :@quux]
- end
- end
-
- @dest.copy_instance_variables_from(@source)
- assert !@dest.instance_variable_defined?('@bar')
- assert !@dest.instance_variable_defined?('@quux')
- assert_equal 'baz', @dest.instance_variable_get('@baz')
- end
-
def test_instance_values
object = Object.new
object.instance_variable_set :@a, 1
@@ -165,4 +134,14 @@ class ObjectTryTest < Test::Unit::TestCase
def test_false_try
assert_equal 'false', false.try(:to_s)
end
+
+ def test_try_only_block
+ assert_equal @string.reverse, @string.try { |s| s.reverse }
+ end
+
+ def test_try_only_block_nil
+ ran = false
+ nil.try { ran = true }
+ assert_equal false, ran
+ end
end
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index 0bb2c4a39e..5579c27215 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -36,6 +36,10 @@ class TimeWithZoneTest < Test::Unit::TestCase
assert_equal @twz.object_id, @twz.in_time_zone(ActiveSupport::TimeZone['Eastern Time (US & Canada)']).object_id
end
+ def test_localtime
+ assert_equal @twz.localtime, @twz.utc.getlocal
+ end
+
def test_utc?
assert_equal false, @twz.utc?
assert_equal true, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']).utc?
@@ -763,6 +767,13 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
end
end
+ def test_localtime
+ Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_equal @dt.in_time_zone.localtime, @dt.in_time_zone.utc.to_time.getlocal
+ ensure
+ Time.zone_default = nil
+ end
+
def test_use_zone
Time.zone = 'Alaska'
Time.use_zone 'Hawaii' do
diff --git a/rails.gemspec b/rails.gemspec
index d791e21ec2..98b5f46554 100644
--- a/rails.gemspec
+++ b/rails.gemspec
@@ -25,5 +25,5 @@ Gem::Specification.new do |s|
s.add_dependency('activeresource', version)
s.add_dependency('actionmailer', version)
s.add_dependency('railties', version)
- s.add_dependency('bundler', '~> 1.0.3')
+ s.add_dependency('bundler', '~> 1.0')
end
diff --git a/railties/CHANGELOG b/railties/CHANGELOG
index fdfdb5eef5..75f1df44e7 100644
--- a/railties/CHANGELOG
+++ b/railties/CHANGELOG
@@ -1,5 +1,7 @@
*Rails 3.1.0 (unreleased)*
+* Added `rails plugin new` command which generates rails plugin with gemspec, tests and dummy application for testing [Piotr Sarnacki]
+
* 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]
@@ -20,7 +22,7 @@
* Changed ActionDispatch::Static to allow handling multiple directories [Piotr Sarnacki]
-* Added namespace() method to Engine, which sets Engine as isolated [Piotr Sarnacki]
+* Added isolate_namespace() method to Engine, which sets Engine as isolated [Piotr Sarnacki]
* Include all helpers from plugins and shared engines in application [Piotr Sarnacki]
diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index c02e9f1912..b39075f101 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -239,7 +239,7 @@ class LoginsController < ApplicationController
# "Delete" a login, aka "log the user out"
def destroy
# Remove the user id from the session
- session[:current_user_id] = nil
+ @_current_user = session[:current_user_id] = nil
redirect_to root_url
end
end
@@ -261,6 +261,13 @@ class LoginsController < ApplicationController
end
</ruby>
+Note it is also possible to assign a flash message as part of the redirection.
+
+<ruby>
+redirect_to root_url, :notice => "You have successfully logged out"
+</ruby>
+
+
The +destroy+ action redirects to the application's +root_url+, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:
<ruby>
diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile
index 2259061c30..8d2ce44e93 100644
--- a/railties/guides/source/action_mailer_basics.textile
+++ b/railties/guides/source/action_mailer_basics.textile
@@ -446,7 +446,7 @@ The following configuration options are best made in one of the environment file
|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, :file 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.|
+|perform_deliveries|Determines whether deliveries are actually carried out when the +deliver+ method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.|
|deliveries|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.|
h4. Example Action Mailer Configuration
@@ -492,7 +492,7 @@ class UserMailerTest < ActionMailer::TestCase
user = users(:some_user_in_your_fixtures)
# Send the email, then test that it got queued
- email = UserMailer.deliver_welcome_email(user)
+ email = UserMailer.welcome_email(user).deliver
assert !ActionMailer::Base.deliveries.empty?
# Test the body of the sent email contains what we expect it to
diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile
index 9b1d264d2c..dc1200812e 100644
--- a/railties/guides/source/active_support_core_extensions.textile
+++ b/railties/guides/source/active_support_core_extensions.textile
@@ -167,6 +167,12 @@ def log_info(sql, name, ms)
end
</ruby>
++try+ can also be called without arguments but a block, which will only be executed if the object is not nil:
+
+<ruby>
+@person.try { |p| "#{p.first_name} #{p.last_name}" }
+</ruby>
+
NOTE: Defined in +active_support/core_ext/object/try.rb+.
h4. +singleton_class+
@@ -395,39 +401,6 @@ C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+.
-h5. +copy_instance_variables_from(object, exclude = [])+
-
-Copies the instance variables of +object+ into +self+.
-
-Instance variable names in the +exclude+ array are ignored. If +object+
-responds to +protected_instance_variables+ the ones returned are
-also ignored. For example, Rails controllers implement that method.
-
-In both arrays strings and symbols are understood, and they have to include
-the at sign.
-
-<ruby>
-class C
- def initialize(x, y, z)
- @x, @y, @z = x, y, z
- end
-
- def protected_instance_variables
- %w(@z)
- end
-end
-
-a = C.new(0, 1, 2)
-b = C.new(3, 4, 5)
-
-a.copy_instance_variables_from(b, [:@y])
-# a is now: @x = 3, @y = 1, @z = 2
-</ruby>
-
-In the example +object+ and +self+ are of the same type, but they don't need to.
-
-NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+.
-
h4. Silencing Warnings, Streams, and Exceptions
The methods +silence_warnings+ and +enable_warnings+ change the value of +$VERBOSE+ accordingly for the duration of their block, and reset it afterwards:
diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile
index 900b3fb5d5..e3ccd6396c 100644
--- a/railties/guides/source/api_documentation_guidelines.textile
+++ b/railties/guides/source/api_documentation_guidelines.textile
@@ -116,14 +116,12 @@ Use fixed-width fonts for:
* file names
<ruby>
-# Copies the instance variables of +object+ into +self+.
-#
-# Instance variable names in the +exclude+ array are ignored. If +object+
-# responds to <tt>protected_instance_variables</tt> the ones returned are
-# also ignored. For example, Rails controllers implement that method.
-# ...
-def copy_instance_variables_from(object, exclude = [])
- ...
+class Array
+ # Calls <tt>to_param</tt> on all its elements and joins the result with
+ # slashes. This is used by <tt>url_for</tt> in Action Pack.
+ def to_param
+ collect { |e| e.to_param }.join '/'
+ end
end
</ruby>
diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile
index bb38c64307..28fff5c11e 100644
--- a/railties/guides/source/configuring.textile
+++ b/railties/guides/source/configuring.textile
@@ -32,7 +32,7 @@ config.filter_parameters << :password
This is a setting for Rails itself. If you want to pass settings to individual Rails components, you can do so via the same +config+ object:
<ruby>
-config.active_record.colorize_logging = false
+config.active_record.timestamped_migrations = false
</ruby>
Rails will use that particular setting to configure Active Record.
@@ -45,6 +45,8 @@ h4. Rails General Configuration
* +config.cache_store+ configures which cache store to use for Rails caching. Options include +:memory_store+, +:file_store+, +:mem_cache_store+ or the name of your own custom class.
+* +config.colorize_logging+ (true by default) specifies whether or not to use ANSI color codes when logging information.
+
* +config.controller_paths+ accepts an array of paths that will be searched for controllers. Defaults to +app/controllers+.
* +config.database_configuration_file+ overrides the default path for the database configuration file. Default to +config/database.yml+.
@@ -105,8 +107,6 @@ h4. Configuring Active Record
* +config.active_record.pluralize_table_names+ specifies whether Rails will look for singular or plural table names in the database. If set to +true+ (the default), then the Customer class will use the +customers+ table. If set to +false+, then the Customers class will use the +customer+ table.
-* +config.active_record.colorize_logging+ (true by default) specifies whether or not to use ANSI color codes when logging information from ActiveRecord.
-
* +config.active_record.default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:local+.
* +config.active_record.schema_format+ controls the format for dumping the database schema to a file. The options are +:ruby+ (the default) for a database-independent version that depends on migrations, or +:sql+ for a set of (potentially database-dependent) SQL statements.
diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile
index 6eec18b8b9..adf427147b 100644
--- a/railties/guides/source/debugging_rails_applications.textile
+++ b/railties/guides/source/debugging_rails_applications.textile
@@ -127,8 +127,8 @@ Rails makes use of Ruby's standard +logger+ to write log information. You can al
You can specify an alternative logger in your +environment.rb+ or any environment file:
<ruby>
-ActiveRecord::Base.logger = Logger.new(STDOUT)
-ActiveRecord::Base.logger = Log4r::Logger.new("Application Log")
+Rails.logger = Logger.new(STDOUT)
+Rails.logger = Log4r::Logger.new("Application Log")
</ruby>
Or in the +Initializer+ section, add _any_ of the following
@@ -142,13 +142,13 @@ TIP: By default, each log is created under +Rails.root/log/+ and the log file na
h4. Log Levels
-When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the +ActiveRecord::Base.logger.level+ method.
+When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the +Rails.logger.level+ method.
The available log levels are: +:debug+, +:info+, +:warn+, +:error+, and +:fatal+, corresponding to the log level numbers from 0 up to 4 respectively. To change the default log level, use
<ruby>
config.log_level = Logger::WARN # In any environment initializer, or
-ActiveRecord::Base.logger.level = 0 # at any time
+Rails.logger.level = 0 # at any time
</ruby>
This is useful when you want to log under development or staging, but you don't want to flood your production log with unnecessary information.
diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile
index 80e0421b48..ded82512d3 100644
--- a/railties/guides/source/form_helpers.textile
+++ b/railties/guides/source/form_helpers.textile
@@ -67,7 +67,7 @@ A basic search form
<% end %>
</erb>
-TIP: +search_path+ can be a named route specified in "routes.rb" as: <br /><code>match "search" => "search"</code>This declares for path "/search" to call action "search" from controller "search".
+TIP: +search_path+ can be a named route specified in "routes.rb" as: <br /><code>match "search" => "search"</code> This declares that path "/search" will be handled by action "search" belonging to controller "search".
The above view code will result in the following markup:
@@ -107,7 +107,7 @@ WARNING: Do not delimit the second hash without doing so with the first hash, ot
h4. Helpers for Generating Form Elements
-Rails provides a series of helpers for generating form elements such as checkboxes, text fields, radio buttons, and so on. These basic helpers, with names ending in <notextile>_tag</notextile> such as +text_field_tag+, +check_box_tag+, etc., generate just a single +&lt;input&gt;+ element. The first parameter to these is always the name of the input. In the controller this name will be the key in the +params+ hash used to get the value entered by the user. For example, if the form contains
+Rails provides a series of helpers for generating form elements such as checkboxes, text fields and radio buttons. These basic helpers, with names ending in <notextile>_tag</notextile> such as +text_field_tag+ and +check_box_tag+ generate just a single +&lt;input&gt;+ element. The first parameter to these is always the name of the input. In the controller this name will be the key in the +params+ hash used to get the value entered by the user. For example, if the form contains
<erb>
<%= text_field_tag(:query) %>
@@ -127,18 +127,18 @@ Checkboxes are form controls that give the user a set of options they can enable
<erb>
<%= check_box_tag(:pet_dog) %>
- <%= label_tag(:pet_dog, "I own a dog") %>
+<%= label_tag(:pet_dog, "I own a dog") %>
<%= check_box_tag(:pet_cat) %>
- <%= label_tag(:pet_cat, "I own a cat") %>
+<%= label_tag(:pet_cat, "I own a cat") %>
</erb>
output:
<html>
<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
- <label for="pet_dog">I own a dog</label>
+<label for="pet_dog">I own a dog</label>
<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
- <label for="pet_cat">I own a cat</label>
+<label for="pet_cat">I own a cat</label>
</html>
The second parameter to +check_box_tag+ is the value of the input. This is the value that will be submitted by the browser if the checkbox is ticked (i.e. the value that will be present in the +params+ hash). With the above form you would check the value of +params[:pet_dog]+ and +params[:pet_cat]+ to see which pets the user owns.
@@ -149,18 +149,18 @@ Radio buttons, while similar to checkboxes, are controls that specify a set of o
<erb>
<%= radio_button_tag(:age, "child") %>
- <%= label_tag(:age_child, "I am younger than 21") %>
+<%= label_tag(:age_child, "I am younger than 21") %>
<%= radio_button_tag(:age, "adult") %>
- <%= label_tag(:age_adult, "I'm over 21") %>
+<%= label_tag(:age_adult, "I'm over 21") %>
</erb>
output:
<html>
<input id="age_child" name="age" type="radio" value="child" />
- <label for="age_child">I am younger than 21</label>
+<label for="age_child">I am younger than 21</label>
<input id="age_adult" name="age" type="radio" value="adult" />
- <label for="age_adult">I'm over 21</label>
+<label for="age_adult">I'm over 21</label>
</html>
As with +check_box_tag+ the second parameter to +radio_button_tag+ is the value of the input. Because these two radio buttons share the same name (age) the user will only be able to select one and +params[:age]+ will contain either "child" or "adult".
@@ -232,13 +232,13 @@ The corresponding view +app/views/articles/new.html.erb+ using +form_for+ looks
<%= form_for @article, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %>
<%= f.text_field :title %>
<%= f.text_area :body, :size => "60x12" %>
- <%= submit_tag "Create" %>
+ <%= f.submit "Create" %>
<% end %>
</erb>
There are a few things to note here:
-# +:article+ is the name of the model and +@article+ is the actual object being edited.
+# +@article+ is the actual object being edited.
# There is a single hash of options. Routing options are passed in the +:url+ hash, HTML options are passed in the +:html+ hash.
# The +form_for+ method yields a *form builder* object (the +f+ variable).
# Methods to create form controls are called *on* the form builder object +f+
@@ -284,7 +284,7 @@ h4. Relying on Record Identification
The Article model is directly available to users of the application, so -- following the best practices for developing with Rails -- you should declare it *a resource*:
<ruby>
-map.resources :articles
+resources :articles
</ruby>
TIP: Declaring a resource has a number of side-affects. See "Rails Routing From the Outside In":routing.html#resource-routing-the-rails-default for more information on setting up and using resources.
@@ -294,13 +294,13 @@ When dealing with RESTful resources, calls to +form_for+ can get significantly e
<ruby>
## Creating a new article
# long-style:
-form_for(:article, @article, :url => articles_path)
+form_for(@article, :url => articles_path)
# same thing, short-style (record identification gets used):
form_for(@article)
## Editing an existing article
# long-style:
-form_for(:article, @article, :url => article_path(@article), :html => { :method => "put" })
+form_for(@article, :url => article_path(@article), :html => { :method => "put" })
# short-style:
form_for(@article)
</ruby>
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile
index e592417dcb..f3420e37d1 100644
--- a/railties/guides/source/getting_started.textile
+++ b/railties/guides/source/getting_started.textile
@@ -919,8 +919,6 @@ So first, we'll wire up the Post show template (+/app/views/posts/show.html.erb+
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
- <%= f.error_messages %>
-
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
@@ -989,8 +987,6 @@ Once we have made the new comment, we send the user back to the original post us
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
- <%= f.error_messages %>
-
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
@@ -1057,8 +1053,6 @@ Then in the +app/views/posts/show.html.erb+ you can change it to look like the f
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
- <%= f.error_messages %>
-
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
@@ -1086,8 +1080,6 @@ Lets also move that new comment section out to it's own partial, again, you crea
<erb>
<%= form_for([@post, @post.comments.build]) do |f| %>
- <%= f.error_messages %>
-
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile
index 77c20c8bb0..4cc5f3843f 100644
--- a/railties/guides/source/initialization.textile
+++ b/railties/guides/source/initialization.textile
@@ -1479,10 +1479,10 @@ Next, the Railtie itself is defined:
require "action_view/railties/log_subscriber"
log_subscriber ActionView::Railties::LogSubscriber.new
- initializer "action_view.cache_asset_timestamps" do |app|
+ initializer "action_view.cache_asset_id" do |app|
unless app.config.cache_classes
- ActionView.base_hook do
- ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false
+ ActiveSupport.on_load(:action_view) do
+ ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false
end
end
end
@@ -1492,7 +1492,7 @@ Next, the Railtie itself is defined:
The +ActionView::LogSubscriber+ sets up a method called +render_template+ which is called when a template is rendered. TODO: Templates only or partials and layouts also? I would imagine these fall under the templates category, but there needs to research to ensure this is correct.
-The sole initializer defined here, _action_view.cache_asset_timestamps_ is responsible for caching the timestamps on the ends of your assets. If you've ever seen a link generated by +image_tag+ or +stylesheet_link_tag+ you would know that I mean that this timestamp is the number after the _?_ in this example: _/javascripts/prototype.js?1265442620_. This initializer will do nothing if +cache_classes+ is set to false in any of your application's configuration. TODO: Elaborate.
+The sole initializer defined here, _action_view.cache_asset_ids_ is responsible for caching the timestamps on the ends of your assets. If you've ever seen a link generated by +image_tag+ or +stylesheet_link_tag+ you would know that I mean that this timestamp is the number after the _?_ in this example: _/javascripts/prototype.js?1265442620_. This initializer will do nothing if +cache_classes+ is set to false in any of your application's configuration. TODO: Elaborate.
h4. Action Mailer Railtie
@@ -3003,7 +3003,7 @@ The +I18n::Railtie+ also defines an +after_initialize+ which we will return to l
**Action View Initializers **
-* action_view.cache_asset_timestamps
+* action_view.cache_asset_ids
**Action Mailer Initializers **
diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile
index c65ea5c797..4e26d152bf 100644
--- a/railties/guides/source/layouts_and_rendering.textile
+++ b/railties/guides/source/layouts_and_rendering.textile
@@ -970,7 +970,7 @@ Partial templates - usually just called "partials" - are another device for brea
h5. Naming Partials
-To render a partial as part of a view, you use the +render+ method within the view, and include the +:partial+ option:
+To render a partial as part of a view, you use the +render+ method within the view:
<ruby>
<%= render "menu" %>
diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile
index 7c2725e652..d32e7de564 100644
--- a/railties/guides/source/plugins.textile
+++ b/railties/guides/source/plugins.textile
@@ -802,7 +802,7 @@ You can also see if your routes work by running +rake routes+ from your app dire
h3. Generators
-Many plugins ship with generators. When you created the plugin above, you specified the +--with-generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'.
+Many plugins ship with generators. When you created the plugin above, you specified the +--generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'.
Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file.
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
index f48ae9c7f7..cc0c3316c8 100644
--- a/railties/guides/source/routing.textile
+++ b/railties/guides/source/routing.textile
@@ -436,6 +436,26 @@ match 'exit' => 'sessions#destroy', :as => :logout
This will create +logout_path+ and +logout_url+ as named helpers in your application. Calling +logout_path+ will return +/exit+
+h4. HTTP Verb Constraints
+
+You can use the +:via+ option to constrain the request to one or more HTTP methods:
+
+<ruby>
+match 'photos/show' => 'photos#show', :via => :get
+</ruby>
+
+There is a shorthand version of this as well:
+
+<ruby>
+get 'photos/show'
+</ruby>
+
+You can also permit more than one verb to a single route:
+
+<ruby>
+match 'photos/show' => 'photos#show', :via => [:get, :post]
+</ruby>
+
h4. Segment Constraints
You can use the +:constraints+ option to enforce a format for a dynamic segment:
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index d84373cddf..182068071d 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -35,7 +35,6 @@ module Rails
#
class Application < Engine
autoload :Bootstrap, 'rails/application/bootstrap'
- autoload :Configurable, 'rails/application/configurable'
autoload :Configuration, 'rails/application/configuration'
autoload :Finisher, 'rails/application/finisher'
autoload :Railties, 'rails/application/railties'
diff --git a/railties/lib/rails/cli.rb b/railties/lib/rails/cli.rb
index 1260772605..2b32f7edf1 100644
--- a/railties/lib/rails/cli.rb
+++ b/railties/lib/rails/cli.rb
@@ -5,10 +5,12 @@ require 'rails/script_rails_loader'
# the rest of this script is not run.
Rails::ScriptRailsLoader.exec_script_rails!
-railties_path = File.expand_path('../../lib', __FILE__)
-$:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path)
-
require 'rails/ruby_version_check'
Signal.trap("INT") { puts; exit }
-require 'rails/commands/application'
+if ARGV.first == 'plugin'
+ ARGV.shift
+ require 'rails/commands/plugin_new'
+else
+ require 'rails/commands/application'
+end
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
index e3aa6d7c3e..de5d876c18 100644
--- a/railties/lib/rails/commands.rb
+++ b/railties/lib/rails/commands.rb
@@ -12,14 +12,22 @@ command = aliases[command] || command
case command
when 'generate', 'destroy', 'plugin'
- require APP_PATH
- Rails.application.require_environment!
+ if command == "plugin" && ARGV.first == "new"
+ require "rails/commands/plugin_new"
+ elsif command == 'generate' && ARGV.first == "plugin_new"
+ puts "This generator should not be used directly as a generator. You should use `rails plugin new` command instead"
+ exit(1)
+ else
+ require APP_PATH
+ Rails.application.require_environment!
- if defined?(ENGINE_PATH)
- engine = Rails.application.railties.engines.find { |r| r.root.to_s == ENGINE_PATH }
- Rails.application = engine
+ if defined?(ENGINE_PATH)
+ engine = Rails.application.railties.engines.find { |r| r.root.to_s == ENGINE_PATH }
+ Rails.application = engine
+ end
+
+ require "rails/commands/#{command}"
end
- require "rails/commands/#{command}"
when 'benchmarker', 'profiler'
require APP_PATH
diff --git a/railties/lib/rails/commands/plugin_new.rb b/railties/lib/rails/commands/plugin_new.rb
new file mode 100644
index 0000000000..8baa8ebfd4
--- /dev/null
+++ b/railties/lib/rails/commands/plugin_new.rb
@@ -0,0 +1,10 @@
+if ARGV.first != "new"
+ ARGV[0] = "--help"
+else
+ ARGV.shift
+end
+
+require 'rails/generators'
+require 'rails/generators/rails/plugin_new/plugin_new_generator'
+
+Rails::Generators::PluginNewGenerator.start
diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb
index 8369795e71..66fab0a760 100644
--- a/railties/lib/rails/configuration.rb
+++ b/railties/lib/rails/configuration.rb
@@ -1,5 +1,6 @@
require 'active_support/deprecation'
require 'active_support/ordered_options'
+require 'active_support/core_ext/hash/deep_dup'
require 'rails/paths'
require 'rails/rack'
@@ -51,6 +52,13 @@ module Rails
@colorize_logging = true
end
+ def initialize_copy(source)
+ @aliases = @aliases.deep_dup
+ @options = @options.deep_dup
+ @fallbacks = @fallbacks.deep_dup
+ @templates = @templates.dup
+ end
+
def method_missing(method, *args)
method = method.to_s.sub(/=$/, '').to_sym
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index 72bfe207d7..62fb781c19 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -324,11 +324,12 @@ module Rails
# MyEngine::Engine.load_seed
#
class Engine < Railtie
- autoload :Configurable, "rails/engine/configurable"
autoload :Configuration, "rails/engine/configuration"
+ autoload :Railties, "rails/engine/railties"
class << self
attr_accessor :called_from, :isolated
+ alias :isolated? :isolated
alias :engine_name :railtie_name
def inherited(base)
@@ -368,10 +369,6 @@ module Rails
end
end
end
-
- def isolated?
- !!isolated
- end
end
delegate :middleware, :root, :paths, :to => :config
diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb
index 7a07dcad7d..4f458b0aee 100644
--- a/railties/lib/rails/engine/configuration.rb
+++ b/railties/lib/rails/engine/configuration.rb
@@ -10,6 +10,7 @@ module Rails
def initialize(root=nil)
super()
@root = root
+ @generators = app_generators.dup
end
# Returns the middleware stack for the engine.
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
new file mode 100644
index 0000000000..f5c626553c
--- /dev/null
+++ b/railties/lib/rails/generators/app_base.rb
@@ -0,0 +1,176 @@
+require 'digest/md5'
+require 'active_support/secure_random'
+require 'rails/version' unless defined?(Rails::VERSION)
+require 'rbconfig'
+require 'open-uri'
+require 'uri'
+
+module Rails
+ module Generators
+ class AppBase < Base
+ DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
+ JAVASCRIPTS = %w( prototype jquery )
+
+ attr_accessor :rails_template
+ add_shebang_option!
+
+ argument :app_path, :type => :string
+
+ def self.add_shared_options_for(name)
+ class_option :builder, :type => :string, :aliases => "-b",
+ :desc => "Path to a #{name} builder (can be a filesystem path or URL)"
+
+ class_option :template, :type => :string, :aliases => "-m",
+ :desc => "Path to an #{name} template (can be a filesystem path or URL)"
+
+ class_option :skip_gemfile, :type => :boolean, :default => false,
+ :desc => "Don't create a Gemfile"
+
+ class_option :skip_git, :type => :boolean, :aliases => "-G", :default => false,
+ :desc => "Skip Git ignores and keeps"
+
+ class_option :skip_active_record, :type => :boolean, :aliases => "-O", :default => false,
+ :desc => "Skip Active Record files"
+
+ 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 :skip_javascript, :type => :boolean, :aliases => "-J", :default => false,
+ :desc => "Skip javascript files"
+
+ class_option :dev, :type => :boolean, :default => false,
+ :desc => "Setup the #{name} with Gemfile pointing to your Rails checkout"
+
+ class_option :edge, :type => :boolean, :default => false,
+ :desc => "Setup the #{name} with Gemfile pointing to Rails repository"
+
+ class_option :skip_test_unit, :type => :boolean, :aliases => "-T", :default => false,
+ :desc => "Skip Test::Unit files"
+
+ class_option :help, :type => :boolean, :aliases => "-h", :group => :rails,
+ :desc => "Show this help message and quit"
+ end
+
+ def initialize(*args)
+ @original_wd = Dir.pwd
+
+ super
+ end
+
+ protected
+
+ def builder
+ @builder ||= begin
+ if path = options[:builder]
+ if URI(path).is_a?(URI::HTTP)
+ contents = open(path, "Accept" => "application/x-thor-template") {|io| io.read }
+ else
+ contents = open(File.expand_path(path, @original_wd)) {|io| io.read }
+ end
+
+ prok = eval("proc { #{contents} }", TOPLEVEL_BINDING, path, 1)
+ instance_eval(&prok)
+ end
+
+ builder_class = get_builder_class
+ builder_class.send(:include, ActionMethods)
+ builder_class.new(self)
+ end
+ end
+
+ def build(meth, *args)
+ builder.send(meth, *args) if builder.respond_to?(meth)
+ end
+
+ def create_root
+ self.destination_root = File.expand_path(app_path, destination_root)
+ valid_const?
+
+ empty_directory '.'
+ set_default_accessors!
+ FileUtils.cd(destination_root) unless options[:pretend]
+ end
+
+ def apply_rails_template
+ apply rails_template if rails_template
+ rescue Thor::Error, LoadError, Errno::ENOENT => e
+ raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}"
+ end
+
+ def set_default_accessors!
+ self.rails_template = case options[:template]
+ when /^http:\/\//
+ options[:template]
+ when String
+ File.expand_path(options[:template], Dir.pwd)
+ else
+ options[:template]
+ end
+ end
+
+ def database_gemfile_entry
+ entry = ""
+ unless options[:skip_active_record]
+ entry = "gem '#{gem_for_database}'"
+ entry << ", :require => '#{require_for_database}'" if require_for_database
+ end
+ entry
+ end
+
+ def rails_gemfile_entry
+ if options.dev?
+ <<-GEMFILE
+gem 'rails', :path => '#{Rails::Generators::RAILS_DEV_PATH}'
+gem 'arel', :git => 'git://github.com/rails/arel.git'
+gem "rack", :git => "git://github.com/rack/rack.git"
+ GEMFILE
+ elsif options.edge?
+ <<-GEMFILE
+gem 'rails', :git => 'git://github.com/rails/rails.git'
+gem 'arel', :git => 'git://github.com/rails/arel.git'
+gem "rack", :git => "git://github.com/rack/rack.git"
+ GEMFILE
+ else
+ <<-GEMFILE
+gem 'rails', '#{Rails::VERSION::STRING}'
+
+# Bundle edge Rails instead:
+# gem 'rails', :git => 'git://github.com/rails/rails.git'
+# gem 'arel', :git => 'git://github.com/rails/arel.git'
+# gem "rack", :git => "git://github.com/rack/rack.git"
+ GEMFILE
+ end
+ end
+
+ def gem_for_database
+ # %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
+ case options[:database]
+ when "oracle" then "ruby-oci8"
+ when "postgresql" then "pg"
+ when "sqlite3" then "sqlite3-ruby"
+ when "frontbase" then "ruby-frontbase"
+ when "mysql" then "mysql2"
+ else options[:database]
+ end
+ end
+
+ def require_for_database
+ case options[:database]
+ when "sqlite3" then "sqlite3"
+ end
+ end
+
+ def bundle_if_dev_or_edge
+ bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
+ run "#{bundle_command} install" if dev_or_edge?
+ end
+
+ def dev_or_edge?
+ options.dev? || options.edge?
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index 9131a19043..e0dde4360f 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -16,6 +16,14 @@ module Rails
parse_attributes! if respond_to?(:attributes)
end
+ no_tasks do
+ def template(source, *args, &block)
+ inside_template do
+ super
+ end
+ end
+ end
+
protected
attr_reader :file_name
alias :singular_name :file_name
@@ -23,16 +31,14 @@ module Rails
# Wrap block with namespace of current application
# if namespace exists and is not skipped
def module_namespacing(&block)
- inside_namespace do
- content = capture(&block)
- content = wrap_with_namespace(content) if namespaced?
- concat(content)
- end
+ content = capture(&block)
+ content = wrap_with_namespace(content) if namespaced?
+ concat(content)
end
def indent(content, multiplier = 2)
spaces = " " * multiplier
- content.each_line.map {|line| "#{spaces}#{line}" }.join("\n")
+ content = content.each_line.map {|line| "#{spaces}#{line}" }.join
end
def wrap_with_namespace(content)
@@ -40,12 +46,15 @@ module Rails
"module #{namespace.name}\n#{content}\nend\n"
end
- def inside_namespace
- @inside_namespace = true if namespaced?
- result = yield
- result
+ def inside_template
+ @inside_template = true
+ yield
ensure
- @inside_namespace = false
+ @inside_template = false
+ end
+
+ def inside_template?
+ @inside_template
end
def namespace
@@ -55,11 +64,7 @@ module Rails
end
def namespaced?
- !options[:skip_namespace] && !!namespace
- end
-
- def inside_namespace?
- @inside_namespace
+ !options[:skip_namespace] && namespace
end
def file_path
@@ -67,7 +72,7 @@ module Rails
end
def class_path
- inside_namespace? || !namespaced? ? regular_class_path : namespaced_class_path
+ inside_template? || !namespaced? ? regular_class_path : namespaced_class_path
end
def regular_class_path
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index 44f9fde0a6..ef1eb8d237 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -1,9 +1,4 @@
-require 'digest/md5'
-require 'active_support/secure_random'
-require 'rails/version' unless defined?(Rails::VERSION)
-require 'rbconfig'
-require 'open-uri'
-require 'uri'
+require 'rails/generators/app_base'
module Rails
module ActionMethods
@@ -158,60 +153,16 @@ module Rails
RESERVED_NAMES = %w[application destroy benchmarker profiler
plugin runner test]
- class AppGenerator < Base
- DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
- JAVASCRIPTS = %w( prototype jquery )
-
- attr_accessor :rails_template
- add_shebang_option!
-
- argument :app_path, :type => :string
-
- 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)"
-
- class_option :template, :type => :string, :aliases => "-m",
- :desc => "Path to an application template (can be a filesystem path or URL)"
-
- class_option :dev, :type => :boolean, :default => false,
- :desc => "Setup the application with Gemfile pointing to your Rails checkout"
-
- class_option :edge, :type => :boolean, :default => false,
- :desc => "Setup the application with Gemfile pointing to Rails repository"
-
- class_option :skip_gemfile, :type => :boolean, :default => false,
- :desc => "Don't create a Gemfile"
-
- class_option :skip_active_record, :type => :boolean, :aliases => "-O", :default => false,
- :desc => "Skip Active Record files"
-
- class_option :skip_test_unit, :type => :boolean, :aliases => "-T", :default => false,
- :desc => "Skip Test::Unit 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"
+ class AppGenerator < AppBase
+ add_shared_options_for "application"
# Add bin/rails options
class_option :version, :type => :boolean, :aliases => "-v", :group => :rails,
:desc => "Show Rails version number and quit"
- class_option :help, :type => :boolean, :aliases => "-h", :group => :rails,
- :desc => "Show this help message and quit"
-
def initialize(*args)
raise Error, "Options should be given after the application name. For details run: rails --help" if args[0].blank?
- @original_wd = Dir.pwd
-
super
if !options[:skip_active_record] && !DATABASES.include?(options[:database])
@@ -223,14 +174,7 @@ module Rails
end
end
- def create_root
- self.destination_root = File.expand_path(app_path, destination_root)
- valid_app_const?
-
- empty_directory '.'
- set_default_accessors!
- FileUtils.cd(destination_root) unless options[:pretend]
- end
+ public_task :create_root
def create_root_files
build(:readme)
@@ -309,16 +253,7 @@ module Rails
build(:leftovers)
end
- def apply_rails_template
- apply rails_template if rails_template
- rescue Thor::Error, LoadError, Errno::ENOENT => e
- raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}"
- end
-
- def bundle_if_dev_or_edge
- bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
- run "#{bundle_command} install" if dev_or_edge?
- end
+ public_task :apply_rails_template, :bundle_if_dev_or_edge
protected
@@ -326,40 +261,6 @@ module Rails
"rails new #{self.arguments.map(&:usage).join(' ')} [options]"
end
- def builder
- @builder ||= begin
- if path = options[:builder]
- if URI(path).is_a?(URI::HTTP)
- contents = open(path, "Accept" => "application/x-thor-template") {|io| io.read }
- else
- contents = open(File.expand_path(path, @original_wd)) {|io| io.read }
- end
-
- prok = eval("proc { #{contents} }", TOPLEVEL_BINDING, path, 1)
- instance_eval(&prok)
- end
-
- builder_class = defined?(::AppBuilder) ? ::AppBuilder : Rails::AppBuilder
- builder_class.send(:include, ActionMethods)
- builder_class.new(self)
- end
- end
-
- def build(meth, *args)
- builder.send(meth, *args) if builder.respond_to?(meth)
- end
-
- def set_default_accessors!
- self.rails_template = case options[:template]
- when /^http:\/\//
- options[:template]
- when String
- File.expand_path(options[:template], Dir.pwd)
- else
- options[:template]
- end
- end
-
# Define file as an alias to create_file for backwards compatibility.
def file(*args, &block)
create_file(*args, &block)
@@ -388,7 +289,7 @@ module Rails
@app_const ||= "#{app_const_base}::Application"
end
- def valid_app_const?
+ def valid_const?
if app_const =~ /^\d/
raise Error, "Invalid application name #{app_name}. Please give a name which does not start with numbers."
elsif RESERVED_NAMES.include?(app_name)
@@ -402,28 +303,6 @@ module Rails
ActiveSupport::SecureRandom.hex(64)
end
- def dev_or_edge?
- options.dev? || options.edge?
- end
-
- def gem_for_database
- # %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
- case options[:database]
- when "oracle" then "ruby-oci8"
- when "postgresql" then "pg"
- when "sqlite3" then "sqlite3-ruby"
- when "frontbase" then "ruby-frontbase"
- when "mysql" then "mysql2"
- else options[:database]
- end
- end
-
- def require_for_database
- case options[:database]
- when "sqlite3" then "sqlite3"
- end
- end
-
def mysql_socket
@mysql_socket ||= [
"/tmp/mysql.sock", # default
@@ -442,6 +321,10 @@ module Rails
empty_directory(destination, config)
create_file("#{destination}/.gitkeep") unless options[:skip_git]
end
+
+ def get_builder_class
+ defined?(::AppBuilder) ? ::AppBuilder : Rails::AppBuilder
+ end
end
end
end
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 40213b1261..86b9e8f40c 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -1,25 +1,8 @@
source 'http://rubygems.org'
-<%- if options.dev? -%>
-gem 'rails', :path => '<%= Rails::Generators::RAILS_DEV_PATH %>'
-gem 'arel', :git => 'git://github.com/rails/arel.git'
-gem "rack", :git => "git://github.com/rack/rack.git"
-<%- elsif options.edge? -%>
-gem 'rails', :git => 'git://github.com/rails/rails.git'
-gem 'arel', :git => 'git://github.com/rails/arel.git'
-gem "rack", :git => "git://github.com/rack/rack.git"
-<%- else -%>
-gem 'rails', '<%= Rails::VERSION::STRING %>'
+<%= rails_gemfile_entry -%>
-# Bundle edge Rails instead:
-# gem 'rails', :git => 'git://github.com/rails/rails.git'
-# gem 'arel', :git => 'git://github.com/rails/arel.git'
-# gem "rack", :git => "git://github.com/rack/rack.git"
-<%- end -%>
-
-<% unless options[:skip_active_record] -%>
-gem '<%= gem_for_database %>'<% if require_for_database %>, :require => '<%= require_for_database %>'<% end %>
-<% end -%>
+<%= database_gemfile_entry -%>
# Use unicorn as the web server
# gem 'unicorn'
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 00a23a7b89..6e515756fe 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -48,6 +48,10 @@ module <%= app_const_base %>
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
<% end -%>
+<% if options[:skip_test_unit] -%>
+ config.generators.test_framework = false
+<% end -%>
+
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
index ad9a79c433..a4f114586c 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
@@ -1,5 +1,5 @@
/*!
- * jQuery JavaScript Library v1.4.3
+ * jQuery JavaScript Library v1.4.4
* http://jquery.com/
*
* Copyright 2010, John Resig
@@ -11,7 +11,7 @@
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
- * Date: Thu Oct 14 23:10:06 2010 -0400
+ * Date: Thu Nov 11 19:04:53 2010 -0500
*/
(function( window, undefined ) {
@@ -211,7 +211,7 @@ jQuery.fn = jQuery.prototype = {
selector: "",
// The current version of jQuery being used
- jquery: "1.4.3",
+ jquery: "1.4.4",
// The default length of a jQuery object is 0
length: 0,
@@ -330,8 +330,11 @@ jQuery.fn = jQuery.prototype = {
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, copyIsArray;
+ var options, name, src, copy, copyIsArray, clone,
+ target = arguments[0] || {},
+ i = 1,
+ length = arguments.length,
+ deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
@@ -433,18 +436,21 @@ jQuery.extend({
// 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 );
- }
+ var fn,
+ i = 0,
+ ready = readyList;
// Reset the list of functions
readyList = null;
- }
- // Trigger any bound ready events
- if ( jQuery.fn.triggerHandler ) {
- jQuery( document ).triggerHandler( "ready" );
+ while ( (fn = ready[ i++ ]) ) {
+ fn.call( document, jQuery );
+ }
+
+ // Trigger any bound ready events
+ if ( jQuery.fn.trigger ) {
+ jQuery( document ).trigger( "ready" ).unbind( "ready" );
+ }
}
}
},
@@ -697,7 +703,8 @@ jQuery.extend({
},
merge: function( first, second ) {
- var i = first.length, j = 0;
+ var i = first.length,
+ j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
@@ -964,6 +971,7 @@ return (window.jQuery = window.$ = jQuery);
optSelected: opt.selected,
// Will be defined later
+ deleteExpando: true,
optDisabled: false,
checkClone: false,
scriptEval: false,
@@ -994,6 +1002,15 @@ return (window.jQuery = window.$ = jQuery);
delete window[ id ];
}
+ // Test to see if it's possible to delete an expando from an element
+ // Fails in Internet Explorer
+ try {
+ delete script.test;
+
+ } catch(e) {
+ jQuery.support.deleteExpando = false;
+ }
+
root.removeChild( script );
if ( div.attachEvent && div.fireEvent ) {
@@ -1087,20 +1104,6 @@ return (window.jQuery = window.$ = jQuery);
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 windowData = {},
@@ -1237,8 +1240,24 @@ jQuery.extend({
jQuery.fn.extend({
data: function( key, value ) {
+ var data = null;
+
if ( typeof key === "undefined" ) {
- return this.length ? jQuery.data( this[0] ) : null;
+ if ( this.length ) {
+ var attr = this[0].attributes, name;
+ data = jQuery.data( this[0] );
+
+ for ( var i = 0, l = attr.length; i < l; i++ ) {
+ name = attr[i].name;
+
+ if ( name.indexOf( "data-" ) === 0 ) {
+ name = name.substr( 5 );
+ dataAttr( this[0], name, data[ name ] );
+ }
+ }
+ }
+
+ return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
@@ -1250,31 +1269,12 @@ jQuery.fn.extend({
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
- var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
+ data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
-
- // If nothing was found internally, try to fetch any
- // data from the HTML5 data-* attribute
- if ( data === undefined && this[0].nodeType === 1 ) {
- data = this[0].getAttribute( "data-" + key );
-
- if ( typeof data === "string" ) {
- try {
- data = data === "true" ? true :
- data === "false" ? false :
- data === "null" ? null :
- !jQuery.isNaN( data ) ? parseFloat( data ) :
- rbrace.test( data ) ? jQuery.parseJSON( data ) :
- data;
- } catch( e ) {}
-
- } else {
- data = undefined;
- }
- }
+ data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
@@ -1283,7 +1283,8 @@ jQuery.fn.extend({
} else {
return this.each(function() {
- var $this = jQuery( this ), args = [ parts[0], value ];
+ var $this = jQuery( this ),
+ args = [ parts[0], value ];
$this.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
@@ -1299,6 +1300,33 @@ jQuery.fn.extend({
}
});
+function dataAttr( elem, key, data ) {
+ // If nothing was found internally, try to fetch any
+ // data from the HTML5 data-* attribute
+ if ( data === undefined && elem.nodeType === 1 ) {
+ data = elem.getAttribute( "data-" + key );
+
+ if ( typeof data === "string" ) {
+ try {
+ data = data === "true" ? true :
+ data === "false" ? false :
+ data === "null" ? null :
+ !jQuery.isNaN( data ) ? parseFloat( data ) :
+ rbrace.test( data ) ? jQuery.parseJSON( data ) :
+ data;
+ } catch( e ) {}
+
+ // Make sure we set the data so it isn't changed later
+ jQuery.data( elem, key, data );
+
+ } else {
+ data = undefined;
+ }
+ }
+
+ return data;
+}
+
@@ -1329,7 +1357,8 @@ jQuery.extend({
dequeue: function( elem, type ) {
type = type || "fx";
- var queue = jQuery.queue( elem, type ), fn = queue.shift();
+ var queue = jQuery.queue( elem, type ),
+ fn = queue.shift();
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
@@ -1405,6 +1434,19 @@ var rclass = /[\n\t]/g,
rclickable = /^a(?:rea)?$/i,
rradiocheck = /^(?:radio|checkbox)$/i;
+jQuery.props = {
+ "for": "htmlFor",
+ "class": "className",
+ readonly: "readOnly",
+ maxlength: "maxLength",
+ cellspacing: "cellSpacing",
+ rowspan: "rowSpan",
+ colspan: "colSpan",
+ tabindex: "tabIndex",
+ usemap: "useMap",
+ frameborder: "frameBorder"
+};
+
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
@@ -1438,7 +1480,9 @@ jQuery.fn.extend({
elem.className = value;
} else {
- var className = " " + elem.className + " ", setClass = elem.className;
+ var className = " " + elem.className + " ",
+ setClass = elem.className;
+
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
setClass += " " + classNames[c];
@@ -1486,7 +1530,8 @@ jQuery.fn.extend({
},
toggleClass: function( value, stateVal ) {
- var type = typeof value, isBool = typeof stateVal === "boolean";
+ var type = typeof value,
+ isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
@@ -1498,7 +1543,9 @@ jQuery.fn.extend({
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
- var className, i = 0, self = jQuery(this),
+ var className,
+ i = 0,
+ self = jQuery( this ),
state = stateVal,
classNames = value.split( rspaces );
@@ -1667,91 +1714,88 @@ jQuery.extend({
// 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;
- }
- }
- }
+ // These attributes require special treatment
+ var special = rspecialurl.test( name );
- // If applicable, access the attribute via the DOM 0 way
- // 'in' checks fail in Blackberry 4.7 #6931
- if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
- if ( set ) {
- // We can't allow the type property to be changed (since it causes problems in IE)
- if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
- jQuery.error( "type property can't be changed" );
- }
+ // Safari mis-reports the default selected property of an option
+ // Accessing the parent's selectedIndex property fixes it
+ if ( name === "selected" && !jQuery.support.optSelected ) {
+ var parent = elem.parentNode;
+ if ( parent ) {
+ parent.selectedIndex;
- if ( value === null ) {
- if ( elem.nodeType === 1 ) {
- elem.removeAttribute( name );
- }
-
- } else {
- elem[ name ] = value;
- }
+ // Make sure that it also works with optgroups, see #5701
+ if ( parent.parentNode ) {
+ parent.parentNode.selectedIndex;
}
+ }
+ }
- // browsers index elements by id/name on forms, give priority to attributes.
- if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
- return elem.getAttributeNode( name ).nodeValue;
+ // If applicable, access the attribute via the DOM 0 way
+ // 'in' checks fail in Blackberry 4.7 #6931
+ if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
+ if ( set ) {
+ // We can't allow the type property to be changed (since it causes problems in IE)
+ if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
+ jQuery.error( "type property can't be changed" );
}
- // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
- // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
- if ( name === "tabIndex" ) {
- var attributeNode = elem.getAttributeNode( "tabIndex" );
+ if ( value === null ) {
+ if ( elem.nodeType === 1 ) {
+ elem.removeAttribute( name );
+ }
- return attributeNode && attributeNode.specified ?
- attributeNode.value :
- rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
- 0 :
- undefined;
+ } else {
+ elem[ name ] = value;
}
+ }
- return elem[ name ];
+ // browsers index elements by id/name on forms, give priority to attributes.
+ if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
+ return elem.getAttributeNode( name ).nodeValue;
}
- if ( !jQuery.support.style && notxml && name === "style" ) {
- if ( set ) {
- elem.style.cssText = "" + value;
- }
+ // 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 elem.style.cssText;
+ 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 ) {
- // convert the value to a string (all browsers do this but IE) see #1070
- elem.setAttribute( name, "" + value );
+ elem.style.cssText = "" + value;
}
- // Ensure that missing attributes return undefined
- // Blackberry 4.7 returns "" from getAttribute #6938
- if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
- return undefined;
- }
+ return elem.style.cssText;
+ }
- var attr = !jQuery.support.hrefNormalized && notxml && special ?
- // Some attributes require a special call on IE
- elem.getAttribute( name, 2 ) :
- elem.getAttribute( name );
+ if ( set ) {
+ // convert the value to a string (all browsers do this but IE) see #1070
+ elem.setAttribute( name, "" + value );
+ }
- // Non-existent attributes return null, we normalize to undefined
- return attr === null ? undefined : attr;
+ // Ensure that missing attributes return undefined
+ // Blackberry 4.7 returns "" from getAttribute #6938
+ if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
+ return undefined;
}
+
+ 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;
}
});
@@ -1790,6 +1834,9 @@ jQuery.event = {
if ( handler === false ) {
handler = returnFalse;
+ } else if ( !handler ) {
+ // Fixes bug #7229. Fix recommended by jdalton
+ return;
}
var handleObjIn, handleObj;
@@ -2133,8 +2180,10 @@ jQuery.event = {
jQuery.event.trigger( event, data, parent, true );
} else if ( !event.isDefaultPrevented() ) {
- var target = event.target, old, targetType = type.replace(rnamespaces, ""),
- isClick = jQuery.nodeName(target, "a") && targetType === "click",
+ var old,
+ target = event.target,
+ targetType = type.replace( rnamespaces, "" ),
+ isClick = jQuery.nodeName( target, "a" ) && targetType === "click",
special = jQuery.event.special[ targetType ] || {};
if ( (!special._default || special._default.call( elem, event ) === false) &&
@@ -2166,7 +2215,9 @@ jQuery.event = {
},
handle: function( event ) {
- var all, handlers, namespaces, namespace_sort = [], namespace_re, events, args = jQuery.makeArray( arguments );
+ var all, handlers, namespaces, namespace_re, events,
+ namespace_sort = [],
+ args = jQuery.makeArray( arguments );
event = args[0] = jQuery.event.fix( event || window.event );
event.currentTarget = this;
@@ -2245,7 +2296,8 @@ jQuery.event = {
// Fix target property, if necessary
if ( !event.target ) {
- event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
+ // Fixes #1925 where srcElement might not be defined either
+ event.target = event.srcElement || document;
}
// check if target is a textnode (safari)
@@ -2260,7 +2312,9 @@ jQuery.event = {
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
- var doc = document.documentElement, body = document.body;
+ 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);
}
@@ -2466,7 +2520,8 @@ if ( !jQuery.support.submitBubbles ) {
setup: function( data, namespaces ) {
if ( this.nodeName.toLowerCase() !== "form" ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
- var elem = e.target, type = elem.type;
+ var elem = e.target,
+ type = elem.type;
if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
e.liveFired = undefined;
@@ -2475,7 +2530,8 @@ if ( !jQuery.support.submitBubbles ) {
});
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
- var elem = e.target, type = elem.type;
+ var elem = e.target,
+ type = elem.type;
if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
e.liveFired = undefined;
@@ -2716,7 +2772,8 @@ jQuery.fn.extend({
toggle: function( fn ) {
// Save reference to arguments for access in closure
- var args = arguments, i = 1;
+ var args = arguments,
+ i = 1;
// link all the functions, so any of them can unbind this click handler
while ( i < args.length ) {
@@ -2811,8 +2868,9 @@ jQuery.each(["live", "die"], function( i, name ) {
});
function liveHandler( event ) {
- var stop, maxLevel, elems = [], selectors = [],
- related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
+ var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
+ elems = [],
+ selectors = [],
events = jQuery.data( this, this.nodeType ? "events" : "__events__" );
if ( typeof events === "function" ) {
@@ -2823,7 +2881,7 @@ function liveHandler( event ) {
if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) {
return;
}
-
+
if ( event.namespace ) {
namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
}
@@ -2887,6 +2945,9 @@ function liveHandler( event ) {
if ( ret === false ) {
stop = false;
}
+ if ( event.isImmediatePropagationStopped() ) {
+ break;
+ }
}
}
@@ -2954,12 +3015,12 @@ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[
// 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(){
+[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
-var Sizzle = function(selector, context, results, seed) {
+var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
@@ -2973,13 +3034,16 @@ var Sizzle = function(selector, context, results, seed) {
return results;
}
- var parts = [], m, set, checkSet, extra, prune = true, contextXML = Sizzle.isXML(context),
- soFar = selector, ret, cur, pop, i;
+ var m, set, checkSet, extra, ret, cur, pop, i,
+ prune = true,
+ contextXML = Sizzle.isXML( context ),
+ parts = [],
+ soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
- chunker.exec("");
- m = chunker.exec(soFar);
+ chunker.exec( "" );
+ m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
@@ -2994,8 +3058,10 @@ var Sizzle = function(selector, context, results, seed) {
} while ( m );
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 ] :
@@ -3011,23 +3077,31 @@ var Sizzle = function(selector, context, results, seed) {
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]) ) {
+
ret = Sizzle.find( parts.shift(), context, contextXML );
- context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
+ context = ret.expr ?
+ Sizzle.filter( ret.expr, ret.set )[0] :
+ ret.set[0];
}
if ( context ) {
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;
+
+ set = ret.expr ?
+ Sizzle.filter( ret.expr, ret.set ) :
+ ret.set;
if ( parts.length > 0 ) {
- checkSet = makeArray(set);
+ checkSet = makeArray( set );
+
} else {
prune = false;
}
@@ -3048,6 +3122,7 @@ var Sizzle = function(selector, context, results, seed) {
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
+
} else {
checkSet = parts = [];
}
@@ -3064,12 +3139,14 @@ var Sizzle = function(selector, context, results, seed) {
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
+
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
+
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
@@ -3077,6 +3154,7 @@ var Sizzle = function(selector, context, results, seed) {
}
}
}
+
} else {
makeArray( checkSet, results );
}
@@ -3089,15 +3167,15 @@ var Sizzle = function(selector, context, results, seed) {
return results;
};
-Sizzle.uniqueSort = function(results){
+Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
- results.sort(sortOrder);
+ results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
- if ( results[i] === results[i-1] ) {
- results.splice(i--, 1);
+ if ( results[i] === results[ i - 1 ] ) {
+ results.splice( i--, 1 );
}
}
}
@@ -3106,15 +3184,15 @@ Sizzle.uniqueSort = function(results){
return results;
};
-Sizzle.matches = function(expr, set){
- return Sizzle(expr, null, null, set);
+Sizzle.matches = function( expr, set ) {
+ return Sizzle( expr, null, null, set );
};
-Sizzle.matchesSelector = function(node, expr){
- return Sizzle(expr, null, null, [node]).length > 0;
+Sizzle.matchesSelector = function( node, expr ) {
+ return Sizzle( expr, null, null, [node] ).length > 0;
};
-Sizzle.find = function(expr, context, isXML){
+Sizzle.find = function( expr, context, isXML ) {
var set;
if ( !expr ) {
@@ -3122,15 +3200,17 @@ Sizzle.find = function(expr, context, isXML){
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
- var type = Expr.order[i], match;
+ var match,
+ type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
- match.splice(1,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;
@@ -3140,20 +3220,26 @@ Sizzle.find = function(expr, context, isXML){
}
if ( !set ) {
- set = context.getElementsByTagName("*");
+ set = context.getElementsByTagName( "*" );
}
- return {set: set, expr: expr};
+ return { set: set, expr: expr };
};
-Sizzle.filter = function(expr, set, inplace, not){
- var old = expr, result = [], curLoop = set, match, anyFound,
- isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);
+Sizzle.filter = function( expr, set, inplace, not ) {
+ var match, anyFound,
+ old = expr,
+ result = [],
+ curLoop = set,
+ isXMLFilter = set && set[0] && Sizzle.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];
+ var found, item,
+ filter = Expr.filter[ type ],
+ left = match[1];
+
anyFound = false;
match.splice(1,1);
@@ -3171,6 +3257,7 @@ Sizzle.filter = function(expr, set, inplace, not){
if ( !match ) {
anyFound = found = true;
+
} else if ( match === true ) {
continue;
}
@@ -3185,9 +3272,11 @@ Sizzle.filter = function(expr, set, inplace, not){
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
+
} else {
curLoop[i] = false;
}
+
} else if ( pass ) {
result.push( item );
anyFound = true;
@@ -3216,6 +3305,7 @@ Sizzle.filter = function(expr, set, inplace, not){
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
+
} else {
break;
}
@@ -3233,6 +3323,7 @@ Sizzle.error = function( msg ) {
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
+
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
@@ -3243,20 +3334,24 @@ var Expr = Sizzle.selectors = {
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");
+ href: function( elem ) {
+ return elem.getAttribute( "href" );
}
},
+
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
- isTag = isPartStr && !/\W/.test(part),
+ isTag = isPartStr && !/\W/.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
@@ -3277,23 +3372,29 @@ var Expr = Sizzle.selectors = {
Sizzle.filter( part, checkSet, true );
}
},
- ">": function(checkSet, part){
- var isPartStr = typeof part === "string",
- elem, i = 0, l = checkSet.length;
- if ( isPartStr && !/\W/.test(part) ) {
+ ">": function( checkSet, part ) {
+ var elem,
+ isPartStr = typeof part === "string",
+ i = 0,
+ l = checkSet.length;
+
+ if ( isPartStr && !/\W/.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
+
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
+
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
+
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
@@ -3306,8 +3407,11 @@ var Expr = Sizzle.selectors = {
}
}
},
+
"": function(checkSet, part, isXML){
- var doneName = done++, checkFn = dirCheck, nodeCheck;
+ var nodeCheck,
+ doneName = done++,
+ checkFn = dirCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
part = part.toLowerCase();
@@ -3315,22 +3419,26 @@ var Expr = Sizzle.selectors = {
checkFn = dirNodeCheck;
}
- checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
+ checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
- "~": function(checkSet, part, isXML){
- var doneName = done++, checkFn = dirCheck, nodeCheck;
- if ( typeof part === "string" && !/\W/.test(part) ) {
+ "~": function( checkSet, part, isXML ) {
+ var nodeCheck,
+ doneName = done++,
+ checkFn = dirCheck;
+
+ if ( typeof part === "string" && !/\W/.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
- checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
+ checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
+
find: {
- ID: function(match, context, isXML){
+ ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
@@ -3338,9 +3446,11 @@ var Expr = Sizzle.selectors = {
return m && m.parentNode ? [m] : [];
}
},
- NAME: function(match, context){
+
+ NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
- var ret = [], results = context.getElementsByName(match[1]);
+ var ret = [],
+ results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
@@ -3351,12 +3461,13 @@ var Expr = Sizzle.selectors = {
return ret.length === 0 ? null : ret;
}
},
- TAG: function(match, context){
- return context.getElementsByTagName(match[1]);
+
+ TAG: function( match, context ) {
+ return context.getElementsByTagName( match[1] );
}
},
preFilter: {
- CLASS: function(match, curLoop, inplace, result, not, isXML){
+ CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
@@ -3369,6 +3480,7 @@ var Expr = Sizzle.selectors = {
if ( !inplace ) {
result.push( elem );
}
+
} else if ( inplace ) {
curLoop[i] = false;
}
@@ -3377,13 +3489,16 @@ var Expr = Sizzle.selectors = {
return false;
},
- ID: function(match){
+
+ ID: function( match ) {
return match[1].replace(/\\/g, "");
},
- TAG: function(match, curLoop){
+
+ TAG: function( match, curLoop ) {
return match[1].toLowerCase();
},
- CHILD: function(match){
+
+ 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(
@@ -3400,7 +3515,8 @@ var Expr = Sizzle.selectors = {
return match;
},
- ATTR: function(match, curLoop, inplace, result, not, isXML){
+
+ ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
@@ -3413,122 +3529,156 @@ var Expr = Sizzle.selectors = {
return match;
},
- PSEUDO: function(match, curLoop, inplace, result, not){
+
+ 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){
+
+ POS: function( match ) {
match.unshift( true );
+
return match;
}
},
+
filters: {
- enabled: function(elem){
+ enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
- disabled: function(elem){
+
+ disabled: function( elem ) {
return elem.disabled === true;
},
- checked: function(elem){
+
+ checked: function( elem ) {
return elem.checked === true;
},
- selected: function(elem){
+
+ 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){
+
+ parent: function( elem ) {
return !!elem.firstChild;
},
- empty: function(elem){
+
+ empty: function( elem ) {
return !elem.firstChild;
},
- has: function(elem, i, match){
+
+ has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
- header: function(elem){
+
+ header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
- text: function(elem){
+
+ text: function( elem ) {
return "text" === elem.type;
},
- radio: function(elem){
+ radio: function( elem ) {
return "radio" === elem.type;
},
- checkbox: function(elem){
+
+ checkbox: function( elem ) {
return "checkbox" === elem.type;
},
- file: function(elem){
+
+ file: function( elem ) {
return "file" === elem.type;
},
- password: function(elem){
+ password: function( elem ) {
return "password" === elem.type;
},
- submit: function(elem){
+
+ submit: function( elem ) {
return "submit" === elem.type;
},
- image: function(elem){
+
+ image: function( elem ) {
return "image" === elem.type;
},
- reset: function(elem){
+
+ reset: function( elem ) {
return "reset" === elem.type;
},
- button: function(elem){
+
+ button: function( elem ) {
return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
},
- input: function(elem){
- return (/input|select|textarea|button/i).test(elem.nodeName);
+
+ input: function( elem ) {
+ return (/input|select|textarea|button/i).test( elem.nodeName );
}
},
setFilters: {
- first: function(elem, i){
+ first: function( elem, i ) {
return i === 0;
},
- last: function(elem, i, match, array){
+
+ last: function( elem, i, match, array ) {
return i === array.length - 1;
},
- even: function(elem, i){
+
+ even: function( elem, i ) {
return i % 2 === 0;
},
- odd: function(elem, i){
+
+ odd: function( elem, i ) {
return i % 2 === 1;
},
- lt: function(elem, i, match){
+
+ lt: function( elem, i, match ) {
return i < match[3] - 0;
},
- gt: function(elem, i, match){
+
+ gt: function( elem, i, match ) {
return i > match[3] - 0;
},
- nth: function(elem, i, match){
+
+ nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
- eq: function(elem, i, match){
+
+ 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 ];
+ 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 || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
+
} else if ( name === "not" ) {
var not = match[3];
@@ -3539,33 +3689,43 @@ var Expr = Sizzle.selectors = {
}
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':
+
+ 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':
+
+ case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
+
return true;
- case 'nth':
- var first = match[2], last = match[3];
+
+ case "nth":
+ var first = match[2],
+ last = match[3];
if ( first === 1 && last === 0 ) {
return true;
@@ -3576,33 +3736,41 @@ var Expr = Sizzle.selectors = {
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){
+
+ ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
- TAG: function(elem, match){
+
+ TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
- CLASS: function(elem, match){
+
+ CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
- ATTR: function(elem, match){
+
+ ATTR: function( elem, match ) {
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
@@ -3633,8 +3801,10 @@ var Expr = Sizzle.selectors = {
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
- POS: function(elem, match, i, array){
- var name = match[2], filter = Expr.setFilters[ name ];
+
+ POS: function( elem, match, i, array ) {
+ var name = match[2],
+ filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
@@ -3653,7 +3823,7 @@ for ( var type in Expr.match ) {
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
-var makeArray = function(array, results) {
+var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
@@ -3672,17 +3842,20 @@ try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
-} catch(e){
- makeArray = function(array, results) {
- var ret = results || [], i = 0;
+} catch( e ) {
+ makeArray = function( array, results ) {
+ var i = 0,
+ ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
+
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
+
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
@@ -3709,10 +3882,15 @@ if ( document.documentElement.compareDocumentPosition ) {
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
+
} else {
sortOrder = function( a, b ) {
- var ap = [], bp = [], aup = a.parentNode, bup = b.parentNode,
- cur = aup, al, bl;
+ var al, bl,
+ ap = [],
+ bp = [],
+ aup = a.parentNode,
+ bup = b.parentNode,
+ cur = aup;
// The nodes are identical, we can exit early
if ( a === b ) {
@@ -3805,31 +3983,40 @@ Sizzle.getText = function( elems ) {
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
- id = "script" + (new Date()).getTime();
+ id = "script" + (new Date()).getTime(),
+ root = document.documentElement;
+
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){
+ 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 : [];
+
+ return m ?
+ m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
+ [m] :
+ undefined :
+ [];
}
};
- Expr.filter.ID = function(elem, match){
+ 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
+
+ // release memory in IE
+ root = form = null;
})();
(function(){
@@ -3842,8 +4029,8 @@ Sizzle.getText = function( elems ) {
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
- Expr.find.TAG = function(match, context){
- var results = context.getElementsByTagName(match[1]);
+ Expr.find.TAG = function( match, context ) {
+ var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
@@ -3864,19 +4051,25 @@ Sizzle.getText = function( elems ) {
// 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);
+
+ Expr.attrHandle.href = function( elem ) {
+ return elem.getAttribute( "href", 2 );
};
}
- div = null; // release memory in IE
+ // release memory in IE
+ div = null;
})();
if ( document.querySelectorAll ) {
(function(){
- var oldSizzle = Sizzle, div = document.createElement("div");
+ var oldSizzle = Sizzle,
+ div = document.createElement("div"),
+ id = "__sizzle__";
+
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
@@ -3885,9 +4078,12 @@ if ( document.querySelectorAll ) {
return;
}
- Sizzle = function(query, context, extra, seed){
+ Sizzle = function( query, context, extra, seed ) {
context = context || document;
+ // Make sure that attribute selectors are quoted
+ query = query.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
+
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
@@ -3901,17 +4097,19 @@ if ( document.querySelectorAll ) {
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
- var old = context.id, id = context.id = "__sizzle__";
+ var old = context.getAttribute( "id" ),
+ nid = old || id;
+
+ if ( !old ) {
+ context.setAttribute( "id", nid );
+ }
try {
- return makeArray( context.querySelectorAll( "#" + id + " " + query ), extra );
+ return makeArray( context.querySelectorAll( "#" + nid + " " + query ), extra );
} catch(pseudoError) {
} finally {
- if ( old ) {
- context.id = old;
-
- } else {
+ if ( !old ) {
context.removeAttribute( "id" );
}
}
@@ -3925,7 +4123,8 @@ if ( document.querySelectorAll ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
- div = null; // release memory in IE
+ // release memory in IE
+ div = null;
})();
}
@@ -3937,7 +4136,7 @@ if ( document.querySelectorAll ) {
try {
// This should fail with an exception
// Gecko does not error, returns false instead
- matches.call( document.documentElement, ":sizzle" );
+ matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
@@ -3945,13 +4144,18 @@ if ( document.querySelectorAll ) {
if ( matches ) {
Sizzle.matchesSelector = function( node, expr ) {
+ // Make sure that attribute selectors are quoted
+ expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
+
+ if ( !Sizzle.isXML( node ) ) {
try {
- if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) ) {
+ if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
return matches.call( node, expr );
}
} catch(e) {}
+ }
- return Sizzle(expr, null, null, [node]).length > 0;
+ return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
@@ -3975,22 +4179,25 @@ if ( document.querySelectorAll ) {
}
Expr.order.splice(1, 0, "CLASS");
- Expr.find.CLASS = function(match, context, isXML) {
+ Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
- div = null; // release memory in IE
+ // release memory in IE
+ div = null;
})();
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;
+ elem = elem[dir];
+
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
@@ -4018,9 +4225,11 @@ function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
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;
+
+ elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
@@ -4033,6 +4242,7 @@ function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
+
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
@@ -4053,21 +4263,34 @@ function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
}
}
-Sizzle.contains = document.documentElement.contains ? function(a, b){
- return a !== b && (a.contains ? a.contains(b) : true);
-} : function(a, b){
- return !!(a.compareDocumentPosition(b) & 16);
-};
+if ( document.documentElement.contains ) {
+ Sizzle.contains = function( a, b ) {
+ return a !== b && (a.contains ? a.contains(b) : true);
+ };
-Sizzle.isXML = function(elem){
+} else if ( document.documentElement.compareDocumentPosition ) {
+ Sizzle.contains = function( a, b ) {
+ return !!(a.compareDocumentPosition(b) & 16);
+ };
+
+} else {
+ Sizzle.contains = function() {
+ return false;
+ };
+}
+
+Sizzle.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,
+var posProcess = function( selector, context ) {
+ var match,
+ tmpSet = [],
+ later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
@@ -4109,7 +4332,8 @@ var runtil = /Until$/,
jQuery.fn.extend({
find: function( selector ) {
- var ret = this.pushStack( "", "find", selector ), length = 0;
+ var ret = this.pushStack( "", "find", selector ),
+ length = 0;
for ( var i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
@@ -4158,7 +4382,9 @@ jQuery.fn.extend({
var ret = [], i, l, cur = this[0];
if ( jQuery.isArray( selectors ) ) {
- var match, matches = {}, selector, level = 1;
+ var match, selector,
+ matches = {},
+ level = 1;
if ( cur && selectors.length ) {
for ( i = 0, l = selectors.length; i < l; i++ ) {
@@ -4324,7 +4550,9 @@ jQuery.extend({
},
dir: function( elem, dir, until ) {
- var matched = [], cur = elem[dir];
+ 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 );
@@ -4400,7 +4628,8 @@ var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnocache = /<(?:script|object|embed|option|style)/i,
- rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, // checked="checked" or checked (html5)
+ // checked="checked" or checked (html5)
+ rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
raction = /\=([^="'>\s]+\/)>/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
@@ -4426,7 +4655,8 @@ jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
- var self = jQuery(this);
+ var self = jQuery( this );
+
self.text( text.call(this, i, self.text()) );
});
}
@@ -4475,7 +4705,8 @@ jQuery.fn.extend({
}
return this.each(function() {
- var self = jQuery( this ), contents = self.contents();
+ var self = jQuery( this ),
+ contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
@@ -4586,7 +4817,9 @@ jQuery.fn.extend({
// 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;
+ var html = this.outerHTML,
+ ownerDocument = this.ownerDocument;
+
if ( !html ) {
var div = ownerDocument.createElement("div");
div.appendChild( this.cloneNode(true) );
@@ -4641,7 +4874,8 @@ jQuery.fn.extend({
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
- var self = jQuery(this);
+ var self = jQuery( this );
+
self.html( value.call(this, i, self.html()) );
});
@@ -4664,13 +4898,14 @@ jQuery.fn.extend({
}
if ( typeof value !== "string" ) {
- value = jQuery(value).detach();
+ value = jQuery( value ).detach();
}
return this.each(function() {
- var next = this.nextSibling, parent = this.parentNode;
+ var next = this.nextSibling,
+ parent = this.parentNode;
- jQuery(this).remove();
+ jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
@@ -4688,7 +4923,9 @@ jQuery.fn.extend({
},
domManip: function( args, table, callback ) {
- var results, first, value = args[0], scripts = [], fragment, parent;
+ var results, first, fragment, parent,
+ 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 ) ) {
@@ -4763,7 +5000,9 @@ function cloneCopyEvent(orig, ret) {
return;
}
- var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events;
+ var oldData = jQuery.data( orig[i++] ),
+ curData = jQuery.data( this, oldData ),
+ events = oldData && oldData.events;
if ( events ) {
delete curData.handle;
@@ -4820,7 +5059,8 @@ jQuery.each({
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
- var ret = [], insert = jQuery( selector ),
+ var ret = [],
+ insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
@@ -5004,8 +5244,8 @@ var ralpha = /alpha\([^)]*\)/i,
cssHeight = [ "Top", "Bottom" ],
curCSS,
- // cache check for defaultView.getComputedStyle
- getComputedStyle = document.defaultView && document.defaultView.getComputedStyle,
+ getComputedStyle,
+ currentStyle,
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
@@ -5161,7 +5401,29 @@ jQuery.each(["height", "width"], function( i, name ) {
});
}
- return val + "px";
+ if ( val <= 0 ) {
+ val = curCSS( elem, name, name );
+
+ if ( val === "0px" && currentStyle ) {
+ val = currentStyle( elem, name, name );
+ }
+
+ if ( val != null ) {
+ // Should return "auto" instead of 0, use 0 for
+ // temporary backwards-compat
+ return val === "" || val === "auto" ? "0px" : val;
+ }
+ }
+
+ if ( val < 0 || val == null ) {
+ val = elem.style[ name ];
+
+ // Should return "auto" instead of 0, use 0 for
+ // temporary backwards-compat
+ return val === "" || val === "auto" ? "0px" : val;
+ }
+
+ return typeof val === "string" ? val : val + "px";
}
},
@@ -5210,8 +5472,8 @@ if ( !jQuery.support.opacity ) {
};
}
-if ( getComputedStyle ) {
- curCSS = function( elem, newName, name ) {
+if ( document.defaultView && document.defaultView.getComputedStyle ) {
+ getComputedStyle = function( elem, newName, name ) {
var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase();
@@ -5229,10 +5491,13 @@ if ( getComputedStyle ) {
return ret;
};
+}
-} else if ( document.documentElement.currentStyle ) {
- curCSS = function( elem, name ) {
- var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style;
+if ( document.documentElement.currentStyle ) {
+ currentStyle = function( elem, name ) {
+ var left, rsLeft,
+ ret = elem.currentStyle && elem.currentStyle[ name ],
+ style = elem.style;
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
@@ -5254,10 +5519,12 @@ if ( getComputedStyle ) {
elem.runtimeStyle.left = rsLeft;
}
- return ret;
+ return ret === "" ? "auto" : ret;
};
}
+curCSS = getComputedStyle || currentStyle;
+
function getWH( elem, name, extra ) {
var which = name === "width" ? cssWidth : cssHeight,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
@@ -5284,7 +5551,8 @@ function getWH( elem, name, extra ) {
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
- var width = elem.offsetWidth, height = elem.offsetHeight;
+ var width = elem.offsetWidth,
+ height = elem.offsetHeight;
return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
};
@@ -5301,7 +5569,7 @@ var jsc = jQuery.now(),
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
- rnoContent = /^(?:GET|HEAD|DELETE)$/,
+ rnoContent = /^(?:GET|HEAD)$/,
rbracket = /\[\]$/,
jsre = /\=\?(&|$)/,
rquery = /\?/,
@@ -5536,10 +5804,6 @@ jQuery.extend({
var customJsonp = window[ jsonp ];
window[ jsonp ] = function( tmp ) {
- data = tmp;
- jQuery.handleSuccess( s, xhr, status, data );
- jQuery.handleComplete( s, xhr, status, data );
-
if ( jQuery.isFunction( customJsonp ) ) {
customJsonp( tmp );
@@ -5551,6 +5815,10 @@ jQuery.extend({
delete window[ jsonp ];
} catch( jsonpError ) {}
}
+
+ data = tmp;
+ jQuery.handleSuccess( s, xhr, status, data );
+ jQuery.handleComplete( s, xhr, status, data );
if ( head ) {
head.removeChild( script );
@@ -5562,7 +5830,7 @@ jQuery.extend({
s.cache = false;
}
- if ( s.cache === false && type === "GET" ) {
+ if ( s.cache === false && noContent ) {
var ts = jQuery.now();
// try replacing _= if it is there
@@ -5572,8 +5840,8 @@ jQuery.extend({
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" ) {
+ // If data is available, append data to url for GET/HEAD requests
+ if ( s.data && noContent ) {
s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
}
@@ -5584,7 +5852,7 @@ jQuery.extend({
// 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);
+ remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host);
// If we're requesting a remote document
// and trying to load JSON or Script with a GET
@@ -5760,10 +6028,11 @@ jQuery.extend({
try {
var oldAbort = xhr.abort;
xhr.abort = function() {
- // xhr.abort in IE7 is not a native JS function
- // and does not have a call property
- if ( xhr && oldAbort.call ) {
- oldAbort.call( xhr );
+ if ( xhr ) {
+ // oldAbort has no call property in IE7 so
+ // just do it this way, which works in all
+ // browsers
+ Function.prototype.call.call( oldAbort, xhr );
}
onreadystatechange( "abort" );
@@ -5803,11 +6072,12 @@ jQuery.extend({
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
- var s = [], add = function( key, value ) {
- // If value is a function, invoke it and return its value
- value = jQuery.isFunction(value) ? value() : value;
- s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
- };
+ var s = [],
+ add = function( key, value ) {
+ // If value is a function, invoke it and return its value
+ value = jQuery.isFunction(value) ? value() : value;
+ s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
+ };
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
@@ -6029,28 +6299,39 @@ var elemdisplay = {},
jQuery.fn.extend({
show: function( speed, easing, callback ) {
+ var elem, display;
+
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback);
+
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
+ elem = this[i];
+ display = elem.style.display;
+
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
- if ( !jQuery.data(this[i], "olddisplay") && this[i].style.display === "none" ) {
- this[i].style.display = "";
+ if ( !jQuery.data(elem, "olddisplay") && display === "none" ) {
+ display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
- if ( this[i].style.display === "" && jQuery.css( this[i], "display" ) === "none" ) {
- jQuery.data(this[i], "olddisplay", defaultDisplay(this[i].nodeName));
+ if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
+ jQuery.data(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
- this[i].style.display = jQuery.data(this[i], "olddisplay") || "";
+ elem = this[i];
+ display = elem.style.display;
+
+ if ( display === "" || display === "none" ) {
+ elem.style.display = jQuery.data(elem, "olddisplay") || "";
+ }
}
return this;
@@ -6115,7 +6396,7 @@ jQuery.fn.extend({
}
return this[ optall.queue === false ? "each" : "queue" ](function() {
- // XXX ‘this’ does not always have a nodeName when running the
+ // XXX 'this' does not always have a nodeName when running the
// test suite
var opt = jQuery.extend({}, optall), p,
@@ -6188,7 +6469,7 @@ jQuery.fn.extend({
} else {
var parts = rfxnum.exec(val),
- start = e.cur(true) || 0;
+ start = e.cur() || 0;
if ( parts ) {
var end = parseFloat( parts[2] ),
@@ -6197,7 +6478,7 @@ jQuery.fn.extend({
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( self, name, (end || 1) + unit);
- start = ((end || 1) / e.cur(true)) * start;
+ start = ((end || 1) / e.cur()) * start;
jQuery.style( self, name, start + unit);
}
@@ -6266,7 +6547,8 @@ jQuery.each({
slideUp: genFx("hide", 1),
slideToggle: genFx("toggle", 1),
fadeIn: { opacity: "show" },
- fadeOut: { opacity: "hide" }
+ fadeOut: { opacity: "hide" },
+ fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
@@ -6344,6 +6626,9 @@ jQuery.fx.prototype = {
// Start an animation from one number to another
custom: function( from, to, unit ) {
+ var self = this,
+ fx = jQuery.fx;
+
this.startTime = jQuery.now();
this.start = from;
this.end = to;
@@ -6351,7 +6636,6 @@ jQuery.fx.prototype = {
this.now = this.start;
this.pos = this.state = 0;
- var self = this, fx = jQuery.fx;
function t( gotoEnd ) {
return self.step(gotoEnd);
}
@@ -6408,7 +6692,9 @@ jQuery.fx.prototype = {
if ( done ) {
// Reset the overflow
if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
- var elem = this.elem, options = this.options;
+ var elem = this.elem,
+ options = this.options;
+
jQuery.each( [ "", "X", "Y" ], function (index, value) {
elem.style[ "overflow" + value ] = options.overflow[index];
} );
@@ -6587,11 +6873,16 @@ if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.offset.initialize();
- var offsetParent = elem.offsetParent, prevOffsetParent = elem,
- doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
- body = doc.body, defaultView = doc.defaultView,
+ var computedStyle,
+ offsetParent = elem.offsetParent,
+ prevOffsetParent = elem,
+ doc = elem.ownerDocument,
+ docElem = doc.documentElement,
+ body = doc.body,
+ defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
- top = elem.offsetTop, left = elem.offsetLeft;
+ top = elem.offsetTop,
+ left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
@@ -6673,7 +6964,8 @@ jQuery.offset = {
},
bodyOffset: function( body ) {
- var top = body.offsetTop, left = body.offsetLeft;
+ var top = body.offsetTop,
+ left = body.offsetLeft;
jQuery.offset.initialize();
@@ -6854,27 +7146,31 @@ jQuery.each([ "Height", "Width" ], function( i, name ) {
});
}
- return jQuery.isWindow( elem ) ?
+ if ( jQuery.isWindow( elem ) ) {
// 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
- parseFloat( 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" );
+ return elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] ||
+ elem.document.body[ "client" + name ];
+
+ // Get document width or height
+ } else if ( elem.nodeType === 9 ) {
+ // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
+ return 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
+ } else if ( size === undefined ) {
+ var orig = jQuery.css( elem, type ),
+ ret = parseFloat( orig );
+
+ return jQuery.isNaN( ret ) ? orig : ret;
+
+ // Set the width or height on the element (default to pixels if value is unitless)
+ } else {
+ return this.css( type, typeof size === "string" ? size : size + "px" );
+ }
};
});
diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
index 40ed2062d3..97f681d826 100644
--- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
@@ -1,3 +1,4 @@
+
require 'rails/generators/rails/generator/generator_generator'
module Rails
@@ -5,6 +6,12 @@ module Rails
class PluginGenerator < NamedBase
class_option :tasks, :desc => "When supplied creates tasks base files."
+ def show_deprecation
+ return unless behavior == :invoke
+ message = "Plugin generator is deprecated, please use 'rails plugin new' command to generate plugin structure."
+ ActiveSupport::Deprecation.warn message
+ end
+
check_class_collision
def create_root_files
diff --git a/railties/lib/rails/generators/rails/plugin_new/USAGE b/railties/lib/rails/generators/rails/plugin_new/USAGE
new file mode 100644
index 0000000000..9a7bf9f396
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/USAGE
@@ -0,0 +1,10 @@
+Description:
+ The 'rails plugin new' command creates a skeleton for developing any
+ kind of Rails extension with ability to run tests using dummy Rails
+ application.
+
+Example:
+ rails plugin new ~/Code/Ruby/blog
+
+ This generates a skeletal Rails plugin in ~/Code/Ruby/blog.
+ See the README in the newly created plugin to get going.
diff --git a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
new file mode 100644
index 0000000000..9c54b98238
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
@@ -0,0 +1,249 @@
+require 'active_support/core_ext/hash/slice'
+require "rails/generators/rails/app/app_generator"
+
+module Rails
+ class PluginBuilder
+ def rakefile
+ template "Rakefile"
+ end
+
+ def app
+ directory "app" if options[:mountable]
+ end
+
+ def readme
+ copy_file "README.rdoc"
+ end
+
+ def gemfile
+ template "Gemfile"
+ end
+
+ def license
+ template "MIT-LICENSE"
+ end
+
+ def gemspec
+ template "%name%.gemspec"
+ end
+
+ def gitignore
+ copy_file "gitignore", ".gitignore"
+ end
+
+ def lib
+ template "lib/%name%.rb"
+ template "lib/tasks/%name%_tasks.rake"
+ if full?
+ template "lib/%name%/engine.rb"
+ end
+ end
+
+ def config
+ template "config/routes.rb" if mountable?
+ end
+
+ def test
+ template "test/test_helper.rb"
+ template "test/%name%_test.rb"
+ append_file "Rakefile", <<-EOF
+#{rakefile_test_tasks}
+
+task :default => :test
+ EOF
+ if full?
+ template "test/integration/navigation_test.rb"
+ end
+ end
+
+ def generate_test_dummy(force = false)
+ opts = (options || {}).slice(:skip_active_record, :skip_javascript, :database, :javascript)
+ opts[:force] = force
+
+ invoke Rails::Generators::AppGenerator,
+ [ File.expand_path(dummy_path, destination_root) ], opts
+ end
+
+ def test_dummy_config
+ template "rails/boot.rb", "#{dummy_path}/config/boot.rb", :force => true
+ template "rails/application.rb", "#{dummy_path}/config/application.rb", :force => true
+ if mountable?
+ template "rails/routes.rb", "#{dummy_path}/config/routes.rb", :force => true
+ end
+ end
+
+ def test_dummy_clean
+ inside dummy_path do
+ remove_file ".gitignore"
+ remove_file "db/seeds.rb"
+ remove_file "doc"
+ remove_file "Gemfile"
+ remove_file "lib/tasks"
+ remove_file "public/images/rails.png"
+ remove_file "public/index.html"
+ remove_file "public/robots.txt"
+ remove_file "README"
+ remove_file "test"
+ remove_file "vendor"
+ end
+ end
+
+ def script(force = false)
+ directory "script", :force => force do |content|
+ "#{shebang}\n" + content
+ end
+ chmod "script", 0755, :verbose => false
+ end
+ end
+
+ module Generators
+ class PluginNewGenerator < AppBase
+ add_shared_options_for "plugin"
+
+ alias_method :plugin_path, :app_path
+
+ class_option :dummy_path, :type => :string, :default => "test/dummy",
+ :desc => "Create dummy application at given path"
+
+ class_option :full, :type => :boolean, :default => false,
+ :desc => "Generate rails engine with integration tests"
+
+ class_option :mountable, :type => :boolean, :default => false,
+ :desc => "Generate mountable isolated application"
+
+ class_option :skip_gemspec, :type => :boolean, :default => false,
+ :desc => "Skip gemspec file"
+
+ def initialize(*args)
+ raise Error, "Options should be given after the plugin name. For details run: rails plugin --help" if args[0].blank?
+
+ super
+ end
+
+ public_task :create_root
+
+ def create_root_files
+ build(:readme)
+ build(:rakefile)
+ build(:gemspec) unless options[:skip_gemspec]
+ build(:license)
+ build(:gitignore) unless options[:skip_git]
+ build(:gemfile) unless options[:skip_gemfile]
+ end
+
+ def create_app_files
+ build(:app)
+ end
+
+ def create_config_files
+ build(:config)
+ end
+
+ def create_lib_files
+ build(:lib)
+ end
+
+ def create_script_files
+ build(:script)
+ end
+
+ def create_test_files
+ build(:test) unless options[:skip_test_unit]
+ end
+
+ def create_test_dummy_files
+ return if options[:skip_test_unit]
+ create_dummy_app
+ end
+
+ def finish_template
+ build(:leftovers)
+ end
+
+ public_task :apply_rails_template, :bundle_if_dev_or_edge
+
+ protected
+ def create_dummy_app(path = nil)
+ dummy_path(path) if path
+
+ say_status :vendor_app, dummy_path
+ mute do
+ build(:generate_test_dummy)
+ store_application_definition!
+ build(:test_dummy_config)
+ build(:test_dummy_clean)
+ # ensure that script/rails has proper dummy_path
+ build(:script, true)
+ end
+ end
+
+ def full?
+ options[:full] || options[:mountable]
+ end
+
+ def mountable?
+ options[:mountable]
+ end
+
+ def self.banner
+ "rails plugin new #{self.arguments.map(&:usage).join(' ')} [options]"
+ end
+
+ def name
+ @name ||= File.basename(destination_root)
+ end
+
+ def camelized
+ @camelized ||= name.gsub(/\W/, '_').squeeze('_').camelize
+ end
+
+ def valid_const?
+ if camelized =~ /^\d/
+ raise Error, "Invalid plugin name #{name}. Please give a name which does not start with numbers."
+ elsif RESERVED_NAMES.include?(name)
+ raise Error, "Invalid plugin name #{name}. Please give a name which does not match one of the reserved rails words."
+ elsif Object.const_defined?(camelized)
+ raise Error, "Invalid plugin name #{name}, constant #{camelized} is already in use. Please choose another application name."
+ end
+ end
+
+ def application_definition
+ @application_definition ||= begin
+
+ dummy_application_path = File.expand_path("#{dummy_path}/config/application.rb", destination_root)
+ unless options[:pretend] || !File.exists?(dummy_application_path)
+ contents = File.read(dummy_application_path)
+ contents[(contents.index("module Dummy"))..-1]
+ end
+ end
+ end
+ alias :store_application_definition! :application_definition
+
+ def get_builder_class
+ defined?(::PluginBuilder) ? ::PluginBuilder : Rails::PluginBuilder
+ end
+
+ def rakefile_test_tasks
+ <<-RUBY
+require 'rake/testtask'
+
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.libs << 'test'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = false
+end
+ RUBY
+ end
+
+ def dummy_path(path = nil)
+ @dummy_path = path if path
+ @dummy_path || options[:dummy_path]
+ end
+
+ def mute(&block)
+ shell.mute(&block)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
new file mode 100644
index 0000000000..3d9bfb22c7
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
@@ -0,0 +1,9 @@
+# Provide a simple gemspec so you can easily use your
+# project in your rails apps through git.
+Gem::Specification.new do |s|
+ s.name = "<%= name %>"
+ s.summary = "Insert <%= camelized %> summary."
+ s.description = "Insert <%= camelized %> description."
+ s.files = Dir["lib/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
+ s.version = "0.0.1"
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
new file mode 100644
index 0000000000..29900c93dc
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
@@ -0,0 +1,11 @@
+source "http://rubygems.org"
+
+<%= rails_gemfile_entry -%>
+
+<% if full? -%>
+<%= database_gemfile_entry -%>
+<% end -%>
+
+if RUBY_VERSION < '1.9'
+ gem "ruby-debug", ">= 0.10.3"
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE b/railties/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE
new file mode 100644
index 0000000000..d7a9109894
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright <%= Date.today.year %> YOURNAME
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/README.rdoc b/railties/lib/rails/generators/rails/plugin_new/templates/README.rdoc
new file mode 100644
index 0000000000..301d647731
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/README.rdoc
@@ -0,0 +1,3 @@
+= <%= camelized %>
+
+This project rocks and uses MIT-LICENSE. \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
new file mode 100644
index 0000000000..88f50f9f04
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
@@ -0,0 +1,18 @@
+# encoding: UTF-8
+require 'rubygems'
+begin
+ require 'bundler/setup'
+rescue LoadError
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
+end
+
+require 'rake'
+require 'rake/rdoctask'
+
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = '<%= camelized %>'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README.rdoc')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt b/railties/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt
new file mode 100644
index 0000000000..448ad7f989
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/app/controllers/%name%/application_controller.rb.tt
@@ -0,0 +1,4 @@
+module <%= camelized %>
+ class ApplicationController < ActionController::Base
+ end
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt b/railties/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt
new file mode 100644
index 0000000000..40ae9f52c2
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/app/helpers/%name%/application_helper.rb.tt
@@ -0,0 +1,4 @@
+module <%= camelized %>
+ module ApplicationHelper
+ end
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb b/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb
new file mode 100644
index 0000000000..42ddf380d8
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb
@@ -0,0 +1,3 @@
+<%= camelized %>::Engine.routes.draw do
+
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/gitignore b/railties/lib/rails/generators/rails/plugin_new/templates/gitignore
new file mode 100644
index 0000000000..1463de6dfb
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/gitignore
@@ -0,0 +1,6 @@
+.bundle/
+log/*.log
+pkg/
+test/dummy/db/*.sqlite3
+test/dummy/log/*.log
+test/dummy/tmp/ \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb
new file mode 100644
index 0000000000..2d3bdc510c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%.rb
@@ -0,0 +1,6 @@
+<% if full? -%>
+require "<%= name %>/engine"
+
+<% end -%>
+module <%= camelized %>
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb
new file mode 100644
index 0000000000..9600ee0c3f
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb
@@ -0,0 +1,7 @@
+module <%= camelized %>
+ class Engine < Rails::Engine
+<% if mountable? -%>
+ isolate_namespace <%= camelized %>
+<% end -%>
+ end
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake b/railties/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake
new file mode 100644
index 0000000000..7121f5ae23
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/tasks/%name%_tasks.rake
@@ -0,0 +1,4 @@
+# desc "Explaining what the task does"
+# task :<%= name %> do
+# # Task goes here
+# end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb
new file mode 100644
index 0000000000..8b68280a5e
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb
@@ -0,0 +1,16 @@
+require File.expand_path('../boot', __FILE__)
+
+<% unless options[:skip_active_record] -%>
+require 'rails/all'
+<% else -%>
+# require "active_record/railtie"
+require "action_controller/railtie"
+require "action_mailer/railtie"
+require "active_resource/railtie"
+require "rails/test_unit/railtie"
+<% end -%>
+
+Bundler.require
+require "<%= name %>"
+
+<%= application_definition %>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb
new file mode 100644
index 0000000000..eba0681370
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb
@@ -0,0 +1,10 @@
+require 'rubygems'
+gemfile = File.expand_path('../../../../Gemfile', __FILE__)
+
+if File.exist?(gemfile)
+ ENV['BUNDLE_GEMFILE'] = gemfile
+ require 'bundler'
+ Bundler.setup
+end
+
+$:.unshift File.expand_path('../../../../lib', __FILE__) \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb
new file mode 100644
index 0000000000..730ee31c3d
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/routes.rb
@@ -0,0 +1,4 @@
+Rails.application.routes.draw do
+
+ mount <%= camelized %>::Engine => "/<%= name %>"
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/script/rails.tt b/railties/lib/rails/generators/rails/plugin_new/templates/script/rails.tt
new file mode 100644
index 0000000000..ebd5a77dd5
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/script/rails.tt
@@ -0,0 +1,5 @@
+#!/usr/bin/env ruby
+# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
+
+ENGINE_PATH = File.expand_path('../..', __FILE__)
+load File.expand_path('../../<%= dummy_path %>/script/rails', __FILE__)
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb b/railties/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb
new file mode 100644
index 0000000000..0a8bbd4aaf
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/%name%_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class <%= camelized %>Test < ActiveSupport::TestCase
+ test "truth" do
+ assert_kind_of Module, <%= camelized %>
+ end
+end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb b/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb
new file mode 100644
index 0000000000..d06fe7cbd0
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb
@@ -0,0 +1,11 @@
+require 'test_helper'
+
+class NavigationTest < ActionDispatch::IntegrationTest
+ fixtures :all
+
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
+
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb
new file mode 100644
index 0000000000..7b61047e77
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb
@@ -0,0 +1,15 @@
+# Configure Rails Envinronment
+ENV["RAILS_ENV"] = "test"
+
+require File.expand_path("../dummy/config/environment.rb", __FILE__)
+require "rails/test_help"
+
+Rails.backtrace_cleaner.remove_silencers!
+
+<% if full? && !options[:skip_active_record] -%>
+# Run any available migration from application
+ActiveRecord::Migrator.migrate File.expand_path("../dummy/db/migrate/", __FILE__)
+<% end -%>
+
+# Load support files
+Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
diff --git a/railties/lib/rails/generators/rails/resource/resource_generator.rb b/railties/lib/rails/generators/rails/resource/resource_generator.rb
index 8a943013d3..c7345f3cfb 100644
--- a/railties/lib/rails/generators/rails/resource/resource_generator.rb
+++ b/railties/lib/rails/generators/rails/resource/resource_generator.rb
@@ -16,9 +16,9 @@ module Rails
def add_resource_route
return if options[:actions].present?
- route_config = class_path.collect{|namespace| "namespace :#{namespace} do " }.join(" ")
+ route_config = regular_class_path.collect{|namespace| "namespace :#{namespace} do " }.join(" ")
route_config << "resources :#{file_name.pluralize}"
- route_config << " end" * class_path.size
+ route_config << " end" * regular_class_path.size
route route_config
end
end
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
index b21340f755..b5317a055b 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
@@ -1,3 +1,4 @@
+<% module_namespacing do -%>
class <%= controller_class_name %>Controller < ApplicationController
# GET <%= route_url %>
# GET <%= route_url %>.xml
@@ -81,3 +82,4 @@ class <%= controller_class_name %>Controller < ApplicationController
end
end
end
+<% end -%>
diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb
index 829f4b200a..d6ccfc496a 100644
--- a/railties/lib/rails/generators/resource_helpers.rb
+++ b/railties/lib/rails/generators/resource_helpers.rb
@@ -17,7 +17,7 @@ module Rails
def initialize(*args) #:nodoc:
super
- if name == name.pluralize && !options[:force_plural]
+ if name == name.pluralize && name.singularize != name.pluralize && !options[:force_plural]
unless ResourceHelpers.skip_warn
say "Plural version of the model detected, using singularized version. Override with --force-plural."
ResourceHelpers.skip_warn = true
@@ -34,7 +34,7 @@ module Rails
attr_reader :controller_name
def controller_class_path
- @class_path
+ class_path
end
def controller_file_name
@@ -46,7 +46,7 @@ module Rails
end
def controller_class_name
- @controller_class_name ||= (controller_class_path + [controller_file_name]).map!{ |m| m.camelize }.join('::')
+ (controller_class_path + [controller_file_name]).map!{ |m| m.camelize }.join('::')
end
def controller_i18n_scope
diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
index f23e495450..964d59d84c 100644
--- a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
@@ -1,5 +1,6 @@
require 'test_helper'
+<% module_namespacing do -%>
class <%= controller_class_name %>ControllerTest < ActionController::TestCase
setup do
@<%= singular_table_name %> = <%= table_name %>(:one)
@@ -47,3 +48,4 @@ class <%= controller_class_name %>ControllerTest < ActionController::TestCase
assert_redirected_to <%= index_helper %>_path
end
end
+<% end -%>
diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb
index 6cbd1f21c0..d05e031f56 100644
--- a/railties/lib/rails/info.rb
+++ b/railties/lib/rails/info.rb
@@ -1,5 +1,4 @@
require "cgi"
-require "active_support/core_ext/cgi"
module Rails
module Info
diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb
index 0213d46254..b076881c21 100644
--- a/railties/lib/rails/version.rb
+++ b/railties/lib/rails/version.rb
@@ -3,8 +3,8 @@ module Rails
MAJOR = 3
MINOR = 1
TINY = 0
- BUILD = "beta"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb
index 551e966c85..3a3e28179a 100644
--- a/railties/test/application/generators_test.rb
+++ b/railties/test/application/generators_test.rb
@@ -25,6 +25,18 @@ module ApplicationTests
yield app_const.config
end
+ test "allow running plugin new generator inside Rails app directory" do
+ FileUtils.cd rails_root
+ `./script/rails plugin new vendor/plugins/bukkits`
+ assert File.exist?(File.join(rails_root, "vendor/plugins/bukkits/test/dummy/config/application.rb"))
+ end
+
+ test "don't allow running plugin_new generator as a generator" do
+ FileUtils.cd rails_root
+ output = `./script/rails g plugin_new vendor/plugins/bukkits`
+ assert_match /This generator should not be used directly as a generator. You should use `rails plugin new` command instead/, output
+ end
+
test "generators default values" do
with_bare_config do |c|
assert_equal(true, c.generators.colorize_logging)
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index 8e527236ea..719550f9d9 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -38,5 +38,14 @@ module ApplicationTests
assert_match "Code LOC: 5 Test LOC: 0 Code to Test Ratio: 1:0.0",
Dir.chdir(app_path){ `rake stats` }
end
+
+ def test_rake_routes_output_strips_anchors_from_http_verbs
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/cart', :to => 'cart#show'
+ end
+ RUBY
+ assert_match 'cart GET /cart(.:format)', Dir.chdir(app_path){ `rake routes` }
+ end
end
end
diff --git a/railties/test/fixtures/lib/empty_builder.rb b/railties/test/fixtures/lib/app_builders/empty_builder.rb
index babd9c2461..babd9c2461 100644
--- a/railties/test/fixtures/lib/empty_builder.rb
+++ b/railties/test/fixtures/lib/app_builders/empty_builder.rb
diff --git a/railties/test/fixtures/lib/app_builders/simple_builder.rb b/railties/test/fixtures/lib/app_builders/simple_builder.rb
new file mode 100644
index 0000000000..993d3a2aa2
--- /dev/null
+++ b/railties/test/fixtures/lib/app_builders/simple_builder.rb
@@ -0,0 +1,7 @@
+class AppBuilder
+ def gitignore
+ create_file ".gitignore", <<-R.strip
+foobar
+ R
+ end
+end
diff --git a/railties/test/fixtures/lib/app_builders/tweak_builder.rb b/railties/test/fixtures/lib/app_builders/tweak_builder.rb
new file mode 100644
index 0000000000..cb50be01cb
--- /dev/null
+++ b/railties/test/fixtures/lib/app_builders/tweak_builder.rb
@@ -0,0 +1,7 @@
+class AppBuilder < Rails::AppBuilder
+ def gitignore
+ create_file ".gitignore", <<-R.strip
+foobar
+ R
+ end
+end
diff --git a/railties/test/fixtures/lib/create_test_dummy_template.rb b/railties/test/fixtures/lib/create_test_dummy_template.rb
new file mode 100644
index 0000000000..e4378bbd1a
--- /dev/null
+++ b/railties/test/fixtures/lib/create_test_dummy_template.rb
@@ -0,0 +1 @@
+create_dummy_app("spec/dummy")
diff --git a/railties/test/fixtures/lib/plugin_builders/empty_builder.rb b/railties/test/fixtures/lib/plugin_builders/empty_builder.rb
new file mode 100644
index 0000000000..5c5607621c
--- /dev/null
+++ b/railties/test/fixtures/lib/plugin_builders/empty_builder.rb
@@ -0,0 +1,2 @@
+class PluginBuilder
+end
diff --git a/railties/test/fixtures/lib/plugin_builders/simple_builder.rb b/railties/test/fixtures/lib/plugin_builders/simple_builder.rb
new file mode 100644
index 0000000000..08f6c5535d
--- /dev/null
+++ b/railties/test/fixtures/lib/plugin_builders/simple_builder.rb
@@ -0,0 +1,7 @@
+class PluginBuilder
+ def gitignore
+ create_file ".gitignore", <<-R.strip
+foobar
+ R
+ end
+end
diff --git a/railties/test/fixtures/lib/plugin_builders/spec_builder.rb b/railties/test/fixtures/lib/plugin_builders/spec_builder.rb
new file mode 100644
index 0000000000..aa18c7ddaa
--- /dev/null
+++ b/railties/test/fixtures/lib/plugin_builders/spec_builder.rb
@@ -0,0 +1,19 @@
+class PluginBuilder < Rails::PluginBuilder
+ def test
+ create_file "spec/spec_helper.rb"
+ append_file "Rakefile", <<-EOF
+# spec tasks in rakefile
+
+task :default => :spec
+ EOF
+ end
+
+ def generate_test_dummy
+ dummy_path("spec/dummy")
+ super
+ end
+
+ def skip_test_unit?
+ true
+ end
+end
diff --git a/railties/test/fixtures/lib/plugin_builders/tweak_builder.rb b/railties/test/fixtures/lib/plugin_builders/tweak_builder.rb
new file mode 100644
index 0000000000..1e801409a4
--- /dev/null
+++ b/railties/test/fixtures/lib/plugin_builders/tweak_builder.rb
@@ -0,0 +1,7 @@
+class PluginBuilder < Rails::PluginBuilder
+ def gitignore
+ create_file ".gitignore", <<-R.strip
+foobar
+ R
+ end
+end
diff --git a/railties/test/fixtures/lib/simple_builder.rb b/railties/test/fixtures/lib/simple_builder.rb
deleted file mode 100644
index 47dcdc0d96..0000000000
--- a/railties/test/fixtures/lib/simple_builder.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-class AppBuilder
- def configru
- create_file "config.ru", <<-R.strip
-run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }
- R
- end
-end \ No newline at end of file
diff --git a/railties/test/fixtures/lib/tweak_builder.rb b/railties/test/fixtures/lib/tweak_builder.rb
deleted file mode 100644
index eed20ecc9b..0000000000
--- a/railties/test/fixtures/lib/tweak_builder.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-class AppBuilder < Rails::AppBuilder
- def configru
- create_file "config.ru", <<-R.strip
-run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }
- R
- end
-end \ No newline at end of file
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index c7339cb8d2..7faa674a81 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -1,6 +1,7 @@
require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/app/app_generator'
+require 'generators/shared_generator_tests.rb'
DEFAULT_APP_FILES = %w(
.gitignore
@@ -40,36 +41,10 @@ DEFAULT_APP_FILES = %w(
class AppGeneratorTest < Rails::Generators::TestCase
include GeneratorsTestHelper
arguments [destination_root]
+ include SharedGeneratorTests
- def setup
- Rails.application = TestApp::Application
- super
- Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
- @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
-
- Kernel::silence_warnings do
- Thor::Base.shell.send(:attr_accessor, :always_force)
- @shell = Thor::Base.shell.new
- @shell.send(:always_force=, true)
- end
- end
-
- def teardown
- super
- Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
- Rails.application = TestApp::Application.instance
- end
-
- def test_application_skeleton_is_created
- run_generator
-
- DEFAULT_APP_FILES.each{ |path| assert_file path }
- end
-
- def test_application_generate_pretend
- run_generator ["testapp", "--pretend"]
-
- DEFAULT_APP_FILES.each{ |path| assert_no_file path }
+ def default_files
+ ::DEFAULT_APP_FILES
end
def test_application_controller_and_layout_files
@@ -78,36 +53,11 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_no_file "public/stylesheets/application.css"
end
- def test_options_before_application_name_raises_an_error
- content = capture(:stderr){ run_generator(["--skip-active-record", destination_root]) }
- assert_equal "Options should be given after the application name. For details run: rails --help\n", content
- end
-
- def test_name_collision_raises_an_error
- reserved_words = %w[application destroy plugin runner test]
- reserved_words.each do |reserved|
- content = capture(:stderr){ run_generator [File.join(destination_root, reserved)] }
- assert_equal "Invalid application name #{reserved}. Please give a name which does not match one of the reserved rails words.\n", content
- end
- end
-
- def test_invalid_database_option_raises_an_error
- content = capture(:stderr){ run_generator([destination_root, "-d", "unknown"]) }
- assert_match /Invalid value for \-\-database option/, content
- end
-
def test_invalid_application_name_raises_an_error
content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] }
assert_equal "Invalid application name 43-things. Please give a name which does not start with numbers.\n", content
end
- def test_application_name_raises_an_error_if_name_already_used_constant
- %w{ String Hash Class Module Set Symbol }.each do |ruby_class|
- content = capture(:stderr){ run_generator [File.join(destination_root, ruby_class)] }
- assert_equal "Invalid application name #{ruby_class}, constant #{ruby_class} is already in use. Please choose another application name.\n", content
- end
- end
-
def test_invalid_application_name_is_fixed
run_generator [File.join(destination_root, "things-43")]
assert_file "things-43/config/environment.rb", /Things43::Application\.initialize!/
@@ -133,11 +83,11 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "myapp_moved/config/environment.rb", /Myapp::Application\.initialize!/
assert_file "myapp_moved/config/initializers/session_store.rb", /_myapp_session/
end
-
+
def test_rails_update_generates_correct_session_key
app_root = File.join(destination_root, 'myapp')
run_generator [app_root]
-
+
Rails.application.config.root = app_root
Rails.application.class.stubs(:name).returns("Myapp")
Rails.application.stubs(:is_a?).returns(Rails::Application)
@@ -187,12 +137,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "public/javascripts/rails.js"
assert_file "test"
end
-
- 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\(\)/
@@ -200,7 +145,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_no_file "public/javascripts/prototype.js"
assert_no_file "public/javascripts/rails.js"
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\)/
@@ -208,7 +153,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
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\)/
@@ -217,36 +162,11 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "public/javascripts/rails.js", /jQuery/
end
- def test_shebang_is_added_to_rails_file
- run_generator [destination_root, "--ruby", "foo/bar/baz"]
- assert_file "script/rails", /#!foo\/bar\/baz/
- end
-
- def test_shebang_when_is_the_same_as_default_use_env
- run_generator [destination_root, "--ruby", Thor::Util.ruby_command]
- assert_file "script/rails", /#!\/usr\/bin\/env/
- end
-
def test_template_from_dir_pwd
FileUtils.cd(Rails.root)
assert_match /It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"])
end
- def test_template_raises_an_error_with_invalid_path
- content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) }
- assert_match /The template \[.*\] could not be loaded/, content
- assert_match /non\/existant\/path/, content
- end
-
- def test_template_is_executed_when_supplied
- path = "http://gist.github.com/103208.txt"
- template = %{ say "It works!" }
- template.instance_eval "def read; self; end" # Make the string respond to read
-
- generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
- assert_match /It works!/, silence(:stdout){ generator.invoke_all }
- end
-
def test_usage_read_from_file
File.expects(:read).returns("USAGE FROM FILE")
assert_equal "USAGE FROM FILE", Rails::Generators::AppGenerator.desc
@@ -266,17 +186,11 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file 'lib/test_file.rb', 'heres test data'
end
- def test_dev_option
- generator([destination_root], :dev => true).expects(:run).with("#{@bundle_command} install")
- silence(:stdout){ generator.invoke_all }
- rails_path = File.expand_path('../../..', Rails.root)
- assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:path\s+=>\s+["']#{Regexp.escape(rails_path)}["']$/
- end
-
- def test_edge_option
- generator([destination_root], :edge => true).expects(:run).with("#{@bundle_command} install")
- silence(:stdout){ generator.invoke_all }
- assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("git://github.com/rails/rails.git")}["']$/
+ def test_test_unit_is_removed_from_frameworks_if_skip_test_unit_is_given
+ run_generator [destination_root, "--skip-test-unit"]
+ assert_file "config/application.rb" do |file|
+ assert_match /config.generators.test_framework = false/, file
+ end
end
protected
@@ -292,62 +206,21 @@ class CustomAppGeneratorTest < Rails::Generators::TestCase
tests Rails::Generators::AppGenerator
arguments [destination_root]
+ include SharedCustomGeneratorTests
- def setup
- Rails.application = TestApp::Application
- super
- Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
- @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
- end
-
- def teardown
- super
- Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
- Object.class_eval { remove_const :AppBuilder if const_defined?(:AppBuilder) }
- Rails.application = TestApp::Application.instance
- end
-
- def test_builder_option_with_empty_app_builder
- FileUtils.cd(Rails.root)
- run_generator([destination_root, "-b", "#{Rails.root}/lib/empty_builder.rb"])
- DEFAULT_APP_FILES.each{ |path| assert_no_file path }
- end
-
- def test_builder_option_with_simple_app_builder
- FileUtils.cd(Rails.root)
- run_generator([destination_root, "-b", "#{Rails.root}/lib/simple_builder.rb"])
- (DEFAULT_APP_FILES - ['config.ru']).each{ |path| assert_no_file path }
- assert_file "config.ru", %[run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }]
- end
-
- def test_builder_option_with_relative_path
- here = File.expand_path(File.dirname(__FILE__))
- FileUtils.cd(here)
- run_generator([destination_root, "-b", "../fixtures/lib/simple_builder.rb"])
- (DEFAULT_APP_FILES - ['config.ru']).each{ |path| assert_no_file path }
- assert_file "config.ru", %[run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }]
+protected
+ def default_files
+ ::DEFAULT_APP_FILES
end
- def test_builder_option_with_tweak_app_builder
- FileUtils.cd(Rails.root)
- run_generator([destination_root, "-b", "#{Rails.root}/lib/tweak_builder.rb"])
- DEFAULT_APP_FILES.each{ |path| assert_file path }
- assert_file "config.ru", %[run proc { |env| [200, { "Content-Type" => "text/html" }, ["Hello World"]] }]
+ def builders_dir
+ "app_builders"
end
- def test_builder_option_with_http
- path = "http://gist.github.com/103208.txt"
- template = "class AppBuilder; end"
- template.instance_eval "def read; self; end" # Make the string respond to read
-
- generator([destination_root], :builder => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
- capture(:stdout) { generator.invoke_all }
-
- DEFAULT_APP_FILES.each{ |path| assert_no_file path }
+ def builder_class
+ :AppBuilder
end
-protected
-
def action(*args, &block)
silence(:stdout){ generator.send(*args, &block) }
end
diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb
index d1190fd17d..d61a02d32f 100644
--- a/railties/test/generators/namespaced_generators_test.rb
+++ b/railties/test/generators/namespaced_generators_test.rb
@@ -3,6 +3,7 @@ require 'rails/generators/rails/controller/controller_generator'
require 'rails/generators/rails/model/model_generator'
require 'rails/generators/rails/observer/observer_generator'
require 'rails/generators/mailer/mailer_generator'
+require 'rails/generators/rails/scaffold/scaffold_generator'
class NamespacedGeneratorTestCase < Rails::Generators::TestCase
def setup
@@ -202,3 +203,155 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase
assert_file "app/views/test_app/notifier"
end
end
+
+class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
+ include GeneratorsTestHelper
+ arguments %w(product_line title:string price:integer)
+ tests Rails::Generators::ScaffoldGenerator
+
+ setup :copy_routes
+
+ def test_scaffold_on_invoke
+ run_generator
+
+ # Model
+ assert_file "app/models/test_app/product_line.rb", /module TestApp\n class ProductLine < ActiveRecord::Base/
+ assert_file "test/unit/test_app/product_line_test.rb", /module TestApp\n class ProductLineTest < ActiveSupport::TestCase/
+ assert_file "test/fixtures/test_app/product_lines.yml"
+ assert_migration "db/migrate/create_test_app_product_lines.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_match(/resources :product_lines$/, route)
+ end
+
+ # Controller
+ assert_file "app/controllers/test_app/product_lines_controller.rb" do |content|
+ assert_match(/module TestApp\n class ProductLinesController < ApplicationController/, content)
+ end
+
+ assert_file "test/functional/test_app/product_lines_controller_test.rb",
+ /module TestApp\n class ProductLinesControllerTest < ActionController::TestCase/
+
+ # Views
+ %w(
+ index
+ edit
+ new
+ show
+ _form
+ ).each { |view| assert_file "app/views/test_app/product_lines/#{view}.html.erb" }
+ assert_no_file "app/views/layouts/test_app/product_lines.html.erb"
+
+ # Helpers
+ assert_file "app/helpers/test_app/product_lines_helper.rb"
+ assert_file "test/unit/helpers/test_app/product_lines_helper_test.rb"
+
+ # Stylesheets
+ assert_file "public/stylesheets/scaffold.css"
+ end
+
+ def test_scaffold_on_revoke
+ run_generator
+ run_generator ["product_line"], :behavior => :revoke
+
+ # Model
+ assert_no_file "app/models/test_app/product_line.rb"
+ assert_no_file "test/unit/test_app/product_line_test.rb"
+ assert_no_file "test/fixtures/test_app/product_lines.yml"
+ assert_no_migration "db/migrate/create_test_app_product_lines.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_no_match(/resources :product_lines$/, route)
+ end
+
+ # Controller
+ assert_no_file "app/controllers/test_app/product_lines_controller.rb"
+ assert_no_file "test/functional/test_app/product_lines_controller_test.rb"
+
+ # Views
+ assert_no_file "app/views/test_app/product_lines"
+ assert_no_file "app/views/test_app/layouts/product_lines.html.erb"
+
+ # Helpers
+ assert_no_file "app/helpers/test_app/product_lines_helper.rb"
+ assert_no_file "test/unit/helpers/test_app/product_lines_helper_test.rb"
+
+ # Stylesheets (should not be removed)
+ assert_file "public/stylesheets/scaffold.css"
+ end
+
+ def test_scaffold_with_namespace_on_invoke
+ run_generator [ "admin/role", "name:string", "description:string" ]
+
+ # Model
+ assert_file "app/models/test_app/admin.rb", /module TestApp\n module Admin/
+ assert_file "app/models/test_app/admin/role.rb", /module TestApp\n class Admin::Role < ActiveRecord::Base/
+ assert_file "test/unit/test_app/admin/role_test.rb", /module TestApp\n class Admin::RoleTest < ActiveSupport::TestCase/
+ assert_file "test/fixtures/test_app/admin/roles.yml"
+ assert_migration "db/migrate/create_test_app_admin_roles.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_match(/namespace :admin do resources :roles end$/, route)
+ end
+
+ # Controller
+ assert_file "app/controllers/test_app/admin/roles_controller.rb" do |content|
+ assert_match(/module TestApp\n class Admin::RolesController < ApplicationController/, content)
+ end
+
+ assert_file "test/functional/test_app/admin/roles_controller_test.rb",
+ /module TestApp\n class Admin::RolesControllerTest < ActionController::TestCase/
+
+ # Views
+ %w(
+ index
+ edit
+ new
+ show
+ _form
+ ).each { |view| assert_file "app/views/test_app/admin/roles/#{view}.html.erb" }
+ assert_no_file "app/views/layouts/admin/roles.html.erb"
+
+ # Helpers
+ assert_file "app/helpers/test_app/admin/roles_helper.rb"
+ assert_file "test/unit/helpers/test_app/admin/roles_helper_test.rb"
+
+ # Stylesheets
+ assert_file "public/stylesheets/scaffold.css"
+ end
+
+ def test_scaffold_with_namespace_on_revoke
+ run_generator [ "admin/role", "name:string", "description:string" ]
+ run_generator [ "admin/role" ], :behavior => :revoke
+
+ # Model
+ assert_file "app/models/test_app/admin.rb" # ( should not be remove )
+ assert_no_file "app/models/test_app/admin/role.rb"
+ assert_no_file "test/unit/test_app/admin/role_test.rb"
+ assert_no_file "test/fixtures/test_app/admin/roles.yml"
+ assert_no_migration "db/migrate/create_test_app_admin_roles.rb"
+
+ # Route
+ assert_file "config/routes.rb" do |route|
+ assert_no_match(/namespace :admin do resources :roles end$/, route)
+ end
+
+ # Controller
+ assert_no_file "app/controllers/test_app/admin/roles_controller.rb"
+ assert_no_file "test/functional/test_app/admin/roles_controller_test.rb"
+
+ # Views
+ assert_no_file "app/views/test_app/admin/roles"
+ assert_no_file "app/views/layouts/test_app/admin/roles.html.erb"
+
+ # Helpers
+ assert_no_file "app/helpers/test_app/admin/roles_helper.rb"
+ assert_no_file "test/unit/helpers/test_app/admin/roles_helper_test.rb"
+
+ # Stylesheets (should not be removed)
+ assert_file "public/stylesheets/scaffold.css"
+ end
+end
diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb
index c1f646f7c1..e6686a6af4 100644
--- a/railties/test/generators/plugin_generator_test.rb
+++ b/railties/test/generators/plugin_generator_test.rb
@@ -6,7 +6,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
arguments %w(plugin_fu)
def test_plugin_skeleton_is_created
- run_generator
+ silence(:stderr) { run_generator }
year = Date.today.year
%w(
@@ -36,30 +36,36 @@ class PluginGeneratorTest < Rails::Generators::TestCase
end
def test_invokes_default_test_framework
- run_generator
+ silence(:stderr) { run_generator }
assert_file "vendor/plugins/plugin_fu/test/plugin_fu_test.rb", /class PluginFuTest < ActiveSupport::TestCase/
assert_file "vendor/plugins/plugin_fu/test/test_helper.rb"
end
def test_logs_if_the_test_framework_cannot_be_found
- content = run_generator ["plugin_fu", "--test-framework=rspec"]
+ content = nil
+ silence(:stderr) { content = run_generator ["plugin_fu", "--test-framework=rspec"] }
assert_match /rspec \[not found\]/, content
end
def test_creates_tasks_if_required
- run_generator ["plugin_fu", "--tasks"]
+ silence(:stderr) { run_generator ["plugin_fu", "--tasks"] }
assert_file "vendor/plugins/plugin_fu/lib/tasks/plugin_fu_tasks.rake"
end
def test_creates_generator_if_required
- run_generator ["plugin_fu", "--generator"]
+ silence(:stderr) { run_generator ["plugin_fu", "--generator"] }
assert_file "vendor/plugins/plugin_fu/lib/generators/templates"
assert_file "vendor/plugins/plugin_fu/lib/generators/plugin_fu_generator.rb",
/class PluginFuGenerator < Rails::Generators::NamedBase/
end
def test_plugin_generator_on_revoke
- run_generator
+ silence(:stderr) { run_generator }
run_generator ["plugin_fu"], :behavior => :revoke
end
+
+ def test_deprecation
+ output = capture(:stderr) { run_generator }
+ assert_match /Plugin generator is deprecated, please use 'rails plugin new' command to generate plugin structure./, output
+ end
end
diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb
new file mode 100644
index 0000000000..2105585272
--- /dev/null
+++ b/railties/test/generators/plugin_new_generator_test.rb
@@ -0,0 +1,196 @@
+require 'abstract_unit'
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/plugin_new/plugin_new_generator'
+require 'generators/shared_generator_tests.rb'
+
+DEFAULT_PLUGIN_FILES = %w(
+ .gitignore
+ Gemfile
+ Rakefile
+ bukkits.gemspec
+ MIT-LICENSE
+ lib
+ lib/bukkits.rb
+ lib/tasks/bukkits_tasks.rake
+ script/rails
+ test/bukkits_test.rb
+ test/test_helper.rb
+ test/dummy
+)
+
+class PluginNewGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ destination File.join(Rails.root, "tmp/bukkits")
+ arguments [destination_root]
+ include SharedGeneratorTests
+
+ def default_files
+ ::DEFAULT_PLUGIN_FILES
+ end
+
+ def test_invalid_plugin_name_raises_an_error
+ content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] }
+ assert_equal "Invalid plugin name 43-things. Please give a name which does not start with numbers.\n", content
+ end
+
+ def test_invalid_plugin_name_is_fixed
+ run_generator [File.join(destination_root, "things-43")]
+ assert_file "things-43/lib/things-43.rb", /module Things43/
+ end
+
+ def test_generating_test_files
+ run_generator
+ assert_file "test/test_helper.rb"
+ assert_file "test/bukkits_test.rb", /assert_kind_of Module, Bukkits/
+ end
+
+ def test_generating_test_files_in_full_mode
+ run_generator [destination_root, "--full"]
+ assert_directory "test/integration/"
+
+ assert_file "test/integration/navigation_test.rb", /ActionDispatch::IntegrationTest/
+ end
+
+ def test_ensure_that_plugin_options_are_not_passed_to_app_generator
+ FileUtils.cd(Rails.root)
+ assert_no_match /It works from file!.*It works_from_file/, run_generator([destination_root, "-m", "lib/template.rb"])
+ end
+
+ def test_ensure_that_test_dummy_can_be_generated_from_a_template
+ FileUtils.cd(Rails.root)
+ run_generator([destination_root, "-m", "lib/create_test_dummy_template.rb", "--skip-test-unit"])
+ assert_file "spec/dummy"
+ assert_no_file "test"
+ end
+
+ def test_database_entry_is_assed_by_default_in_full_mode
+ run_generator([destination_root, "--full"])
+ assert_file "test/dummy/config/database.yml", /sqlite/
+ assert_file "Gemfile", /^gem\s+["']sqlite3-ruby["'],\s+:require\s+=>\s+["']sqlite3["']$/
+ end
+
+ def test_config_another_database
+ run_generator([destination_root, "-d", "mysql", "--full"])
+ assert_file "test/dummy/config/database.yml", /mysql/
+ assert_file "Gemfile", /^gem\s+["']mysql2["']$/
+ end
+
+ def test_active_record_is_removed_from_frameworks_if_skip_active_record_is_given
+ run_generator [destination_root, "--skip-active-record"]
+ assert_file "test/dummy/config/application.rb", /#\s+require\s+["']active_record\/railtie["']/
+ end
+
+ def test_ensure_that_skip_active_record_option_is_passed_to_app_generator
+ run_generator [destination_root, "--skip_active_record"]
+ assert_no_file "test/dummy/config/database.yml"
+ assert_no_match /ActiveRecord/, File.read(File.join(destination_root, "test/test_helper.rb"))
+ end
+
+ def test_ensure_that_database_option_is_passed_to_app_generator
+ run_generator [destination_root, "--database", "postgresql"]
+ assert_file "test/dummy/config/database.yml", /postgres/
+ end
+
+ def test_ensure_that_javascript_option_is_passed_to_app_generator
+ run_generator [destination_root, "--javascript", "jquery"]
+ assert_file "test/dummy/public/javascripts/jquery.js"
+ end
+
+ def test_ensure_that_skip_javascript_option_is_passed_to_app_generator
+ run_generator [destination_root, "--skip_javascript"]
+ assert_no_file "test/dummy/public/javascripts/prototype.js"
+ end
+
+ def test_template_from_dir_pwd
+ FileUtils.cd(Rails.root)
+ assert_match /It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"])
+ end
+
+ def test_ensure_that_tests_works
+ run_generator
+ FileUtils.cd destination_root
+ `bundle install`
+ assert_match /1 tests, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test`
+ end
+
+ def test_ensure_that_tests_works_in_full_mode
+ run_generator [destination_root, "--full"]
+ FileUtils.cd destination_root
+ `bundle install`
+ assert_match /2 tests, 2 assertions, 0 failures, 0 errors/, `bundle exec rake test`
+ end
+
+ def test_creating_engine_in_full_mode
+ run_generator [destination_root, "--full"]
+ assert_file "lib/bukkits/engine.rb", /module Bukkits\n class Engine < Rails::Engine\n end\nend/
+ assert_file "lib/bukkits.rb", /require "bukkits\/engine"/
+ end
+
+ def test_being_quiet_while_creating_dummy_application
+ assert_no_match /create\s+config\/application.rb/, run_generator
+ end
+
+ def test_create_mountable_application_with_mountable_option
+ run_generator [destination_root, "--mountable"]
+ assert_file "config/routes.rb", /Bukkits::Engine.routes.draw do/
+ assert_file "lib/bukkits/engine.rb", /isolate_namespace Bukkits/
+ assert_file "test/dummy/config/routes.rb", /mount Bukkits::Engine => "\/bukkits"/
+ assert_file "app/controllers/bukkits/application_controller.rb", /module Bukkits\n class ApplicationController < ActionController::Base/
+ assert_file "app/helpers/bukkits/application_helper.rb", /module Bukkits\n module ApplicationHelper/
+ end
+
+ def test_passing_dummy_path_as_a_parameter
+ run_generator [destination_root, "--dummy_path", "spec/dummy"]
+ assert_file "spec/dummy"
+ assert_file "spec/dummy/config/application.rb"
+ assert_no_file "test/dummy"
+ end
+
+ def test_skipping_gemspec
+ run_generator [destination_root, "--skip-gemspec"]
+ assert_no_file "bukkits.gemspec"
+ end
+
+protected
+
+ def action(*args, &block)
+ silence(:stdout){ generator.send(*args, &block) }
+ end
+
+end
+
+class CustomPluginGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ tests Rails::Generators::PluginNewGenerator
+
+ destination File.join(Rails.root, "tmp/bukkits")
+ arguments [destination_root]
+ include SharedCustomGeneratorTests
+
+ def test_overriding_test_framework
+ FileUtils.cd(destination_root)
+ run_generator([destination_root, "-b", "#{Rails.root}/lib/plugin_builders/spec_builder.rb"])
+ assert_file 'spec/spec_helper.rb'
+ assert_file 'spec/dummy'
+ assert_file 'Rakefile', /task :default => :spec/
+ assert_file 'Rakefile', /# spec tasks in rakefile/
+ assert_file 'script/rails', %r{spec/dummy}
+ end
+
+protected
+ def default_files
+ ::DEFAULT_PLUGIN_FILES
+ end
+
+ def builder_class
+ :PluginBuilder
+ end
+
+ def builders_dir
+ "plugin_builders"
+ end
+
+ def action(*args, &block)
+ silence(:stdout){ generator.send(*args, &block) }
+ end
+end
diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb
index 55d5bd6f83..71b3619351 100644
--- a/railties/test/generators/resource_generator_test.rb
+++ b/railties/test/generators/resource_generator_test.rb
@@ -73,6 +73,11 @@ class ResourceGeneratorTest < Rails::Generators::TestCase
assert_no_match /Plural version of the model detected/, content
end
+ def test_mass_nouns_do_not_throw_warnings
+ content = run_generator ["sheep".freeze]
+ assert_no_match /Plural version of the model detected/, content
+ end
+
def test_route_is_removed_on_revoke
run_generator
run_generator ["account"], :behavior => :revoke
diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb
new file mode 100644
index 0000000000..d117656fbd
--- /dev/null
+++ b/railties/test/generators/shared_generator_tests.rb
@@ -0,0 +1,187 @@
+module SharedGeneratorTests
+ def setup
+ Rails.application = TestApp::Application
+ super
+ Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
+ @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
+
+ Kernel::silence_warnings do
+ Thor::Base.shell.send(:attr_accessor, :always_force)
+ @shell = Thor::Base.shell.new
+ @shell.send(:always_force=, true)
+ end
+ end
+
+ def teardown
+ super
+ Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
+ Rails.application = TestApp::Application.instance
+ end
+
+ def test_skeleton_is_created
+ run_generator
+
+ default_files.each{ |path| assert_file path }
+ end
+
+ def test_plugin_new_generate_pretend
+ run_generator ["testapp", "--pretend"]
+
+ default_files.each{ |path| assert_no_file path }
+ end
+
+ def test_invalid_database_option_raises_an_error
+ content = capture(:stderr){ run_generator([destination_root, "-d", "unknown"]) }
+ assert_match /Invalid value for \-\-database option/, content
+ end
+
+ def test_test_unit_is_skipped_if_required
+ run_generator [destination_root, "--skip-test-unit"]
+ assert_no_file "test"
+ end
+
+ def test_options_before_application_name_raises_an_error
+ content = capture(:stderr){ run_generator(["--pretend", destination_root]) }
+ assert_match /Options should be given after the \w+ name. For details run: rails( plugin)? --help\n/, content
+ end
+
+ def test_name_collision_raises_an_error
+ reserved_words = %w[application destroy plugin runner test]
+ reserved_words.each do |reserved|
+ content = capture(:stderr){ run_generator [File.join(destination_root, reserved)] }
+ assert_match /Invalid \w+ name #{reserved}. Please give a name which does not match one of the reserved rails words.\n/, content
+ end
+ end
+
+ def test_name_raises_an_error_if_name_already_used_constant
+ %w{ String Hash Class Module Set Symbol }.each do |ruby_class|
+ content = capture(:stderr){ run_generator [File.join(destination_root, ruby_class)] }
+ assert_match /Invalid \w+ name #{ruby_class}, constant #{ruby_class} is already in use. Please choose another \w+ name.\n/, content
+ end
+ end
+
+ def test_shebang_is_added_to_rails_file
+ run_generator [destination_root, "--ruby", "foo/bar/baz"]
+ assert_file "script/rails", /#!foo\/bar\/baz/
+ end
+
+ def test_shebang_when_is_the_same_as_default_use_env
+ run_generator [destination_root, "--ruby", Thor::Util.ruby_command]
+ assert_file "script/rails", /#!\/usr\/bin\/env/
+ end
+
+ def test_template_raises_an_error_with_invalid_path
+ content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) }
+ assert_match /The template \[.*\] could not be loaded/, content
+ assert_match /non\/existant\/path/, content
+ end
+
+ def test_template_is_executed_when_supplied
+ path = "http://gist.github.com/103208.txt"
+ template = %{ say "It works!" }
+ template.instance_eval "def read; self; end" # Make the string respond to read
+
+ generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
+ assert_match /It works!/, silence(:stdout){ generator.invoke_all }
+ end
+
+ def test_dev_option
+ generator([destination_root], :dev => true).expects(:run).with("#{@bundle_command} install")
+ silence(:stdout){ generator.invoke_all }
+ rails_path = File.expand_path('../../..', Rails.root)
+ assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:path\s+=>\s+["']#{Regexp.escape(rails_path)}["']$/
+ end
+
+ def test_edge_option
+ generator([destination_root], :edge => true).expects(:run).with("#{@bundle_command} install")
+ silence(:stdout){ generator.invoke_all }
+ assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("git://github.com/rails/rails.git")}["']$}
+ end
+
+ def test_template_raises_an_error_with_invalid_path
+ content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) }
+ assert_match /The template \[.*\] could not be loaded/, content
+ assert_match /non\/existant\/path/, content
+ end
+
+ def test_template_is_executed_when_supplied
+ path = "http://gist.github.com/103208.txt"
+ template = %{ say "It works!" }
+ template.instance_eval "def read; self; end" # Make the string respond to read
+
+ generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
+ assert_match /It works!/, silence(:stdout){ generator.invoke_all }
+ end
+
+ def test_dev_option
+ generator([destination_root], :dev => true).expects(:run).with("#{@bundle_command} install")
+ silence(:stdout){ generator.invoke_all }
+ rails_path = File.expand_path('../../..', Rails.root)
+ assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:path\s+=>\s+["']#{Regexp.escape(rails_path)}["']$/
+ end
+
+ def test_edge_option
+ generator([destination_root], :edge => true).expects(:run).with("#{@bundle_command} install")
+ silence(:stdout){ generator.invoke_all }
+ assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("git://github.com/rails/rails.git")}["']$}
+ end
+end
+
+module SharedCustomGeneratorTests
+ def setup
+ Rails.application = TestApp::Application
+ super
+ Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
+ @bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
+ end
+
+ def teardown
+ super
+ Rails::Generators::AppGenerator.instance_variable_set('@desc', nil)
+ Object.class_eval do
+ remove_const :AppBuilder if const_defined?(:AppBuilder)
+ remove_const :PluginBuilder if const_defined?(:PluginBuilder)
+ end
+ Rails.application = TestApp::Application.instance
+ end
+
+ def test_builder_option_with_empty_app_builder
+ FileUtils.cd(destination_root)
+ run_generator([destination_root, "-b", "#{Rails.root}/lib/#{builders_dir}/empty_builder.rb"])
+ default_files.each{ |path| assert_no_file path }
+ end
+
+ def test_builder_option_with_simple_plugin_builder
+ FileUtils.cd(destination_root)
+ run_generator([destination_root, "-b", "#{Rails.root}/lib/#{builders_dir}/simple_builder.rb"])
+ (default_files - ['.gitignore']).each{ |path| assert_no_file path }
+ assert_file ".gitignore", "foobar"
+ end
+
+ def test_builder_option_with_relative_path
+ here = File.expand_path(File.dirname(__FILE__))
+ FileUtils.cd(here)
+ run_generator([destination_root, "-b", "../fixtures/lib/#{builders_dir}/simple_builder.rb"])
+ FileUtils.cd(destination_root)
+ (default_files - ['.gitignore']).each{ |path| assert_no_file path }
+ assert_file ".gitignore", "foobar"
+ end
+
+ def test_builder_option_with_tweak_plugin_builder
+ FileUtils.cd(destination_root)
+ run_generator([destination_root, "-b", "#{Rails.root}/lib/#{builders_dir}/tweak_builder.rb"])
+ default_files.each{ |path| assert_file path }
+ assert_file ".gitignore", "foobar"
+ end
+
+ def test_builder_option_with_http
+ path = "http://gist.github.com/103208.txt"
+ template = "class #{builder_class}; end"
+ template.instance_eval "def read; self; end" # Make the string respond to read
+
+ generator([destination_root], :builder => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
+ capture(:stdout) { generator.invoke_all }
+
+ default_files.each{ |path| assert_no_file path }
+ end
+end
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 4b52260ecc..701b6816c8 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -224,32 +224,14 @@ module RailtiesTest
end
RUBY
- @plugin.write "app/views/foo/index.html.erb", <<-RUBY
- <%= compute_public_path("/foo", "") %>
+ @plugin.write "app/views/foo/index.html.erb", <<-ERB
<%= image_path("foo.png") %>
<%= javascript_include_tag("foo") %>
<%= stylesheet_link_tag("foo") %>
- RUBY
-
-
- app_file "app/controllers/bar_controller.rb", <<-RUBY
- class BarController < ActionController::Base
- def index
- render :index
- end
- end
- RUBY
-
- app_file "app/views/bar/index.html.erb", <<-RUBY
- <%= compute_public_path("/foo", "") %>
- RUBY
+ ERB
add_to_config 'config.asset_path = "/omg%s"'
- @plugin.write 'public/touch.txt', <<-RUBY
- touch
- RUBY
-
boot_rails
# should set asset_path with engine name by default
@@ -259,11 +241,10 @@ module RailtiesTest
env = Rack::MockRequest.env_for("/foo")
response = Bukkits::Engine.call(env)
- stripped_body = response[2].body.split("\n").map(&:strip).join("\n")
+ stripped_body = response[2].body.split("\n").map(&:strip).join
- expected = "/omg/bukkits/foo\n" +
- "/omg/bukkits/images/foo.png\n" +
- "<script src=\"/omg/bukkits/javascripts/foo.js\" type=\"text/javascript\"></script>\n" +
+ expected = "/omg/bukkits/images/foo.png" +
+ "<script src=\"/omg/bukkits/javascripts/foo.js\" type=\"text/javascript\"></script>" +
"<link href=\"/omg/bukkits/stylesheets/foo.css\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" />"
assert_equal expected, stripped_body
end
@@ -278,21 +259,18 @@ module RailtiesTest
@plugin.write "app/controllers/foo_controller.rb", <<-RUBY
class FooController < ActionController::Base
def index
+ render :inline => '<%= image_path("foo.png") %>'
end
end
RUBY
- @plugin.write "app/views/foo/index.html.erb", <<-RUBY
- <%= compute_public_path("/foo", "") %>
- RUBY
-
boot_rails
env = Rack::MockRequest.env_for("/foo")
response = Bukkits::Engine.call(env)
stripped_body = response[2].body.strip
- expected = "/bukkits/foo"
+ expected = "/bukkits/images/foo.png"
assert_equal expected, stripped_body
end
@@ -685,5 +663,25 @@ module RailtiesTest
assert_equal :haml , generators[:template_engine]
assert_equal :rspec , generators[:test_framework]
end
+
+ test "engine should get default generators with ability to overwrite them" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ config.generators.test_framework :rspec
+ end
+ end
+ RUBY
+
+ boot_rails
+ require "#{rails_root}/config/environment"
+
+ generators = Bukkits::Engine.config.generators.options[:rails]
+ assert_equal :active_record, generators[:orm]
+ assert_equal :rspec , generators[:test_framework]
+
+ app_generators = Rails.application.config.generators.options[:rails]
+ assert_equal :test_unit , app_generators[:test_framework]
+ end
end
end
diff --git a/release.rb b/release.rb
deleted file mode 100644
index 2076515f0e..0000000000
--- a/release.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-version = ARGV.pop
-
-%w( activesupport activemodel activerecord activeresource actionpack actionmailer railties ).each do |framework|
- puts "Building and pushing #{framework}..."
- `cd #{framework} && gem build #{framework}.gemspec && gem push #{framework}-#{version}.gem && rm #{framework}-#{version}.gem`
-end
-
-puts "Building and pushing Rails..."
-`gem build rails.gemspec`
-`gem push rails-#{version}.gem`
-`rm rails-#{version}.gem` \ No newline at end of file
diff --git a/tasks/release.rb b/tasks/release.rb
new file mode 100644
index 0000000000..a605fed160
--- /dev/null
+++ b/tasks/release.rb
@@ -0,0 +1,96 @@
+FRAMEWORKS = %w( activesupport activemodel activerecord activeresource actionpack actionmailer railties )
+
+root = File.expand_path('../../', __FILE__)
+version = File.read("#{root}/RAILS_VERSION").strip
+tag = "v#{version}"
+
+directory "dist"
+
+(FRAMEWORKS + ['rails']).each do |framework|
+ namespace framework do
+ gem = "dist/#{framework}-#{version}.gem"
+ gemspec = "#{framework}.gemspec"
+
+ task :clean do
+ rm_f gem
+ end
+
+ task :update_version_rb do
+ glob = root.dup
+ glob << "/#{framework}/lib/*" unless framework == "rails"
+ glob << "/version.rb"
+
+ file = Dir[glob].first
+ ruby = File.read(file)
+
+ major, minor, tiny, pre = version.split('.')
+ pre = pre ? pre.inspect : "nil"
+
+ ruby.gsub! /^(\s*)MAJOR = .*?$/, "\\1MAJOR = #{major}"
+ raise "Could not insert MAJOR in #{file}" unless $1
+
+ ruby.gsub! /^(\s*)MINOR = .*?$/, "\\1MINOR = #{minor}"
+ raise "Could not insert MINOR in #{file}" unless $1
+
+ ruby.gsub! /^(\s*)TINY = .*?$/, "\\1TINY = #{tiny}"
+ raise "Could not insert TINY in #{file}" unless $1
+
+ ruby.gsub! /^(\s*)PRE = .*?$/, "\\1PRE = #{pre}"
+ raise "Could not insert PRE in #{file}" unless $1
+
+ File.open(file, 'w') { |f| f.write ruby }
+ end
+
+ task gem => %w(update_version_rb dist) do
+ cmd = ""
+ cmd << "cd #{framework} && " unless framework == "rails"
+ cmd << "gem build #{gemspec} && mv #{framework}-#{version}.gem #{root}/dist/"
+ sh cmd
+ end
+
+ task :build => [:clean, gem]
+ task :install => :build do
+ sh "gem install #{gem}"
+ end
+
+ task :prep_release => [:ensure_clean_state, :build]
+
+ task :push => :build do
+ sh "gem push #{gem}"
+ end
+ end
+end
+
+namespace :all do
+ task :build => FRAMEWORKS.map { |f| "#{f}:build" } + ['rails:build']
+ task :install => FRAMEWORKS.map { |f| "#{f}:install" } + ['rails:install']
+ task :push => FRAMEWORKS.map { |f| "#{f}:push" } + ['rails:push']
+
+ task :ensure_clean_state do
+ unless `git status -s | grep -v RAILS_VERSION`.strip.empty?
+ abort "[ABORTING] `git status` reports a dirty tree. Make sure all changes are committed"
+ end
+
+ unless ENV['SKIP_TAG'] || `git tag | grep #{tag}`.strip.empty?
+ abort "[ABORTING] `git tag` shows that #{tag} already exists. Has this version already\n"\
+ " been released? Git tagging can be skipped by setting SKIP_TAG=1"
+ end
+ end
+
+ task :commit do
+ File.open('dist/commit_message.txt', 'w') do |f|
+ f.puts "# Preparing for #{version} release\n"
+ f.puts
+ f.puts "# UNCOMMENT THE LINE ABOVE TO APPROVE THIS COMMIT"
+ end
+
+ sh "git add . && git commit --verbose --template=dist/commit_message.txt"
+ rm_f "dist/commit_message.txt"
+ end
+
+ task :tag do
+ sh "git tag #{tag}"
+ end
+
+ task :release => %w(ensure_clean_state build commit tag push)
+end
diff --git a/version.rb b/version.rb
index 0213d46254..b076881c21 100644
--- a/version.rb
+++ b/version.rb
@@ -3,8 +3,8 @@ module Rails
MAJOR = 3
MINOR = 1
TINY = 0
- BUILD = "beta"
+ PRE = "beta"
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end