aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--RELEASING_RAILS.rdoc2
-rw-r--r--actionpack/CHANGELOG.md2
-rw-r--r--actionpack/lib/abstract_controller/collector.rb6
-rw-r--r--actionpack/lib/abstract_controller/helpers.rb15
-rw-r--r--actionpack/lib/action_controller/caching.rb3
-rw-r--r--actionpack/lib/action_controller/caching/pages.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb6
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb3
-rw-r--r--actionpack/lib/action_dispatch/middleware/public_exceptions.rb47
-rw-r--r--actionpack/lib/action_view.rb3
-rw-r--r--actionpack/lib/action_view/helpers/controller_helper.rb6
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb15
-rw-r--r--actionpack/test/controller/helper_test.rb32
-rw-r--r--actionpack/test/controller/show_exceptions_test.rb25
-rw-r--r--actionpack/test/dispatch/mime_type_test.rb10
-rw-r--r--actionpack/test/dispatch/request/query_string_parsing_test.rb8
-rw-r--r--actionpack/test/metal/caching_test.rb32
-rw-r--r--actionpack/test/template/form_helper_test.rb8
-rw-r--r--activemodel/CHANGELOG.md32
-rw-r--r--activemodel/lib/active_model/mass_assignment_security/permission_set.rb2
-rw-r--r--activemodel/lib/active_model/serializers/json.rb88
-rw-r--r--activemodel/lib/active_model/validations/format.rb23
-rw-r--r--activemodel/test/cases/mass_assignment_security/permission_set_test.rb6
-rw-r--r--activemodel/test/cases/serializers/json_serialization_test.rb90
-rw-r--r--activemodel/test/cases/validations/format_validation_test.rb18
-rw-r--r--activemodel/test/cases/validations/i18n_validation_test.rb4
-rw-r--r--activerecord/CHANGELOG.md10
-rw-r--r--activerecord/Rakefile10
-rw-r--r--activerecord/lib/active_record/attribute_assignment.rb6
-rw-r--r--activerecord/lib/active_record/attribute_methods.rb4
-rw-r--r--activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb3
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb211
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb2
-rw-r--r--activerecord/lib/active_record/core.rb19
-rw-r--r--activerecord/lib/active_record/errors.rb4
-rw-r--r--activerecord/lib/active_record/migration.rb32
-rw-r--r--activerecord/lib/active_record/persistence.rb16
-rw-r--r--activerecord/lib/active_record/railtie.rb7
-rw-r--r--activerecord/lib/active_record/relation/delegation.rb10
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb6
-rw-r--r--activerecord/lib/active_record/schema_dumper.rb2
-rw-r--r--activerecord/lib/active_record/test_case.rb50
-rw-r--r--activerecord/test/cases/associations/eager_test.rb9
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb7
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb2
-rw-r--r--activerecord/test/cases/callbacks_test.rb2
-rw-r--r--activerecord/test/cases/connection_adapters/abstract_adapter_test.rb2
-rw-r--r--activerecord/test/cases/connection_pool_test.rb104
-rw-r--r--activerecord/test/cases/connection_specification/resolver_test.rb3
-rw-r--r--activerecord/test/cases/dirty_test.rb11
-rw-r--r--activerecord/test/cases/finder_respond_to_test.rb3
-rw-r--r--activerecord/test/cases/finder_test.rb15
-rw-r--r--activerecord/test/cases/mass_assignment_security_test.rb28
-rw-r--r--activerecord/test/cases/migration/column_attributes_test.rb2
-rw-r--r--activerecord/test/cases/migration/references_index_test.rb3
-rw-r--r--activerecord/test/cases/migration_test.rb17
-rw-r--r--activerecord/test/cases/named_scope_test.rb10
-rw-r--r--activerecord/test/cases/persistence_test.rb7
-rw-r--r--activerecord/test/cases/query_cache_test.rb7
-rw-r--r--activerecord/test/models/person.rb21
-rw-r--r--activesupport/CHANGELOG.md14
-rw-r--r--activesupport/lib/active_support/configurable.rb57
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/conversions.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/load_error.rb12
-rw-r--r--activesupport/lib/active_support/core_ext/module/delegation.rb3
-rw-r--r--activesupport/lib/active_support/dependencies.rb23
-rw-r--r--activesupport/lib/active_support/file_update_checker.rb19
-rw-r--r--activesupport/lib/active_support/i18n_railtie.rb23
-rw-r--r--activesupport/lib/active_support/log_subscriber.rb4
-rw-r--r--activesupport/lib/active_support/multibyte/chars.rb2
-rw-r--r--activesupport/lib/active_support/test_case.rb3
-rw-r--r--activesupport/lib/active_support/testing/performance.rb41
-rw-r--r--activesupport/lib/active_support/xml_mini.rb2
-rw-r--r--activesupport/test/configurable_test.rb22
-rw-r--r--activesupport/test/core_ext/kernel_test.rb1
-rw-r--r--activesupport/test/dependencies_test.rb17
-rw-r--r--activesupport/test/test_test.rb82
-rw-r--r--activesupport/test/testing/performance_test.rb23
-rw-r--r--guides/source/active_model_basics.textile2
-rw-r--r--guides/source/contributing_to_ruby_on_rails.textile2
-rw-r--r--guides/source/security.textile33
-rw-r--r--railties/CHANGELOG.md2
-rw-r--r--railties/lib/rails/generators/named_base.rb11
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt3
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt8
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/404.html1
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/500.html1
-rw-r--r--railties/lib/rails/generators/rails/app/templates/test/test_helper.rb2
-rw-r--r--railties/lib/rails/generators/rails/controller/templates/controller.rb2
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec2
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/Gemfile15
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/Rakefile2
-rw-r--r--railties/lib/rails/tasks/framework.rake2
-rw-r--r--railties/lib/rails/test_unit/testing.rake2
-rw-r--r--railties/test/application/assets_test.rb41
-rw-r--r--railties/test/application/configuration_test.rb17
-rw-r--r--railties/test/application/rake_test.rb11
-rw-r--r--railties/test/generators/namespaced_generators_test.rb4
-rw-r--r--railties/test/generators/plugin_new_generator_test.rb44
-rw-r--r--railties/test/railties/engine_test.rb4
100 files changed, 1237 insertions, 457 deletions
diff --git a/RELEASING_RAILS.rdoc b/RELEASING_RAILS.rdoc
index 7a77f9bba2..bdf0ffc2d0 100644
--- a/RELEASING_RAILS.rdoc
+++ b/RELEASING_RAILS.rdoc
@@ -176,7 +176,7 @@ You can do this, or ask the security team to do it.
Email the security reports to:
* rubyonrails-security@googlegroups.com
-* linux-distros@vs.openwall.org
+* oss-security@lists.openwall.com
Be sure to note the security fixes in your announcement along with CVE numbers
and links to each patch. Some people may not be able to upgrade right away,
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 815a46a3ca..8c2d887cb3 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,5 +1,7 @@
## Rails 4.0.0 (unreleased) ##
+* Return proper format on exceptions. *Santiago Pastorino*
+
* Allow to use mounted_helpers (helpers for accessing mounted engines) in ActionView::TestCase. *Piotr Sarnacki*
* Include mounted_helpers (helpers for accessing mounted engines) in ActionDispatch::IntegrationTest by default. *Piotr Sarnacki*
diff --git a/actionpack/lib/abstract_controller/collector.rb b/actionpack/lib/abstract_controller/collector.rb
index 81fb514770..492329c401 100644
--- a/actionpack/lib/abstract_controller/collector.rb
+++ b/actionpack/lib/abstract_controller/collector.rb
@@ -4,7 +4,7 @@ module AbstractController
module Collector
def self.generate_method_for_mime(mime)
sym = mime.is_a?(Symbol) ? mime : mime.to_sym
- const = sym.to_s.upcase
+ const = sym.upcase
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{sym}(*args, &block) # def html(*args, &block)
custom(Mime::#{const}, *args, &block) # custom(Mime::HTML, *args, &block)
@@ -19,7 +19,7 @@ module AbstractController
protected
def method_missing(symbol, &block)
- mime_constant = Mime.const_get(symbol.to_s.upcase)
+ mime_constant = Mime.const_get(symbol.upcase)
if Mime::SET.include?(mime_constant)
AbstractController::Collector.generate_method_for_mime(mime_constant)
@@ -29,4 +29,4 @@ module AbstractController
end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb
index 4e0672d590..d63d17f4c5 100644
--- a/actionpack/lib/abstract_controller/helpers.rb
+++ b/actionpack/lib/abstract_controller/helpers.rb
@@ -132,7 +132,11 @@ module AbstractController
case arg
when String, Symbol
file_name = "#{arg.to_s.underscore}_helper"
- require_dependency(file_name, "Missing helper file helpers/%s.rb")
+ begin
+ require_dependency(file_name)
+ rescue LoadError => e
+ raise MissingHelperError.new(e, file_name)
+ end
file_name.camelize.constantize
when Module
arg
@@ -142,6 +146,15 @@ module AbstractController
end
end
+ class MissingHelperError < LoadError
+ def initialize(error, path)
+ @error = error
+ @path = "helpers/#{path}.rb"
+ set_backtrace error.backtrace
+ super("Missing helper file helpers/%s.rb" % path)
+ end
+ end
+
private
# Makes all the (instance) methods in the helper module available to templates
# rendered through this controller.
diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb
index 112573a38d..9118806059 100644
--- a/actionpack/lib/action_controller/caching.rb
+++ b/actionpack/lib/action_controller/caching.rb
@@ -55,6 +55,9 @@ module ActionController #:nodoc:
end
end
+ include RackDelegation
+ include AbstractController::Callbacks
+
include ConfigMethods
include Pages, Actions, Fragments
include Sweeping if defined?(ActiveRecord)
diff --git a/actionpack/lib/action_controller/caching/pages.rb b/actionpack/lib/action_controller/caching/pages.rb
index dd4eddbe9a..73b8cd383c 100644
--- a/actionpack/lib/action_controller/caching/pages.rb
+++ b/actionpack/lib/action_controller/caching/pages.rb
@@ -110,7 +110,7 @@ module ActionController #:nodoc:
gzip_level = options.fetch(:gzip, page_cache_compression)
gzip_level = case gzip_level
when Symbol
- Zlib.const_get(gzip_level.to_s.upcase)
+ Zlib.const_get(gzip_level.upcase)
when Fixnum
gzip_level
when false
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index 0eaae80461..ee1913dbf9 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -99,9 +99,9 @@ module Mime
end
def register(string, symbol, mime_type_synonyms = [], extension_synonyms = [], skip_lookup = false)
- Mime.const_set(symbol.to_s.upcase, Type.new(string, symbol, mime_type_synonyms))
+ Mime.const_set(symbol.upcase, Type.new(string, symbol, mime_type_synonyms))
- SET << Mime.const_get(symbol.to_s.upcase)
+ SET << Mime.const_get(symbol.upcase)
([string] + mime_type_synonyms).each { |str| LOOKUP[str] = SET.last } unless skip_lookup
([symbol] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext.to_s] = SET.last }
@@ -194,7 +194,7 @@ module Mime
#
# Mime::Type.unregister(:mobile)
def unregister(symbol)
- symbol = symbol.to_s.upcase
+ symbol = symbol.upcase
mime = Mime.const_get(symbol)
Mime.instance_eval { remove_const(symbol) }
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index 6757a53bd1..8cea17c7a6 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -271,13 +271,12 @@ module ActionDispatch
case v
when Array
v.grep(Hash) { |x| deep_munge(x) }
+ v.compact!
when Hash
deep_munge(v)
end
end
- keys = hash.keys.find_all { |k| hash[k] == [nil] }
- keys.each { |k| hash[k] = nil }
hash
end
diff --git a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
index 85b8d178bf..204f3f7fb3 100644
--- a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
@@ -8,23 +8,44 @@ module ActionDispatch
end
def call(env)
- status = env["PATH_INFO"][1..-1]
- locale_path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
- path = "#{public_path}/#{status}.html"
-
- if locale_path && File.exist?(locale_path)
- render(status, File.read(locale_path))
- elsif File.exist?(path)
- render(status, File.read(path))
+ exception = env["action_dispatch.exception"]
+ status = env["PATH_INFO"][1..-1]
+ request = ActionDispatch::Request.new(env)
+ content_type = request.formats.first
+ format = content_type && "to_#{content_type.to_sym}"
+ body = { :status => status, :error => exception.message }
+
+ render(status, body, :format => format, :content_type => content_type)
+ end
+
+ private
+
+ def render(status, body, options)
+ format = options[:format]
+
+ if format && body.respond_to?(format)
+ render_format(status, body.public_send(format), options)
else
- [404, { "X-Cascade" => "pass" }, []]
+ render_html(status)
end
end
- private
+ def render_format(status, body, options)
+ [status, {'Content-Type' => "#{options[:content_type]}; charset=#{ActionDispatch::Response.default_charset}",
+ 'Content-Length' => body.bytesize.to_s}, [body]]
+ end
+
+ def render_html(status)
+ found = false
+ path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
+ path = "#{public_path}/#{status}.html" unless path && (found = File.exist?(path))
- def render(status, body)
- [status, {'Content-Type' => "text/html; charset=#{Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]]
+ if found || File.exist?(path)
+ body = File.read(path)
+ [status, {'Content-Type' => "text/html; charset=#{Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]]
+ else
+ [404, { "X-Cascade" => "pass" }, []]
+ end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb
index 3823f87027..899b40c66a 100644
--- a/actionpack/lib/action_view.rb
+++ b/actionpack/lib/action_view.rb
@@ -36,7 +36,6 @@ module ActionView
autoload :LookupContext
autoload :PathSet
autoload :Template
- autoload :TestCase
autoload_under "renderer" do
autoload :Renderer
@@ -73,6 +72,8 @@ module ActionView
end
end
+ autoload :TestCase
+
ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*'
end
diff --git a/actionpack/lib/action_view/helpers/controller_helper.rb b/actionpack/lib/action_view/helpers/controller_helper.rb
index 1a583e62ae..74ef25f7c1 100644
--- a/actionpack/lib/action_view/helpers/controller_helper.rb
+++ b/actionpack/lib/action_view/helpers/controller_helper.rb
@@ -10,14 +10,16 @@ module ActionView
delegate :request_forgery_protection_token, :params, :session, :cookies, :response, :headers,
:flash, :action_name, :controller_name, :controller_path, :to => :controller
- delegate :logger, :to => :controller, :allow_nil => true
-
def assign_controller(controller)
if @_controller = controller
@_request = controller.request if controller.respond_to?(:request)
@_config = controller.config.inheritable_copy if controller.respond_to?(:config)
end
end
+
+ def logger
+ controller.logger if controller.respond_to?(:logger)
+ end
end
end
end
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index ac150882b1..7dd35f7357 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -1311,10 +1311,21 @@ module ActionView
# post:
# create: "Add %{model}"
#
- def button(value=nil, options={})
+ # ==== Examples
+ # button("Create a post")
+ # # => <button name='button' type='submit'>Create post</button>
+ #
+ # button do
+ # content_tag(:strong, 'Ask me!')
+ # end
+ # # => <button name='button' type='submit'>
+ # # <strong>Ask me!</strong>
+ # # </button>
+ #
+ def button(value = nil, options = {}, &block)
value, options = nil, value if value.is_a?(Hash)
value ||= submit_default_value
- @template.button_tag(value, options)
+ @template.button_tag(value, options, &block)
end
def emitted_hidden_id?
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index deb234b04f..248c81193e 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -109,13 +109,13 @@ class HelperTest < ActiveSupport::TestCase
def test_helper_method
assert_nothing_raised { @controller_class.helper_method :delegate_method }
- assert master_helper_methods.include?('delegate_method')
+ assert master_helper_methods.include?(:delegate_method)
end
def test_helper_attr
assert_nothing_raised { @controller_class.helper_attr :delegate_attr }
- assert master_helper_methods.include?('delegate_attr')
- assert master_helper_methods.include?('delegate_attr=')
+ assert master_helper_methods.include?(:delegate_attr)
+ assert master_helper_methods.include?(:delegate_attr=)
end
def call_controller(klass, action)
@@ -160,16 +160,16 @@ class HelperTest < ActiveSupport::TestCase
end
def test_all_helpers
- methods = AllHelpersController._helpers.instance_methods.map {|m| m.to_s}
+ methods = AllHelpersController._helpers.instance_methods
# abc_helper.rb
- assert methods.include?('bare_a')
+ assert methods.include?(:bare_a)
# fun/games_helper.rb
- assert methods.include?('stratego')
+ assert methods.include?(:stratego)
# fun/pdf_helper.rb
- assert methods.include?('foobar')
+ assert methods.include?(:foobar)
end
def test_all_helpers_with_alternate_helper_dir
@@ -180,35 +180,35 @@ class HelperTest < ActiveSupport::TestCase
@controller_class.helper :all
# helpers/abc_helper.rb should not be included
- assert !master_helper_methods.include?('bare_a')
+ assert !master_helper_methods.include?(:bare_a)
# alternate_helpers/foo_helper.rb
- assert master_helper_methods.include?('baz')
+ assert master_helper_methods.include?(:baz)
end
def test_helper_proxy
- methods = AllHelpersController.helpers.methods.map(&:to_s)
+ methods = AllHelpersController.helpers.methods
# Action View
- assert methods.include?('pluralize')
+ assert methods.include?(:pluralize)
# abc_helper.rb
- assert methods.include?('bare_a')
+ assert methods.include?(:bare_a)
# fun/games_helper.rb
- assert methods.include?('stratego')
+ assert methods.include?(:stratego)
# fun/pdf_helper.rb
- assert methods.include?('foobar')
+ assert methods.include?(:foobar)
end
private
def expected_helper_methods
- TestHelper.instance_methods.map {|m| m.to_s }
+ TestHelper.instance_methods
end
def master_helper_methods
- @controller_class._helpers.instance_methods.map {|m| m.to_s }
+ @controller_class._helpers.instance_methods
end
def missing_methods
diff --git a/actionpack/test/controller/show_exceptions_test.rb b/actionpack/test/controller/show_exceptions_test.rb
index 13ab19ed8f..351b9c4cfa 100644
--- a/actionpack/test/controller/show_exceptions_test.rb
+++ b/actionpack/test/controller/show_exceptions_test.rb
@@ -68,4 +68,29 @@ module ShowExceptions
assert_match(/boom/, body)
end
end
+
+ class ShowExceptionsFormatsTest < ActionDispatch::IntegrationTest
+ def test_render_json_exception
+ @app = ShowExceptionsOverridenController.action(:boom)
+ get "/", {}, 'HTTP_ACCEPT' => 'application/json'
+ assert_response :internal_server_error
+ assert_equal 'application/json', response.content_type.to_s
+ assert_equal({ :status => '500', :error => 'boom!' }.to_json, response.body)
+ end
+
+ def test_render_xml_exception
+ @app = ShowExceptionsOverridenController.action(:boom)
+ get "/", {}, 'HTTP_ACCEPT' => 'application/xml'
+ assert_response :internal_server_error
+ assert_equal 'application/xml', response.content_type.to_s
+ assert_equal({ :status => '500', :error => 'boom!' }.to_xml, response.body)
+ end
+
+ def test_render_fallback_exception
+ @app = ShowExceptionsOverridenController.action(:boom)
+ get "/", {}, 'HTTP_ACCEPT' => 'text/csv'
+ assert_response :internal_server_error
+ assert_equal 'text/html', response.content_type.to_s
+ end
+ end
end
diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb
index e3f9faaa64..9d77c3acc5 100644
--- a/actionpack/test/dispatch/mime_type_test.rb
+++ b/actionpack/test/dispatch/mime_type_test.rb
@@ -148,11 +148,11 @@ class MimeTypeTest < ActiveSupport::TestCase
types = Mime::SET.symbols.uniq - [:all, :iphone]
# Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE
- types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) }
+ types.delete_if { |type| !Mime.const_defined?(type.upcase) }
types.each do |type|
- mime = Mime.const_get(type.to_s.upcase)
+ mime = Mime.const_get(type.upcase)
assert mime.respond_to?("#{type}?"), "#{mime.inspect} does not respond to #{type}?"
assert mime.send("#{type}?"), "#{mime.inspect} is not #{type}?"
invalid_types = types - [type]
@@ -170,10 +170,10 @@ class MimeTypeTest < ActiveSupport::TestCase
all_types = Mime::SET.symbols
all_types.uniq!
# Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE
- all_types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) }
+ all_types.delete_if { |type| !Mime.const_defined?(type.upcase) }
verified, unverified = all_types.partition { |type| Mime::Type.browser_generated_types.include? type }
- assert verified.each { |type| assert Mime.const_get(type.to_s.upcase).verify_request?, "Verifiable Mime Type is not verified: #{type.inspect}" }
- assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" }
+ assert verified.each { |type| assert Mime.const_get(type.upcase).verify_request?, "Verifiable Mime Type is not verified: #{type.inspect}" }
+ assert unverified.each { |type| assert !Mime.const_get(type.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" }
end
test "references gives preference to symbols before strings" do
diff --git a/actionpack/test/dispatch/request/query_string_parsing_test.rb b/actionpack/test/dispatch/request/query_string_parsing_test.rb
index 6ea66f9d32..3cb430d83d 100644
--- a/actionpack/test/dispatch/request/query_string_parsing_test.rb
+++ b/actionpack/test/dispatch/request/query_string_parsing_test.rb
@@ -84,11 +84,15 @@ class QueryStringParsingTest < ActionDispatch::IntegrationTest
assert_parses({"action" => nil}, "action")
assert_parses({"action" => {"foo" => nil}}, "action[foo]")
assert_parses({"action" => {"foo" => { "bar" => nil }}}, "action[foo][bar]")
- assert_parses({"action" => {"foo" => { "bar" => nil }}}, "action[foo][bar][]")
- assert_parses({"action" => {"foo" => nil}}, "action[foo][]")
+ assert_parses({"action" => {"foo" => { "bar" => [] }}}, "action[foo][bar][]")
+ assert_parses({"action" => {"foo" => []}}, "action[foo][]")
assert_parses({"action"=>{"foo"=>[{"bar"=>nil}]}}, "action[foo][][bar]")
end
+ def test_array_parses_without_nil
+ assert_parses({"action" => ['1']}, "action[]=1&action[]")
+ end
+
test "query string with empty key" do
assert_parses(
{ "action" => "create_customer", "full_name" => "David Heinemeier Hansson" },
diff --git a/actionpack/test/metal/caching_test.rb b/actionpack/test/metal/caching_test.rb
new file mode 100644
index 0000000000..a2b6763754
--- /dev/null
+++ b/actionpack/test/metal/caching_test.rb
@@ -0,0 +1,32 @@
+require 'abstract_unit'
+
+CACHE_DIR = 'test_cache'
+# Don't change '/../temp/' cavalierly or you might hose something you don't want hosed
+FILE_STORE_PATH = File.join(File.dirname(__FILE__), '/../temp/', CACHE_DIR)
+
+class CachingController < ActionController::Metal
+ abstract!
+
+ include ActionController::Caching
+
+ self.page_cache_directory = FILE_STORE_PATH
+ self.cache_store = :file_store, FILE_STORE_PATH
+end
+
+class PageCachingTestController < CachingController
+ caches_page :ok
+
+ def ok
+ self.response_body = "ok"
+ end
+end
+
+class PageCachingTest < ActionController::TestCase
+ tests PageCachingTestController
+
+ def test_should_cache_get_with_ok_status
+ get :ok
+ assert_response :ok
+ assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/ok.html"), "get with ok status should have been cached"
+ end
+end
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index c9b39ed18f..7da293ce23 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -1054,6 +1054,9 @@ class FormHelperTest < ActionView::TestCase
concat f.check_box(:secret)
concat f.submit('Create post')
concat f.button('Create post')
+ concat f.button {
+ concat content_tag(:span, 'Create post')
+ }
end
expected = whole_form("/posts/123", "create-post" , "edit_post", :method => 'patch') do
@@ -1063,7 +1066,8 @@ class FormHelperTest < ActionView::TestCase
"<input name='post[secret]' type='hidden' value='0' />" +
"<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
"<input name='commit' type='submit' value='Create post' />" +
- "<button name='button' type='submit'>Create post</button>"
+ "<button name='button' type='submit'>Create post</button>" +
+ "<button name='button' type='submit'><span>Create post</span></button>"
end
assert_dom_equal expected, output_buffer
@@ -2359,7 +2363,7 @@ class FormHelperTest < ActionView::TestCase
end
def test_form_builder_does_not_have_form_for_method
- assert ! ActionView::Helpers::FormBuilder.instance_methods.include?('form_for')
+ assert !ActionView::Helpers::FormBuilder.instance_methods.include?(:form_for)
end
def test_form_for_and_fields_for
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index 4ddafddbe0..847ae7f237 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -1,5 +1,32 @@
## Rails 4.0.0 (unreleased) ##
+* Changed `AM::Serializers::JSON.include_root_in_json' default value to false.
+ Now, AM Serializers and AR objects have the same default behaviour. Fixes #6578.
+
+ class User < ActiveRecord::Base; end
+
+ class Person
+ include ActiveModel::Model
+ include ActiveModel::AttributeMethods
+ include ActiveModel::Serializers::JSON
+
+ attr_accessor :name, :age
+
+ def attributes
+ instance_values
+ end
+ end
+
+ user.as_json
+ => {"id"=>1, "name"=>"Konata Izumi", "age"=>16, "awesome"=>true}
+ # root is not included
+
+ person.as_json
+ => {"name"=>"Francesco", "age"=>22}
+ # root is not included
+
+ *Francesco Rodriguez*
+
* Passing false hash values to `validates` will no longer enable the corresponding validators *Steve Purcell*
* `ConfirmationValidator` error messages will attach to `:#{attribute}_confirmation` instead of `attribute` *Brian Cardarella*
@@ -10,6 +37,11 @@
* Trim down Active Model API by removing `valid?` and `errors.full_messages` *José Valim*
+* When `^` or `$` are used in the regular expression provided to `validates_format_of` and the :multiline option is not set to true, an exception will be raised. This is to prevent security vulnerabilities when using `validates_format_of`. The problem is described in detail in the Rails security guide.
+
+## Rails 3.2.6 (Jun 12, 2012) ##
+
+* No changes.
## Rails 3.2.5 (Jun 1, 2012) ##
diff --git a/activemodel/lib/active_model/mass_assignment_security/permission_set.rb b/activemodel/lib/active_model/mass_assignment_security/permission_set.rb
index 9661349503..415ab0ad17 100644
--- a/activemodel/lib/active_model/mass_assignment_security/permission_set.rb
+++ b/activemodel/lib/active_model/mass_assignment_security/permission_set.rb
@@ -5,7 +5,7 @@ module ActiveModel
class PermissionSet < Set
def +(values)
- super(values.map(&:to_s))
+ super(values.compact.map(&:to_s))
end
def include?(key)
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb
index 63ab8e7edc..e668b4a009 100644
--- a/activemodel/lib/active_model/serializers/json.rb
+++ b/activemodel/lib/active_model/serializers/json.rb
@@ -13,80 +13,80 @@ module ActiveModel
extend ActiveModel::Configuration
config_attribute :include_root_in_json
- self.include_root_in_json = true
+ self.include_root_in_json = false
end
# Returns a hash representing the model. Some configuration can be
# passed through +options+.
#
# The option <tt>include_root_in_json</tt> controls the top-level behavior
- # of +as_json+. If true (the default) +as_json+ will emit a single root
- # node named after the object's type. For example:
+ # of +as_json+. If true +as_json+ will emit a single root node named after
+ # the object's type. The default value for <tt>include_root_in_json</tt>
+ # option is +false+.
#
# user = User.find(1)
# user.as_json
- # # => { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
- # "created_at": "2006/08/01", "awesome": true} }
+ # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true}
+ #
+ # ActiveRecord::Base.include_root_in_json = true
#
- # ActiveRecord::Base.include_root_in_json = false
# user.as_json
- # # => {"id": 1, "name": "Konata Izumi", "age": 16,
- # "created_at": "2006/08/01", "awesome": true}
+ # # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true } }
#
- # This behavior can also be achieved by setting the <tt>:root</tt> option to +false+ as in:
+ # This behavior can also be achieved by setting the <tt>:root</tt> option
+ # to +true+ as in:
#
# user = User.find(1)
- # user.as_json(root: false)
- # # => {"id": 1, "name": "Konata Izumi", "age": 16,
- # "created_at": "2006/08/01", "awesome": true}
- #
- # The remainder of the examples in this section assume include_root_in_json is set to
- # <tt>false</tt>.
+ # user.as_json(root: true)
+ # # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true } }
#
# Without any +options+, the returned Hash will include all the model's
- # attributes. For example:
+ # attributes.
#
# user = User.find(1)
# user.as_json
- # # => {"id": 1, "name": "Konata Izumi", "age": 16,
- # "created_at": "2006/08/01", "awesome": true}
+ # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true}
#
- # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the attributes
- # included, and work similar to the +attributes+ method. For example:
+ # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit
+ # the attributes included, and work similar to the +attributes+ method.
#
- # user.as_json(:only => [ :id, :name ])
- # # => {"id": 1, "name": "Konata Izumi"}
+ # user.as_json(only: [:id, :name])
+ # # => { "id" => 1, "name" => "Konata Izumi" }
#
- # user.as_json(:except => [ :id, :created_at, :age ])
- # # => {"name": "Konata Izumi", "awesome": true}
+ # user.as_json(except: [:id, :created_at, :age])
+ # # => { "name" => "Konata Izumi", "awesome" => true }
#
# To include the result of some method calls on the model use <tt>:methods</tt>:
#
- # user.as_json(:methods => :permalink)
- # # => {"id": 1, "name": "Konata Izumi", "age": 16,
- # "created_at": "2006/08/01", "awesome": true,
- # "permalink": "1-konata-izumi"}
+ # user.as_json(methods: :permalink)
+ # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true,
+ # # "permalink" => "1-konata-izumi" }
#
# To include associations use <tt>:include</tt>:
#
- # user.as_json(:include => :posts)
- # # => {"id": 1, "name": "Konata Izumi", "age": 16,
- # "created_at": "2006/08/01", "awesome": true,
- # "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
- # {"id": 2, author_id: 1, "title": "So I was thinking"}]}
+ # user.as_json(include: :posts)
+ # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true,
+ # # "posts" => [ { "id" => 1, "author_id" => 1, "title" => "Welcome to the weblog" },
+ # # { "id" => 2, "author_id" => 1, "title" => "So I was thinking" } ] }
#
# Second level and higher order associations work as well:
#
- # user.as_json(:include => { :posts => {
- # :include => { :comments => {
- # :only => :body } },
- # :only => :title } })
- # # => {"id": 1, "name": "Konata Izumi", "age": 16,
- # "created_at": "2006/08/01", "awesome": true,
- # "posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}],
- # "title": "Welcome to the weblog"},
- # {"comments": [{"body": "Don't think too hard"}],
- # "title": "So I was thinking"}]}
+ # user.as_json(include: { posts: {
+ # include: { comments: {
+ # only: :body } },
+ # only: :title } })
+ # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
+ # # "created_at" => "2006/08/01", "awesome" => true,
+ # # "posts" => [ { "comments" => [ { "body" => "1st post!" }, { "body" => "Second!" } ],
+ # # "title" => "Welcome to the weblog" },
+ # # { "comments" => [ { "body" => "Don't think too hard" } ],
+ # # "title" => "So I was thinking" } ] }
def as_json(options = nil)
root = include_root_in_json
root = options[:root] if options.try(:key?, :root)
@@ -106,4 +106,4 @@ module ActiveModel
end
end
end
-end
+end \ No newline at end of file
diff --git a/activemodel/lib/active_model/validations/format.rb b/activemodel/lib/active_model/validations/format.rb
index dd87e312f9..ffdf842d94 100644
--- a/activemodel/lib/active_model/validations/format.rb
+++ b/activemodel/lib/active_model/validations/format.rb
@@ -32,11 +32,21 @@ module ActiveModel
def record_error(record, attribute, name, value)
record.errors.add(attribute, :invalid, options.except(name).merge!(:value => value))
end
-
+
+ def regexp_using_multiline_anchors?(regexp)
+ regexp.source.start_with?("^") ||
+ (regexp.source.end_with?("$") && !regexp.source.end_with?("\\$"))
+ end
+
def check_options_validity(options, name)
option = options[name]
if option && !option.is_a?(Regexp) && !option.respond_to?(:call)
raise ArgumentError, "A regular expression or a proc or lambda must be supplied as :#{name}"
+ elsif option && option.is_a?(Regexp) &&
+ regexp_using_multiline_anchors?(option) && options[:multiline] != true
+ raise ArgumentError, "The provided regular expression is using multiline anchors (^ or $), " \
+ "which may present a security risk. Did you mean to use \\A and \\z, or forgot to add the " \
+ ":multiline => true option?"
end
end
end
@@ -47,7 +57,7 @@ module ActiveModel
# attribute matches the regular expression:
#
# class Person < ActiveRecord::Base
- # validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
+ # validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, :on => :create
# end
#
# Alternatively, you can require that the specified attribute does _not_
@@ -63,12 +73,16 @@ module ActiveModel
# class Person < ActiveRecord::Base
# # Admin can have number as a first letter in their screen name
# validates_format_of :screen_name,
- # :with => lambda{ |person| person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\Z/i : /\A[a-z][a-z0-9_\-]*\Z/i }
+ # :with => lambda{ |person| person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
# end
#
# Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the
# string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
#
+ # Due to frequent misuse of <tt>^</tt> and <tt>$</tt>, you need to pass the
+ # :multiline => true option in case you use any of these two anchors in the provided
+ # regular expression. In most cases, you should be using <tt>\A</tt> and <tt>\z</tt>.
+ #
# You must pass either <tt>:with</tt> or <tt>:without</tt> as an option.
# In addition, both must be a regular expression or a proc or lambda, or
# else an exception will be raised.
@@ -98,6 +112,9 @@ module ActiveModel
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:strict</tt> - Specifies whether validation should be strict.
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
+ # * <tt>:multiline</tt> - Set to true if your regular expression contains
+ # anchors that match the beginning or end of lines as opposed to the
+ # beginning or end of the string. These anchors are <tt>^</tt> and <tt>$</tt>.
def validates_format_of(*attr_names)
validates_with FormatValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/test/cases/mass_assignment_security/permission_set_test.rb b/activemodel/test/cases/mass_assignment_security/permission_set_test.rb
index d005b638e4..8082c49852 100644
--- a/activemodel/test/cases/mass_assignment_security/permission_set_test.rb
+++ b/activemodel/test/cases/mass_assignment_security/permission_set_test.rb
@@ -13,6 +13,12 @@ class PermissionSetTest < ActiveModel::TestCase
assert new_list.include?('admin'), "did not add collection to #{@permission_list.inspect}}"
end
+ test "+ compacts added collection values" do
+ added_collection = [ nil ]
+ new_list = @permission_list + added_collection
+ assert_equal new_list, @permission_list, "did not add collection to #{@permission_list.inspect}}"
+ end
+
test "include? normalizes multi-parameter keys" do
multi_param_key = 'admin(1)'
new_list = @permission_list += [ 'admin' ]
diff --git a/activemodel/test/cases/serializers/json_serialization_test.rb b/activemodel/test/cases/serializers/json_serialization_test.rb
index 7160635eb4..e2690f1827 100644
--- a/activemodel/test/cases/serializers/json_serialization_test.rb
+++ b/activemodel/test/cases/serializers/json_serialization_test.rb
@@ -31,10 +31,15 @@ class JsonSerializationTest < ActiveModel::TestCase
@contact.preferences = { 'shows' => 'anime' }
end
- test "should include root in json" do
+ def teardown
+ # set to the default value
+ Contact.include_root_in_json = false
+ end
+
+ test "should not include root in json (class method)" do
json = @contact.to_json
- assert_match %r{^\{"contact":\{}, json
+ assert_no_match %r{^\{"contact":\{}, json
assert_match %r{"name":"Konata Izumi"}, json
assert_match %r{"age":16}, json
assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
@@ -42,41 +47,31 @@ class JsonSerializationTest < ActiveModel::TestCase
assert_match %r{"preferences":\{"shows":"anime"\}}, json
end
- test "should not include root in json (class method)" do
- begin
- Contact.include_root_in_json = false
- json = @contact.to_json
-
- assert_no_match %r{^\{"contact":\{}, json
- assert_match %r{"name":"Konata Izumi"}, json
- assert_match %r{"age":16}, json
- assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
- assert_match %r{"awesome":true}, json
- assert_match %r{"preferences":\{"shows":"anime"\}}, json
- ensure
- Contact.include_root_in_json = true
- end
+ test "should include root in json if include_root_in_json is true" do
+ Contact.include_root_in_json = true
+ json = @contact.to_json
+
+ assert_match %r{^\{"contact":\{}, json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"age":16}, json
+ assert json.include?(%("created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}))
+ assert_match %r{"awesome":true}, json
+ assert_match %r{"preferences":\{"shows":"anime"\}}, json
end
test "should include root in json (option) even if the default is set to false" do
- begin
- Contact.include_root_in_json = false
- json = @contact.to_json(:root => true)
- assert_match %r{^\{"contact":\{}, json
- ensure
- Contact.include_root_in_json = true
- end
+ json = @contact.to_json(root: true)
+ assert_match %r{^\{"contact":\{}, json
end
test "should not include root in json (option)" do
-
- json = @contact.to_json(:root => false)
+ json = @contact.to_json(root: false)
assert_no_match %r{^\{"contact":\{}, json
end
test "should include custom root in json" do
- json = @contact.to_json(:root => 'json_contact')
+ json = @contact.to_json(root: 'json_contact')
assert_match %r{^\{"json_contact":\{}, json
assert_match %r{"name":"Konata Izumi"}, json
@@ -107,7 +102,7 @@ class JsonSerializationTest < ActiveModel::TestCase
end
test "should allow attribute filtering with except" do
- json = @contact.to_json(:except => [:name, :age])
+ json = @contact.to_json(except: [:name, :age])
assert_no_match %r{"name":"Konata Izumi"}, json
assert_no_match %r{"age":16}, json
@@ -122,10 +117,10 @@ class JsonSerializationTest < ActiveModel::TestCase
def @contact.favorite_quote; "Constraints are liberating"; end
# Single method.
- assert_match %r{"label":"Has cheezburger"}, @contact.to_json(:only => :name, :methods => :label)
+ assert_match %r{"label":"Has cheezburger"}, @contact.to_json(only: :name, methods: :label)
# Both methods.
- methods_json = @contact.to_json(:only => :name, :methods => [:label, :favorite_quote])
+ methods_json = @contact.to_json(only: :name, methods: [:label, :favorite_quote])
assert_match %r{"label":"Has cheezburger"}, methods_json
assert_match %r{"favorite_quote":"Constraints are liberating"}, methods_json
end
@@ -143,14 +138,15 @@ class JsonSerializationTest < ActiveModel::TestCase
end
test "serializable_hash should not modify options passed in argument" do
- options = { :except => :name }
+ options = { except: :name }
@contact.serializable_hash(options)
assert_nil options[:only]
assert_equal :name, options[:except]
end
- test "as_json should return a hash" do
+ test "as_json should return a hash if include_root_in_json is true" do
+ Contact.include_root_in_json = true
json = @contact.as_json
assert_kind_of Hash, json
@@ -160,7 +156,7 @@ class JsonSerializationTest < ActiveModel::TestCase
end
end
- test "from_json should set the object's attributes" do
+ test "from_json should work without a root (class attribute)" do
json = @contact.to_json
result = Contact.new.from_json(json)
@@ -172,7 +168,7 @@ class JsonSerializationTest < ActiveModel::TestCase
end
test "from_json should work without a root (method parameter)" do
- json = @contact.to_json(:root => false)
+ json = @contact.to_json
result = Contact.new.from_json(json, false)
assert_equal result.name, @contact.name
@@ -182,24 +178,19 @@ class JsonSerializationTest < ActiveModel::TestCase
assert_equal result.preferences, @contact.preferences
end
- test "from_json should work without a root (class attribute)" do
- begin
- Contact.include_root_in_json = false
- json = @contact.to_json
- result = Contact.new.from_json(json)
-
- assert_equal result.name, @contact.name
- assert_equal result.age, @contact.age
- assert_equal Time.parse(result.created_at), @contact.created_at
- assert_equal result.awesome, @contact.awesome
- assert_equal result.preferences, @contact.preferences
- ensure
- Contact.include_root_in_json = true
- end
+ test "from_json should work with a root (method parameter)" do
+ json = @contact.to_json(root: :true)
+ result = Contact.new.from_json(json, true)
+
+ assert_equal result.name, @contact.name
+ assert_equal result.age, @contact.age
+ assert_equal Time.parse(result.created_at), @contact.created_at
+ assert_equal result.awesome, @contact.awesome
+ assert_equal result.preferences, @contact.preferences
end
test "custom as_json should be honored when generating json" do
- def @contact.as_json(options); { :name => name, :created_at => created_at }; end
+ def @contact.as_json(options); { name: name, created_at: created_at }; end
json = @contact.to_json
assert_match %r{"name":"Konata Izumi"}, json
@@ -209,7 +200,7 @@ class JsonSerializationTest < ActiveModel::TestCase
end
test "custom as_json options should be extendible" do
- def @contact.as_json(options = {}); super(options.merge(:only => [:name])); end
+ def @contact.as_json(options = {}); super(options.merge(only: [:name])); end
json = @contact.to_json
assert_match %r{"name":"Konata Izumi"}, json
@@ -217,5 +208,4 @@ class JsonSerializationTest < ActiveModel::TestCase
assert_no_match %r{"awesome":}, json
assert_no_match %r{"preferences":}, json
end
-
end
diff --git a/activemodel/test/cases/validations/format_validation_test.rb b/activemodel/test/cases/validations/format_validation_test.rb
index 41a1131bcb..308a3c6cef 100644
--- a/activemodel/test/cases/validations/format_validation_test.rb
+++ b/activemodel/test/cases/validations/format_validation_test.rb
@@ -11,7 +11,7 @@ class PresenceValidationTest < ActiveModel::TestCase
end
def test_validate_format
- Topic.validates_format_of(:title, :content, :with => /^Validation\smacros \w+!$/, :message => "is bad data")
+ Topic.validates_format_of(:title, :content, :with => /\AValidation\smacros \w+!\z/, :message => "is bad data")
t = Topic.new("title" => "i'm incorrect", "content" => "Validation macros rule!")
assert t.invalid?, "Shouldn't be valid"
@@ -27,7 +27,7 @@ class PresenceValidationTest < ActiveModel::TestCase
end
def test_validate_format_with_allow_blank
- Topic.validates_format_of(:title, :with => /^Validation\smacros \w+!$/, :allow_blank => true)
+ Topic.validates_format_of(:title, :with => /\AValidation\smacros \w+!\z/, :allow_blank => true)
assert Topic.new("title" => "Shouldn't be valid").invalid?
assert Topic.new("title" => "").valid?
assert Topic.new("title" => nil).valid?
@@ -36,7 +36,7 @@ class PresenceValidationTest < ActiveModel::TestCase
# testing ticket #3142
def test_validate_format_numeric
- Topic.validates_format_of(:title, :content, :with => /^[1-9][0-9]*$/, :message => "is bad data")
+ Topic.validates_format_of(:title, :content, :with => /\A[1-9][0-9]*\z/, :message => "is bad data")
t = Topic.new("title" => "72x", "content" => "6789")
assert t.invalid?, "Shouldn't be valid"
@@ -63,11 +63,21 @@ class PresenceValidationTest < ActiveModel::TestCase
end
def test_validate_format_with_formatted_message
- Topic.validates_format_of(:title, :with => /^Valid Title$/, :message => "can't be %{value}")
+ Topic.validates_format_of(:title, :with => /\AValid Title\z/, :message => "can't be %{value}")
t = Topic.new(:title => 'Invalid title')
assert t.invalid?
assert_equal ["can't be Invalid title"], t.errors[:title]
end
+
+ def test_validate_format_of_with_multiline_regexp_should_raise_error
+ assert_raise(ArgumentError) { Topic.validates_format_of(:title, :with => /^Valid Title$/) }
+ end
+
+ def test_validate_format_of_with_multiline_regexp_and_option
+ assert_nothing_raised(ArgumentError) do
+ Topic.validates_format_of(:title, :with => /^Valid Title$/, :multiline => true)
+ end
+ end
def test_validate_format_with_not_option
Topic.validates_format_of(:title, :without => /foo/, :message => "should not contain foo")
diff --git a/activemodel/test/cases/validations/i18n_validation_test.rb b/activemodel/test/cases/validations/i18n_validation_test.rb
index 6b6aad3bd1..bb751cf9c5 100644
--- a/activemodel/test/cases/validations/i18n_validation_test.rb
+++ b/activemodel/test/cases/validations/i18n_validation_test.rb
@@ -141,7 +141,7 @@ class I18nValidationTest < ActiveModel::TestCase
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_format_of on generated message #{name}" do
- Person.validates_format_of :title, validation_options.merge(:with => /^[1-9][0-9]*$/)
+ Person.validates_format_of :title, validation_options.merge(:with => /\A[1-9][0-9]*\z/)
@person.title = '72x'
@person.errors.expects(:generate_message).with(:title, :invalid, generate_message_options.merge(:value => '72x'))
@person.valid?
@@ -291,7 +291,7 @@ class I18nValidationTest < ActiveModel::TestCase
# validates_format_of w/o mocha
set_expectations_for_validation "validates_format_of", :invalid do |person, options_to_merge|
- Person.validates_format_of :title, options_to_merge.merge(:with => /^[1-9][0-9]*$/)
+ Person.validates_format_of :title, options_to_merge.merge(:with => /\A[1-9][0-9]*\z/)
end
# validates_inclusion_of w/o mocha
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index b04c54ce7f..b7c2788db4 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,5 +1,13 @@
## Rails 4.0.0 (unreleased) ##
+* Added `ActiveRecord::Migration.check_pending!` that raises an error if
+ migrations are pending. *Richard Schneeman*
+
+* Added `#destroy!` which acts like `#destroy` but will raise an
+ `ActiveRecord::RecordNotDestroyed` exception instead of returning `false`.
+
+ *Marc-André Lafortune*
+
* Allow blocks for `count` with `ActiveRecord::Relation`, to work similar as
`Array#count`:
@@ -1206,8 +1214,6 @@
## Rails 3.0.0 (August 29, 2010) ##
-* Changed update_attribute to not run callbacks and update the record directly in the database *Neeraj Singh*
-
* Add scoping and unscoped as the syntax to replace the old with_scope and with_exclusive_scope *José Valim*
* New rake task, db:migrate:status, displays status of migrations #4947 *Kevin Skoglund*
diff --git a/activerecord/Rakefile b/activerecord/Rakefile
index 7feb0b75a0..a29d7b0e99 100644
--- a/activerecord/Rakefile
+++ b/activerecord/Rakefile
@@ -114,6 +114,16 @@ namespace :postgresql do
config = ARTest.config['connections']['postgresql']
%x( createdb -E UTF8 #{config['arunit']['database']} )
%x( createdb -E UTF8 #{config['arunit2']['database']} )
+
+ # prepare hstore
+ version = %x( createdb --version ).strip.gsub(/(.*)(\d\.\d\.\d)$/, "\\2")
+ %w(arunit arunit2).each do |db|
+ if version < "9.1.0"
+ puts "Please prepare hstore data type. See http://www.postgresql.org/docs/9.0/static/hstore.html"
+ else
+ %x( psql #{config[db]['database']} -c "CREATE EXTENSION hstore;" )
+ end
+ end
end
desc 'Drop the PostgreSQL test databases'
diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb
index bf9fe70b31..abc2fa546a 100644
--- a/activerecord/lib/active_record/attribute_assignment.rb
+++ b/activerecord/lib/active_record/attribute_assignment.rb
@@ -64,11 +64,12 @@ module ActiveRecord
# user.name # => "Josh"
# user.is_admin? # => true
def assign_attributes(new_attributes, options = {})
- return unless new_attributes
+ return if new_attributes.blank?
attributes = new_attributes.stringify_keys
multi_parameter_attributes = []
nested_parameter_attributes = []
+ previous_options = @mass_assignment_options
@mass_assignment_options = options
unless options[:without_protection]
@@ -94,8 +95,9 @@ module ActiveRecord
send("#{k}=", v)
end
- @mass_assignment_options = nil
assign_multiparameter_attributes(multi_parameter_attributes)
+ ensure
+ @mass_assignment_options = previous_options
end
protected
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
index 39ea885246..172026d150 100644
--- a/activerecord/lib/active_record/attribute_methods.rb
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -149,7 +149,9 @@ module ActiveRecord
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
def attributes
- Hash[@attributes.map { |name, _| [name, read_attribute(name)] }]
+ attribute_names.each_with_object({}) { |name, attrs|
+ attrs[name] = read_attribute(name)
+ }
end
# Returns an <tt>#inspect</tt>-like string for the value of the
diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
index ac31b636db..58a5d82e14 100644
--- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
+++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
@@ -57,8 +57,9 @@ module ActiveRecord
time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time
end
time = time.in_time_zone rescue nil if time
+ changed = read_attribute(:#{attr_name}) != time
write_attribute(:#{attr_name}, original_time)
- #{attr_name}_will_change!
+ #{attr_name}_will_change! if changed
@attributes_cache["#{attr_name}"] = time
end
EOV
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
index c259e46073..61ff603006 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -2,7 +2,6 @@ require 'thread'
require 'monitor'
require 'set'
require 'active_support/core_ext/module/deprecation'
-require 'timeout'
module ActiveRecord
# Raised when a connection could not be obtained within the connection
@@ -70,6 +69,131 @@ module ActiveRecord
# after which the Reaper will consider a connection reapable. (default
# 5 seconds).
class ConnectionPool
+ # Threadsafe, fair, FIFO queue. Meant to be used by ConnectionPool
+ # with which it shares a Monitor. But could be a generic Queue.
+ #
+ # The Queue in stdlib's 'thread' could replace this class except
+ # stdlib's doesn't support waiting with a timeout.
+ class Queue
+ def initialize(lock = Monitor.new)
+ @lock = lock
+ @cond = @lock.new_cond
+ @num_waiting = 0
+ @queue = []
+ end
+
+ # Test if any threads are currently waiting on the queue.
+ def any_waiting?
+ synchronize do
+ @num_waiting > 0
+ end
+ end
+
+ # Return the number of threads currently waiting on this
+ # queue.
+ def num_waiting
+ synchronize do
+ @num_waiting
+ end
+ end
+
+ # Add +element+ to the queue. Never blocks.
+ def add(element)
+ synchronize do
+ @queue.push element
+ @cond.signal
+ end
+ end
+
+ # If +element+ is in the queue, remove and return it, or nil.
+ def delete(element)
+ synchronize do
+ @queue.delete(element)
+ end
+ end
+
+ # Remove all elements from the queue.
+ def clear
+ synchronize do
+ @queue.clear
+ end
+ end
+
+ # Remove the head of the queue.
+ #
+ # If +timeout+ is not given, remove and return the head the
+ # queue if the number of available elements is strictly
+ # greater than the number of threads currently waiting (that
+ # is, don't jump ahead in line). Otherwise, return nil.
+ #
+ # If +timeout+ is given, block if it there is no element
+ # available, waiting up to +timeout+ seconds for an element to
+ # become available.
+ #
+ # Raises:
+ # - ConnectionTimeoutError if +timeout+ is given and no element
+ # becomes available after +timeout+ seconds,
+ def poll(timeout = nil)
+ synchronize do
+ if timeout
+ no_wait_poll || wait_poll(timeout)
+ else
+ no_wait_poll
+ end
+ end
+ end
+
+ private
+
+ def synchronize(&block)
+ @lock.synchronize(&block)
+ end
+
+ # Test if the queue currently contains any elements.
+ def any?
+ !@queue.empty?
+ end
+
+ # A thread can remove an element from the queue without
+ # waiting if an only if the number of currently available
+ # connections is strictly greater than the number of waiting
+ # threads.
+ def can_remove_no_wait?
+ @queue.size > @num_waiting
+ end
+
+ # Removes and returns the head of the queue if possible, or nil.
+ def remove
+ @queue.shift
+ end
+
+ # Remove and return the head the queue if the number of
+ # available elements is strictly greater than the number of
+ # threads currently waiting. Otherwise, return nil.
+ def no_wait_poll
+ remove if can_remove_no_wait?
+ end
+
+ # Waits on the queue up to +timeout+ seconds, then removes and
+ # returns the head of the queue.
+ def wait_poll(timeout)
+ @num_waiting += 1
+
+ t0 = Time.now
+ elapsed = 0
+ loop do
+ @cond.wait(timeout - elapsed)
+
+ return remove if any?
+
+ elapsed = Time.now - t0
+ raise ConnectionTimeoutError if elapsed >= timeout
+ end
+ ensure
+ @num_waiting -= 1
+ end
+ end
+
# Every +frequency+ seconds, the reaper will call +reap+ on +pool+.
# A reaper instantiated with a nil frequency will never reap the
# connection pool.
@@ -100,21 +224,6 @@ module ActiveRecord
attr_accessor :automatic_reconnect, :checkout_timeout, :dead_connection_timeout
attr_reader :spec, :connections, :size, :reaper
- class Latch # :nodoc:
- def initialize
- @mutex = Mutex.new
- @cond = ConditionVariable.new
- end
-
- def release
- @mutex.synchronize { @cond.broadcast }
- end
-
- def await
- @mutex.synchronize { @cond.wait @mutex }
- end
- end
-
# Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
# object which describes database connection information (e.g. adapter,
# host name, username, password, etc), as well as the maximum size for
@@ -137,9 +246,18 @@ module ActiveRecord
# default max pool size to 5
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
- @latch = Latch.new
@connections = []
@automatic_reconnect = true
+
+ @available = Queue.new self
+ end
+
+ # Hack for tests to be able to add connections. Do not call outside of tests
+ def insert_connection_for_test!(c) #:nodoc:
+ synchronize do
+ @connections << c
+ @available.add c
+ end
end
# Retrieve the connection associated with the current thread, or call
@@ -197,6 +315,7 @@ module ActiveRecord
conn.disconnect!
end
@connections = []
+ @available.clear
end
end
@@ -211,6 +330,10 @@ module ActiveRecord
@connections.delete_if do |conn|
conn.requires_reloading?
end
+ @available.clear
+ @connections.each do |conn|
+ @available.add conn
+ end
end
end
@@ -234,23 +357,10 @@ module ActiveRecord
# Raises:
# - PoolFullError: no connection can be obtained from the pool.
def checkout
- loop do
- # Checkout an available connection
- synchronize do
- # Try to find a connection that hasn't been leased, and lease it
- conn = connections.find { |c| c.lease }
-
- # If all connections were leased, and we have room to expand,
- # create a new connection and lease it.
- if !conn && connections.size < size
- conn = checkout_new_connection
- conn.lease
- end
-
- return checkout_and_verify(conn) if conn
- end
-
- Timeout.timeout(@checkout_timeout, PoolFullError) { @latch.await }
+ synchronize do
+ conn = acquire_connection
+ conn.lease
+ checkout_and_verify(conn)
end
end
@@ -266,8 +376,9 @@ module ActiveRecord
end
release conn
+
+ @available.add conn
end
- @latch.release
end
# Remove a connection from the connection pool. The connection will
@@ -275,12 +386,14 @@ module ActiveRecord
def remove(conn)
synchronize do
@connections.delete conn
+ @available.delete conn
# FIXME: we might want to store the key on the connection so that removing
# from the reserved hash will be a little easier.
release conn
+
+ @available.add checkout_new_connection if @available.any_waiting?
end
- @latch.release
end
# Removes dead connections from the pool. A dead connection can occur
@@ -293,11 +406,35 @@ module ActiveRecord
remove conn if conn.in_use? && stale > conn.last_use && !conn.active?
end
end
- @latch.release
end
private
+ # Acquire a connection by one of 1) immediately removing one
+ # from the queue of available connections, 2) creating a new
+ # connection if the pool is not at capacity, 3) waiting on the
+ # queue for a connection to become available.
+ #
+ # Raises:
+ # - PoolFullError if a connection could not be acquired (FIXME:
+ # why not ConnectionTimeoutError?
+ def acquire_connection
+ if conn = @available.poll
+ conn
+ elsif @connections.size < @size
+ checkout_new_connection
+ else
+ t0 = Time.now
+ begin
+ @available.poll(@checkout_timeout)
+ rescue ConnectionTimeoutError
+ msg = 'could not obtain a database connection within %0.3f seconds (waited %0.3f seconds)' %
+ [@checkout_timeout, Time.now - t0]
+ raise PoolFullError, msg
+ end
+ end
+ end
+
def release(conn)
thread_id = if @reserved_connections[current_connection_id] == conn
current_connection_id
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index 5758ac4569..f5794a4e54 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -548,7 +548,7 @@ module ActiveRecord
if options.is_a?(Hash) && order = options[:order]
case order
when Hash
- column_names.each {|name| option_strings[name] += " #{order[name].to_s.upcase}" if order.has_key?(name)}
+ column_names.each {|name| option_strings[name] += " #{order[name].upcase}" if order.has_key?(name)}
when String
column_names.each {|name| option_strings[name] += " #{order.upcase}"}
end
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index 1fa6c701bb..dbad561ca2 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -380,15 +380,16 @@ module ActiveRecord
@attributes[pk] = nil unless @attributes.key?(pk)
- @aggregation_cache = {}
- @association_cache = {}
- @attributes_cache = {}
- @previously_changed = {}
- @changed_attributes = {}
- @readonly = false
- @destroyed = false
- @marked_for_destruction = false
- @new_record = true
+ @aggregation_cache = {}
+ @association_cache = {}
+ @attributes_cache = {}
+ @previously_changed = {}
+ @changed_attributes = {}
+ @readonly = false
+ @destroyed = false
+ @marked_for_destruction = false
+ @new_record = true
+ @mass_assignment_options = nil
end
end
end
diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb
index fc80f3081e..9b88bb8178 100644
--- a/activerecord/lib/active_record/errors.rb
+++ b/activerecord/lib/active_record/errors.rb
@@ -53,6 +53,10 @@ module ActiveRecord
class RecordNotSaved < ActiveRecordError
end
+ # Raised by ActiveRecord::Base.destroy! when a call to destroy would return false.
+ class RecordNotDestroyed < ActiveRecordError
+ end
+
# Raised when SQL statement cannot be executed by the database (for example, it's often the case for
# MySQL when Ruby driver used is too old).
class StatementInvalid < ActiveRecordError
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index ac4f53c774..acec65991d 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -32,6 +32,12 @@ module ActiveRecord
end
end
+ class PendingMigrationError < ActiveRecordError#:nodoc:
+ def initialize
+ super("Migrations are pending run 'rake db:migrate RAILS_ENV=#{ENV['RAILS_ENV']}' to resolve the issue")
+ end
+ end
+
# = Active Record Migrations
#
# Migrations can manage the evolution of a schema used by several physical
@@ -326,10 +332,28 @@ module ActiveRecord
class Migration
autoload :CommandRecorder, 'active_record/migration/command_recorder'
+
+ # This class is used to verify that all migrations have been run before
+ # loading a web page if config.active_record.migration_error is set to :page_load
+ class CheckPending
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ ActiveRecord::Migration.check_pending!
+ @app.call(env)
+ end
+ end
+
class << self
attr_accessor :delegate # :nodoc:
end
+ def self.check_pending!
+ raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?
+ end
+
def self.method_missing(name, *args, &block) # :nodoc:
(delegate || superclass.delegate).send(name, *args, &block)
end
@@ -605,6 +629,14 @@ module ActiveRecord
end
end
+ def needs_migration?
+ current_version < last_version
+ end
+
+ def last_version
+ migrations(migrations_paths).last.try(:version)||0
+ end
+
def proper_table_name(name)
# Use the Active Record objects own table_name, or pre/suffix from ActiveRecord::Base if name is a symbol/string
name.table_name rescue "#{ActiveRecord::Base.table_name_prefix}#{name}#{ActiveRecord::Base.table_name_suffix}"
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index a1bc39a32d..ec5670ba6e 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -122,6 +122,11 @@ module ActiveRecord
# Deletes the record in the database and freezes this instance to reflect
# that no changes should be made (since they can't be persisted).
+ #
+ # There's a series of callbacks associated with <tt>destroy</tt>. If
+ # the <tt>before_destroy</tt> callback return +false+ the action is cancelled
+ # and <tt>destroy</tt> returns +false+. See
+ # ActiveRecord::Callbacks for further details.
def destroy
raise ReadOnlyRecord if readonly?
destroy_associations
@@ -130,6 +135,17 @@ module ActiveRecord
freeze
end
+ # Deletes the record in the database and freezes this instance to reflect
+ # that no changes should be made (since they can't be persisted).
+ #
+ # There's a series of callbacks associated with <tt>destroy!</tt>. If
+ # the <tt>before_destroy</tt> callback return +false+ the action is cancelled
+ # and <tt>destroy!</tt> raises ActiveRecord::RecordNotDestroyed. See
+ # ActiveRecord::Callbacks for further details.
+ def destroy!
+ destroy || raise(ActiveRecord::RecordNotDestroyed)
+ end
+
# Returns an instance of the specified +klass+ with the attributes of the
# current record. This is mostly useful in relation to single-table
# inheritance structures where you want a subclass to appear as the
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index 1e497b2a79..319516413b 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -59,6 +59,13 @@ module ActiveRecord
ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
end
+ initializer "active_record.migration_error" do |app|
+ if config.active_record.delete(:migration_error) == :page_load
+ config.app_middleware.insert_after "::ActionDispatch::Callbacks",
+ "ActiveRecord::Migration::CheckPending"
+ end
+ end
+
initializer "active_record.set_configs" do |app|
ActiveSupport.on_load(:active_record) do
if app.config.active_record.delete(:whitelist_attributes)
diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb
index f5fdf437bf..64dda4f35a 100644
--- a/activerecord/lib/active_record/relation/delegation.rb
+++ b/activerecord/lib/active_record/relation/delegation.rb
@@ -32,12 +32,12 @@ module ActiveRecord
protected
def method_missing(method, *args, &block)
- if Array.method_defined?(method)
- ::ActiveRecord::Delegation.delegate method, :to => :to_a
- to_a.send(method, *args, &block)
- elsif @klass.respond_to?(method)
+ if @klass.respond_to?(method)
::ActiveRecord::Delegation.delegate_to_scoped_klass(method)
scoping { @klass.send(method, *args, &block) }
+ elsif Array.method_defined?(method)
+ ::ActiveRecord::Delegation.delegate method, :to => :to_a
+ to_a.send(method, *args, &block)
elsif arel.respond_to?(method)
::ActiveRecord::Delegation.delegate method, :to => :arel
arel.send(method, *args, &block)
@@ -46,4 +46,4 @@ module ActiveRecord
end
end
end
-end \ No newline at end of file
+end
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 5f6898b45a..c91758265b 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -106,7 +106,7 @@ module ActiveRecord
# Person.last # returns the last object fetched by SELECT * FROM people
# Person.where(["user_name = ?", user_name]).last
# Person.order("created_on DESC").offset(5).last
- # Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
+ # Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
#
# Take note that in that last case, the results are sorted in ascending order:
#
@@ -176,7 +176,7 @@ module ActiveRecord
join_dependency = construct_join_dependency_for_association_find
relation = construct_relation_for_association_find(join_dependency)
- relation = relation.except(:select, :order).select("1").limit(1)
+ relation = relation.except(:select, :order).select("1 AS one").limit(1)
case id
when Array, Hash
@@ -186,6 +186,8 @@ module ActiveRecord
end
connection.select_value(relation, "#{name} Exists", relation.bind_values)
+ rescue ThrowResult
+ false
end
protected
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
index 7cbe2db408..1cdaa516ba 100644
--- a/activerecord/lib/active_record/schema_dumper.rb
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -175,7 +175,7 @@ HEADER
when BigDecimal
value.to_s
when Date, DateTime, Time
- "'" + value.to_s(:db) + "'"
+ "'#{value.to_s(:db)}'"
else
value.inspect
end
diff --git a/activerecord/lib/active_record/test_case.rb b/activerecord/lib/active_record/test_case.rb
index fcaa4b74a6..c7a6c37d50 100644
--- a/activerecord/lib/active_record/test_case.rb
+++ b/activerecord/lib/active_record/test_case.rb
@@ -8,7 +8,7 @@ module ActiveRecord
# Defines some test assertions to test against SQL queries.
class TestCase < ActiveSupport::TestCase #:nodoc:
def teardown
- SQLCounter.log.clear
+ SQLCounter.clear_log
end
def assert_date_from_db(expected, actual, message = nil)
@@ -22,47 +22,57 @@ module ActiveRecord
end
def assert_sql(*patterns_to_match)
- SQLCounter.log = []
+ SQLCounter.clear_log
yield
- SQLCounter.log
+ SQLCounter.log_all
ensure
failed_patterns = []
patterns_to_match.each do |pattern|
- failed_patterns << pattern unless SQLCounter.log.any?{ |sql| pattern === sql }
+ failed_patterns << pattern unless SQLCounter.log_all.any?{ |sql| pattern === sql }
end
assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map{ |p| p.inspect }.join(', ')} not found.#{SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{SQLCounter.log.join("\n")}"}"
end
- def assert_queries(num = 1)
- SQLCounter.log = []
+ def assert_queries(num = 1, options = {})
+ ignore_none = options.fetch(:ignore_none) { num == :any }
+ SQLCounter.clear_log
yield
ensure
- assert_equal num, SQLCounter.log.size, "#{SQLCounter.log.size} instead of #{num} queries were executed.#{SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{SQLCounter.log.join("\n")}"}"
+ the_log = ignore_none ? SQLCounter.log_all : SQLCounter.log
+ if num == :any
+ assert_operator the_log.size, :>=, 1, "1 or more queries expected, but none were executed."
+ else
+ mesg = "#{the_log.size} instead of #{num} queries were executed.#{the_log.size == 0 ? '' : "\nQueries:\n#{the_log.join("\n")}"}"
+ assert_equal num, the_log.size, mesg
+ end
end
def assert_no_queries(&block)
- prev_ignored_sql = SQLCounter.ignored_sql
- SQLCounter.ignored_sql = []
- assert_queries(0, &block)
- ensure
- SQLCounter.ignored_sql = prev_ignored_sql
+ assert_queries(0, :ignore_none => true, &block)
end
end
class SQLCounter
class << self
- attr_accessor :ignored_sql, :log
+ attr_accessor :ignored_sql, :log, :log_all
+ def clear_log; self.log = []; self.log_all = []; end
end
- self.log = []
+ self.clear_log
self.ignored_sql = [/^PRAGMA (?!(table_info))/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/, /^BEGIN/, /^COMMIT/]
# FIXME: this needs to be refactored so specific database can add their own
- # ignored SQL. This ignored SQL is for Oracle.
- ignored_sql.concat [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im]
-
+ # ignored SQL, or better yet, use a different notification for the queries
+ # instead examining the SQL content.
+ oracle_ignored = [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im]
+ mysql_ignored = [/^SHOW TABLES/i, /^SHOW FULL FIELDS/]
+ postgresql_ignored = [/^\s*select\b.*\bfrom\b.*pg_namespace\b/im, /^\s*select\b.*\battname\b.*\bfrom\b.*\bpg_attribute\b/im]
+
+ [oracle_ignored, mysql_ignored, postgresql_ignored].each do |db_ignored_sql|
+ ignored_sql.concat db_ignored_sql
+ end
attr_reader :ignore
@@ -75,8 +85,10 @@ module ActiveRecord
# FIXME: this seems bad. we should probably have a better way to indicate
# the query was cached
- return if 'CACHE' == values[:name] || ignore =~ sql
- self.class.log << sql
+ return if 'CACHE' == values[:name]
+
+ self.class.log_all << sql
+ self.class.log << sql unless ignore =~ sql
end
end
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index 08467900f9..31b11ee334 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -29,11 +29,6 @@ class EagerAssociationTest < ActiveRecord::TestCase
:owners, :pets, :author_favorites, :jobs, :references, :subscribers, :subscriptions, :books,
:developers, :projects, :developers_projects, :members, :memberships, :clubs, :sponsors
- def setup
- # preheat table existence caches
- Comment.find_by_id(1)
- end
-
def test_eager_with_has_one_through_join_model_with_conditions_on_the_through
member = Member.scoped(:includes => :favourite_club).find(members(:some_other_guy).id)
assert_nil member.favourite_club
@@ -983,7 +978,6 @@ class EagerAssociationTest < ActiveRecord::TestCase
Post.scoped(:includes => :author, :joins => {:taggings => {:tag => :taggings}}, :where => "taggings_tags.super_tag_id=2", :order => 'posts.id').all
end
assert_equal posts(:welcome, :thinking), posts
-
end
def test_eager_loading_with_conditions_on_string_joined_table_preloads
@@ -998,7 +992,6 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
-
end
def test_eager_loading_with_select_on_joined_table_preloads
@@ -1010,8 +1003,6 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_loading_with_conditions_on_join_model_preloads
- Author.columns
-
authors = assert_queries(2) do
Author.scoped(:includes => :author_address, :joins => :comments, :where => "posts.title like 'Welcome%'").all
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 ed1caa2ef5..9d693bae0c 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
@@ -817,11 +817,14 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
# clear cache possibly created by other tests
david.projects.reset_column_information
- assert_queries(1) { david.projects.columns; david.projects.columns }
+ assert_queries(:any) { david.projects.columns }
+ assert_no_queries { david.projects.columns }
## and again to verify that reset_column_information clears the cache correctly
david.projects.reset_column_information
- assert_queries(1) { david.projects.columns; david.projects.columns }
+
+ assert_queries(:any) { david.projects.columns }
+ assert_no_queries { david.projects.columns }
end
def test_attributes_are_being_set_when_initialized_from_habm_association_with_where_clause
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 0d8f311117..b8481175b2 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -1358,7 +1358,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
assert_equal author.essays, Essay.where(writer_id: "David")
-
end
def test_has_many_custom_primary_key
@@ -1438,7 +1437,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
:group => "#{Namespaced::Firm.table_name}.id"
).find firm.id
assert_equal 1, stats.num_clients.to_i
-
ensure
ActiveRecord::Base.store_full_sti_class = old
end
diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb
index 7690769226..deeef3a3fd 100644
--- a/activerecord/test/cases/callbacks_test.rb
+++ b/activerecord/test/cases/callbacks_test.rb
@@ -426,11 +426,13 @@ class CallbacksTest < ActiveRecord::TestCase
def test_before_destroy_returning_false
david = ImmutableDeveloper.find(1)
assert !david.destroy
+ assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! }
assert_not_nil ImmutableDeveloper.find_by_id(1)
someone = CallbackCancellationDeveloper.find(1)
someone.cancel_before_destroy = true
assert !someone.destroy
+ assert_raise(ActiveRecord::RecordNotDestroyed) { someone.destroy! }
assert !someone.after_destroy_called
end
diff --git a/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb b/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb
index 7dc6e8afcb..3e3d6e2769 100644
--- a/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb
+++ b/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb
@@ -36,7 +36,7 @@ module ActiveRecord
def test_close
pool = ConnectionPool.new(ConnectionSpecification.new({}, nil))
- pool.connections << adapter
+ pool.insert_connection_for_test! adapter
adapter.pool = pool
# Make sure the pool marks the connection in use
diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb
index bba7815d73..8287b35aaf 100644
--- a/activerecord/test/cases/connection_pool_test.rb
+++ b/activerecord/test/cases/connection_pool_test.rb
@@ -200,6 +200,110 @@ module ActiveRecord
end.join
end
+ # The connection pool is "fair" if threads waiting for
+ # connections receive them the order in which they began
+ # waiting. This ensures that we don't timeout one HTTP request
+ # even while well under capacity in a multi-threaded environment
+ # such as a Java servlet container.
+ #
+ # We don't need strict fairness: if two connections become
+ # available at the same time, it's fine of two threads that were
+ # waiting acquire the connections out of order.
+ #
+ # Thus this test prepares waiting threads and then trickles in
+ # available connections slowly, ensuring the wakeup order is
+ # correct in this case.
+ def test_checkout_fairness
+ @pool.instance_variable_set(:@size, 10)
+ expected = (1..@pool.size).to_a.freeze
+ # check out all connections so our threads start out waiting
+ conns = expected.map { @pool.checkout }
+ mutex = Mutex.new
+ order = []
+ errors = []
+
+ threads = expected.map do |i|
+ t = Thread.new {
+ begin
+ @pool.checkout # never checked back in
+ mutex.synchronize { order << i }
+ rescue => e
+ mutex.synchronize { errors << e }
+ end
+ }
+ Thread.pass until t.status == "sleep"
+ t
+ end
+
+ # this should wake up the waiting threads one by one in order
+ conns.each { |conn| @pool.checkin(conn); sleep 0.1 }
+
+ threads.each(&:join)
+
+ raise errors.first if errors.any?
+
+ assert_equal(expected, order)
+ end
+
+ # As mentioned in #test_checkout_fairness, we don't care about
+ # strict fairness. This test creates two groups of threads:
+ # group1 whose members all start waiting before any thread in
+ # group2. Enough connections are checked in to wakeup all
+ # group1 threads, and the fact that only group1 and no group2
+ # threads acquired a connection is enforced.
+ def test_checkout_fairness_by_group
+ @pool.instance_variable_set(:@size, 10)
+ # take all the connections
+ conns = (1..10).map { @pool.checkout }
+ mutex = Mutex.new
+ successes = [] # threads that successfully got a connection
+ errors = []
+
+ make_thread = proc do |i|
+ t = Thread.new {
+ begin
+ @pool.checkout # never checked back in
+ mutex.synchronize { successes << i }
+ rescue => e
+ mutex.synchronize { errors << e }
+ end
+ }
+ Thread.pass until t.status == "sleep"
+ t
+ end
+
+ # all group1 threads start waiting before any in group2
+ group1 = (1..5).map(&make_thread)
+ group2 = (6..10).map(&make_thread)
+
+ # checkin n connections back to the pool
+ checkin = proc do |n|
+ n.times do
+ c = conns.pop
+ @pool.checkin(c)
+ end
+ end
+
+ checkin.call(group1.size) # should wake up all group1
+
+ loop do
+ sleep 0.1
+ break if mutex.synchronize { (successes.size + errors.size) == group1.size }
+ end
+
+ winners = mutex.synchronize { successes.dup }
+ checkin.call(group2.size) # should wake up everyone remaining
+
+ group1.each(&:join)
+ group2.each(&:join)
+
+ assert_equal((1..group1.size).to_a, winners.sort)
+
+ if errors.any?
+ raise errors.first
+ end
+ end
+
def test_automatic_reconnect=
pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
assert pool.automatic_reconnect
diff --git a/activerecord/test/cases/connection_specification/resolver_test.rb b/activerecord/test/cases/connection_specification/resolver_test.rb
index e6cb1b9521..673a2b2b88 100644
--- a/activerecord/test/cases/connection_specification/resolver_test.rb
+++ b/activerecord/test/cases/connection_specification/resolver_test.rb
@@ -9,6 +9,7 @@ module ActiveRecord
end
def test_url_host_no_db
+ skip "only if mysql is available" unless defined?(MysqlAdapter)
spec = resolve 'mysql://foo?encoding=utf8'
assert_equal({
:adapter => "mysql",
@@ -18,6 +19,7 @@ module ActiveRecord
end
def test_url_host_db
+ skip "only if mysql is available" unless defined?(MysqlAdapter)
spec = resolve 'mysql://foo/bar?encoding=utf8'
assert_equal({
:adapter => "mysql",
@@ -27,6 +29,7 @@ module ActiveRecord
end
def test_url_port
+ skip "only if mysql is available" unless defined?(MysqlAdapter)
spec = resolve 'mysql://foo:123?encoding=utf8'
assert_equal({
:adapter => "mysql",
diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb
index 2650040a80..46d485135f 100644
--- a/activerecord/test/cases/dirty_test.rb
+++ b/activerecord/test/cases/dirty_test.rb
@@ -78,6 +78,17 @@ class DirtyTest < ActiveRecord::TestCase
assert_equal old_created_on, pirate.created_on_was
end
end
+
+ def test_setting_time_attributes_with_time_zone_field_to_itself_should_not_be_marked_as_a_change
+ in_time_zone 'Paris' do
+ target = Class.new(ActiveRecord::Base)
+ target.table_name = 'pirates'
+
+ pirate = target.create
+ pirate.created_on = pirate.created_on
+ assert !pirate.created_on_changed?
+ end
+ end
def test_time_attributes_changes_without_time_zone_by_skip
in_time_zone 'Paris' do
diff --git a/activerecord/test/cases/finder_respond_to_test.rb b/activerecord/test/cases/finder_respond_to_test.rb
index 810c1500cc..eedbaac3bd 100644
--- a/activerecord/test/cases/finder_respond_to_test.rb
+++ b/activerecord/test/cases/finder_respond_to_test.rb
@@ -80,7 +80,6 @@ class FinderRespondToTest < ActiveRecord::TestCase
private
def ensure_topic_method_is_not_cached(method_id)
- class << Topic; self; end.send(:remove_method, method_id) if Topic.public_methods.any? { |m| m.to_s == method_id.to_s }
+ class << Topic; self; end.send(:remove_method, method_id) if Topic.public_methods.include? method_id
end
-
end
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index f7ecab28ce..aa44307bc2 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -45,6 +45,12 @@ class FinderTest < ActiveRecord::TestCase
assert_raise(NoMethodError) { Topic.exists?([1,2]) }
end
+ def test_exists_does_not_select_columns_without_alias
+ assert_sql(/SELECT\W+1 AS one FROM ["`]topics["`]/i) do
+ Topic.exists?
+ end
+ end
+
def test_exists_returns_true_with_one_record_and_no_args
assert Topic.exists?
end
@@ -63,7 +69,12 @@ class FinderTest < ActiveRecord::TestCase
assert Topic.order(:id).uniq.exists?
end
- def test_does_not_exist_with_empty_table_and_no_args_given
+ def test_exists_with_includes_limit_and_empty_result
+ assert !Topic.includes(:replies).limit(0).exists?
+ assert !Topic.includes(:replies).limit(1).where('0 = 1').exists?
+ end
+
+ def test_exists_with_empty_table_and_no_args_given
Topic.delete_all
assert !Topic.exists?
end
@@ -629,7 +640,7 @@ class FinderTest < ActiveRecord::TestCase
def test_dynamic_finder_on_one_attribute_with_conditions_returns_same_results_after_caching
# ensure this test can run independently of order
- class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
+ class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.include?(:find_by_credit_limit)
a = Account.where('firm_id = ?', 6).find_by_credit_limit(50)
assert_equal a, Account.where('firm_id = ?', 6).find_by_credit_limit(50) # find_by_credit_limit has been cached
end
diff --git a/activerecord/test/cases/mass_assignment_security_test.rb b/activerecord/test/cases/mass_assignment_security_test.rb
index 2f98d3c646..214546802a 100644
--- a/activerecord/test/cases/mass_assignment_security_test.rb
+++ b/activerecord/test/cases/mass_assignment_security_test.rb
@@ -95,7 +95,11 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase
end
def test_mass_assigning_does_not_choke_on_nil
- Firm.new.assign_attributes(nil)
+ assert_nil Firm.new.assign_attributes(nil)
+ end
+
+ def test_mass_assigning_does_not_choke_on_empty_hash
+ assert_nil Firm.new.assign_attributes({})
end
def test_assign_attributes_uses_default_role_when_no_role_is_provided
@@ -878,4 +882,26 @@ class MassAssignmentSecurityNestedAttributesTest < ActiveRecord::TestCase
assert_all_attributes(person.best_friends.first)
end
+ def test_mass_assignment_options_are_reset_after_exception
+ person = NestedPerson.create!({ :first_name => 'David', :gender => 'm' }, :as => :admin)
+ person.create_best_friend!({ :first_name => 'Jeremy', :gender => 'm' }, :as => :admin)
+
+ attributes = { :best_friend_attributes => { :comments => 'rides a sweet bike' } }
+ assert_raises(RuntimeError) { person.assign_attributes(attributes, :as => :admin) }
+ assert_equal 'm', person.best_friend.gender
+
+ person.best_friend_attributes = { :gender => 'f' }
+ assert_equal 'm', person.best_friend.gender
+ end
+
+ def test_mass_assignment_options_are_nested_correctly
+ person = NestedPerson.create!({ :first_name => 'David', :gender => 'm' }, :as => :admin)
+ person.create_best_friend!({ :first_name => 'Jeremy', :gender => 'm' }, :as => :admin)
+
+ attributes = { :best_friend_first_name => 'Josh', :best_friend_attributes => { :gender => 'f' } }
+ person.assign_attributes(attributes, :as => :admin)
+ assert_equal 'Josh', person.best_friend.first_name
+ assert_equal 'f', person.best_friend.gender
+ end
+
end
diff --git a/activerecord/test/cases/migration/column_attributes_test.rb b/activerecord/test/cases/migration/column_attributes_test.rb
index 18f8d82bfe..3014bbe273 100644
--- a/activerecord/test/cases/migration/column_attributes_test.rb
+++ b/activerecord/test/cases/migration/column_attributes_test.rb
@@ -174,7 +174,7 @@ module ActiveRecord
assert_not_equal "Z", bob.moment_of_truth.zone
# US/Eastern is -5 hours from GMT
assert_equal Rational(-5, 24), bob.moment_of_truth.offset
- assert_match(/\A-05:?00\Z/, bob.moment_of_truth.zone) #ruby 1.8.6 uses HH:MM, prior versions use HHMM
+ assert_match(/\A-05:00\Z/, bob.moment_of_truth.zone)
assert_equal DateTime::ITALY, bob.moment_of_truth.start
end
end
diff --git a/activerecord/test/cases/migration/references_index_test.rb b/activerecord/test/cases/migration/references_index_test.rb
index 8ab1c59724..264a99f9ce 100644
--- a/activerecord/test/cases/migration/references_index_test.rb
+++ b/activerecord/test/cases/migration/references_index_test.rb
@@ -51,6 +51,8 @@ module ActiveRecord
end
def test_creates_polymorphic_index
+ return skip "Oracle Adapter does not support foreign keys if :polymorphic => true is used" if current_adapter? :OracleAdapter
+
connection.create_table table_name do |t|
t.references :foo, :polymorphic => true, :index => true
end
@@ -86,6 +88,7 @@ module ActiveRecord
end
def test_creates_polymorphic_index_for_existing_table
+ return skip "Oracle Adapter does not support foreign keys if :polymorphic => true is used" if current_adapter? :OracleAdapter
connection.create_table table_name
connection.change_table table_name do |t|
t.references :foo, :polymorphic => true, :index => true
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index 5d1bad0d54..3c0d2b18d9 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -56,6 +56,21 @@ class MigrationTest < ActiveRecord::TestCase
Person.reset_column_information
end
+ def test_migrator_versions
+ migrations_path = MIGRATIONS_ROOT + "/valid"
+ ActiveRecord::Migrator.migrations_paths = migrations_path
+
+ ActiveRecord::Migrator.up(migrations_path)
+ assert_equal 3, ActiveRecord::Migrator.current_version
+ assert_equal 3, ActiveRecord::Migrator.last_version
+ assert_equal false, ActiveRecord::Migrator.needs_migration?
+
+ ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid")
+ assert_equal 0, ActiveRecord::Migrator.current_version
+ assert_equal 3, ActiveRecord::Migrator.last_version
+ assert_equal true, ActiveRecord::Migrator.needs_migration?
+ end
+
def test_create_table_with_force_true_does_not_drop_nonexisting_table
if Person.connection.table_exists?(:testings2)
Person.connection.drop_table :testings2
@@ -523,7 +538,7 @@ if ActiveRecord::Base.connection.supports_bulk_alter?
# One query for columns (delete_me table)
# One query for primary key (delete_me table)
# One query to do the bulk change
- assert_queries(3) do
+ assert_queries(3, :ignore_none => true) do
with_bulk_change_table do |t|
t.change :name, :string, :default => 'NONAME'
t.change :birthdate, :datetime
diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb
index bf825c002a..c886160af3 100644
--- a/activerecord/test/cases/named_scope_test.rb
+++ b/activerecord/test/cases/named_scope_test.rb
@@ -19,7 +19,6 @@ class NamedScopeTest < ActiveRecord::TestCase
end
def test_found_items_are_cached
- Topic.columns
all_posts = Topic.base
assert_queries(1) do
@@ -46,6 +45,15 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_equal Topic.average(:replies_count), Topic.base.average(:replies_count)
end
+ def test_method_missing_priority_when_delegating
+ klazz = Class.new(ActiveRecord::Base) do
+ self.table_name = "topics"
+ scope :since, Proc.new { where('written_on >= ?', Time.now - 1.day) }
+ scope :to, Proc.new { where('written_on <= ?', Time.now) }
+ end
+ assert_equal klazz.to.since.all, klazz.since.to.all
+ end
+
def test_scope_should_respond_to_own_methods_and_methods_of_the_proxy
assert Topic.approved.respond_to?(:limit)
assert Topic.approved.respond_to?(:count)
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index 0933a4ff3d..fecdf2b705 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -305,6 +305,13 @@ class PersistencesTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
end
+ def test_destroy!
+ topic = Topic.find(1)
+ assert_equal topic, topic.destroy!, 'topic.destroy! did not return self'
+ assert topic.frozen?, 'topic not frozen after destroy!'
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
+ end
+
def test_record_not_found_exception
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(99999) }
end
diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb
index a712e5f689..08f655d7fa 100644
--- a/activerecord/test/cases/query_cache_test.rb
+++ b/activerecord/test/cases/query_cache_test.rb
@@ -151,16 +151,11 @@ class QueryCacheTest < ActiveRecord::TestCase
end
def test_cache_does_not_wrap_string_results_in_arrays
- if current_adapter?(:SQLite3Adapter)
- require 'sqlite3/version'
- sqlite3_version = RUBY_PLATFORM =~ /java/ ? Jdbc::SQLite3::VERSION : SQLite3::VERSION
- end
-
Task.cache do
# Oracle adapter returns count() as Fixnum or Float
if current_adapter?(:OracleAdapter)
assert_kind_of Numeric, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
- elsif current_adapter?(:SQLite3Adapter) && sqlite3_version > '1.2.5' || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter)
+ elsif current_adapter?(:SQLite3Adapter) || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter)
# Future versions of the sqlite3 adapter will return numeric
assert_instance_of Fixnum,
Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb
index d5c0b351aa..33cd6020a1 100644
--- a/activerecord/test/models/person.rb
+++ b/activerecord/test/models/person.rb
@@ -88,6 +88,25 @@ class TightDescendant < TightPerson; end
class RichPerson < ActiveRecord::Base
self.table_name = 'people'
-
+
has_and_belongs_to_many :treasures, :join_table => 'peoples_treasures'
end
+
+class NestedPerson < ActiveRecord::Base
+ self.table_name = 'people'
+
+ attr_accessible :first_name, :best_friend_first_name, :best_friend_attributes
+ attr_accessible :first_name, :gender, :comments, :as => :admin
+ attr_accessible :best_friend_attributes, :best_friend_first_name, :as => :admin
+
+ has_one :best_friend, :class_name => 'NestedPerson', :foreign_key => :best_friend_id
+ accepts_nested_attributes_for :best_friend, :update_only => true
+
+ def comments=(new_comments)
+ raise RuntimeError
+ end
+
+ def best_friend_first_name=(new_name)
+ assign_attributes({ :best_friend_attributes => { :first_name => new_name } })
+ end
+end \ No newline at end of file
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index af9e8c27c7..804336da91 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,5 +1,19 @@
## Rails 4.0.0 (unreleased) ##
+* Remove obsolete and unused `require_association` method from dependencies. *fxn*
+
+* Add `:instance_accessor` option for `config_accessor`.
+
+ class User
+ include ActiveSupport::Configurable
+ config_accessor :allowed_access, instance_accessor: false
+ end
+
+ User.new.allowed_access = true # => NoMethodError
+ User.new.allowed_access # => NoMethodError
+
+ *Francesco Rodriguez*
+
* ActionView::Helpers::NumberHelper methods have been moved to ActiveSupport::NumberHelper and are now available via
Numeric#to_s. Numeric#to_s now accepts the formatting options :phone, :currency, :percentage, :delimited,
:rounded, :human, and :human_size. *Andrew Mutz*
diff --git a/activesupport/lib/active_support/configurable.rb b/activesupport/lib/active_support/configurable.rb
index a8aa53a80f..4fb8c7af3f 100644
--- a/activesupport/lib/active_support/configurable.rb
+++ b/activesupport/lib/active_support/configurable.rb
@@ -37,29 +37,77 @@ module ActiveSupport
yield config
end
- # Allows you to add shortcut so that you don't have to refer to attribute through config.
- # Also look at the example for config to contrast.
+ # Allows you to add shortcut so that you don't have to refer to attribute
+ # through config. Also look at the example for config to contrast.
+ #
+ # Defines both class and instance config accessors.
#
# class User
# include ActiveSupport::Configurable
# config_accessor :allowed_access
# end
#
+ # User.allowed_access # => nil
+ # User.allowed_access = false
+ # User.allowed_access # => false
+ #
# user = User.new
+ # user.allowed_access # => false
# user.allowed_access = true
# user.allowed_access # => true
#
+ # User.allowed_access # => false
+ #
+ # The attribute name must be a valid method name in Ruby.
+ #
+ # class User
+ # include ActiveSupport::Configurable
+ # config_accessor :"1_Badname"
+ # end
+ # # => NameError: invalid config attribute name
+ #
+ # To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
+ # To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
+ #
+ # class User
+ # include ActiveSupport::Configurable
+ # config_accessor :allowed_access, instance_reader: false, instance_writer: false
+ # end
+ #
+ # User.allowed_access = false
+ #  User.allowed_access # => false
+ #
+ # User.new.allowed_access = true # => NoMethodError
+ # User.new.allowed_access # => NoMethodError
+ #
+ # Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
+ #
+ # class User
+ # include ActiveSupport::Configurable
+ # config_accessor :allowed_access, instance_accessor: false
+ # end
+ #
+ # User.allowed_access = false
+ #  User.allowed_access # => false
+ #
+ # User.new.allowed_access = true # => NoMethodError
+ # User.new.allowed_access # => NoMethodError
def config_accessor(*names)
options = names.extract_options!
names.each do |name|
+ raise NameError.new('invalid config attribute name') unless name =~ /^[_A-Za-z]\w*$/
+
reader, line = "def #{name}; config.#{name}; end", __LINE__
writer, line = "def #{name}=(value); config.#{name} = value; end", __LINE__
singleton_class.class_eval reader, __FILE__, line
singleton_class.class_eval writer, __FILE__, line
- class_eval reader, __FILE__, line unless options[:instance_reader] == false
- class_eval writer, __FILE__, line unless options[:instance_writer] == false
+
+ unless options[:instance_accessor] == false
+ class_eval reader, __FILE__, line unless options[:instance_reader] == false
+ class_eval writer, __FILE__, line unless options[:instance_writer] == false
+ end
end
end
end
@@ -79,7 +127,6 @@ module ActiveSupport
#
# user.config.allowed_access # => true
# user.config.level # => 1
- #
def config
@_config ||= self.class.config.inheritable_copy
end
diff --git a/activesupport/lib/active_support/core_ext/date_time/conversions.rb b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
index 19925198c0..13d659f52a 100644
--- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
@@ -39,7 +39,7 @@ class DateTime
to_default_s
end
end
- alias_method :to_default_s, :to_s unless (instance_methods(false) & [:to_s, 'to_s']).empty?
+ alias_method :to_default_s, :to_s if instance_methods(false).include?(:to_s)
alias_method :to_s, :to_formatted_s
#
diff --git a/activesupport/lib/active_support/core_ext/load_error.rb b/activesupport/lib/active_support/core_ext/load_error.rb
index 8bdfa0c5bc..fe24f3716d 100644
--- a/activesupport/lib/active_support/core_ext/load_error.rb
+++ b/activesupport/lib/active_support/core_ext/load_error.rb
@@ -6,12 +6,14 @@ class LoadError
/^cannot load such file -- (.+)$/i,
]
- def path
- @path ||= begin
- REGEXPS.find do |regex|
- message =~ regex
+ unless method_defined?(:path)
+ def path
+ @path ||= begin
+ REGEXPS.find do |regex|
+ message =~ regex
+ end
+ $1
end
- $1
end
end
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb
index fbef27c76a..39a1240c61 100644
--- a/activesupport/lib/active_support/core_ext/module/delegation.rb
+++ b/activesupport/lib/active_support/core_ext/module/delegation.rb
@@ -107,7 +107,6 @@ class Module
raise ArgumentError, 'Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter).'
end
- to = to.to_s
prefix, allow_nil = options.values_at(:prefix, :allow_nil)
if prefix == true && to =~ /^[^a-z_]/
@@ -125,8 +124,6 @@ class Module
line = line.to_i
methods.each do |method|
- method = method.to_s
-
# Attribute writer methods only accept one argument. Makes sure []=
# methods still accept two arguments.
definition = (method =~ /[^\]]=$/) ? 'arg' : '*args, &block'
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index 66f3af7002..c9071a73d8 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -168,8 +168,6 @@ module ActiveSupport #:nodoc:
end
end
- # Use const_missing to autoload associations so we don't have to
- # require_association when using single-table inheritance.
def const_missing(const_name, nesting = nil)
klass_name = name.presence || "Object"
@@ -220,11 +218,7 @@ module ActiveSupport #:nodoc:
raise ArgumentError, "the file name must be a String -- you passed #{file_name.inspect}"
end
- Dependencies.depend_on(file_name, false, message)
- end
-
- def require_association(file_name)
- Dependencies.associate_with(file_name)
+ Dependencies.depend_on(file_name, message)
end
def load_dependency(file)
@@ -306,20 +300,15 @@ module ActiveSupport #:nodoc:
mechanism == :load
end
- def depend_on(file_name, swallow_load_errors = false, message = "No such file to load -- %s.rb")
+ def depend_on(file_name, message = "No such file to load -- %s.rb")
path = search_for_file(file_name)
require_or_load(path || file_name)
rescue LoadError => load_error
- unless swallow_load_errors
- if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
- raise LoadError.new(message % file_name).copy_blame!(load_error)
- end
- raise
+ if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
+ load_error.message.replace(message % file_name)
+ load_error.copy_blame!(load_error)
end
- end
-
- def associate_with(file_name)
- depend_on(file_name, true)
+ raise
end
def clear
diff --git a/activesupport/lib/active_support/file_update_checker.rb b/activesupport/lib/active_support/file_update_checker.rb
index 8860636168..48c39d9370 100644
--- a/activesupport/lib/active_support/file_update_checker.rb
+++ b/activesupport/lib/active_support/file_update_checker.rb
@@ -35,22 +35,11 @@ module ActiveSupport
# have directories as keys and the value is an array of extensions to be
# watched under that directory.
#
- # This method must also receive a block that will be called once a path changes.
- #
- # == Implementation details
- #
- # This particular implementation checks for added, updated, and removed
- # files. Directories lookup are compiled to a glob for performance.
- # Therefore, while someone can add new files to the +files+ array after
- # initialization (and parts of Rails do depend on this feature), adding
- # new directories after initialization is not supported.
- #
- # Notice that other objects that implement the FileUpdateChecker API may
- # not even allow new files to be added after initialization. If this
- # is the case, we recommend freezing the +files+ after initialization to
- # avoid changes that won't make effect.
+ # This method must also receive a block that will be called once a path
+ # changes. The array of files and list of directories cannot be changed
+ # after FileUpdateChecker has been initialized.
def initialize(files, dirs={}, &block)
- @files = files
+ @files = files.freeze
@glob = compile_glob(dirs)
@block = block
diff --git a/activesupport/lib/active_support/i18n_railtie.rb b/activesupport/lib/active_support/i18n_railtie.rb
index bbeb8d82c6..f67b221024 100644
--- a/activesupport/lib/active_support/i18n_railtie.rb
+++ b/activesupport/lib/active_support/i18n_railtie.rb
@@ -9,25 +9,6 @@ module I18n
config.i18n.load_path = []
config.i18n.fallbacks = ActiveSupport::OrderedOptions.new
- def self.reloader
- @reloader ||= ActiveSupport::FileUpdateChecker.new(reloader_paths){ I18n.reload! }
- end
-
- def self.reloader_paths
- @reloader_paths ||= []
- end
-
- # Add <tt>I18n::Railtie.reloader</tt> to ActionDispatch callbacks. Since, at this
- # point, no path was added to the reloader, I18n.reload! is not triggered
- # on to_prepare callbacks. This will only happen on the config.after_initialize
- # callback below.
- initializer "i18n.callbacks" do |app|
- app.reloaders << I18n::Railtie.reloader
- ActionDispatch::Reloader.to_prepare do
- I18n::Railtie.reloader.execute_if_updated
- end
- end
-
# Set the i18n configuration after initialization since a lot of
# configuration is still usually done in application initializers.
config.after_initialize do |app|
@@ -63,7 +44,9 @@ module I18n
init_fallbacks(fallbacks) if fallbacks && validate_fallbacks(fallbacks)
- reloader_paths.concat I18n.load_path
+ reloader = ActiveSupport::FileUpdateChecker.new(I18n.load_path.dup){ I18n.reload! }
+ app.reloaders << reloader
+ ActionDispatch::Reloader.to_prepare { reloader.execute_if_updated }
reloader.execute
@i18n_inited = true
diff --git a/activesupport/lib/active_support/log_subscriber.rb b/activesupport/lib/active_support/log_subscriber.rb
index d2a6e1bd82..bea2ca17f1 100644
--- a/activesupport/lib/active_support/log_subscriber.rb
+++ b/activesupport/lib/active_support/log_subscriber.rb
@@ -61,7 +61,7 @@ module ActiveSupport
@@flushable_loggers = nil
log_subscriber.public_methods(false).each do |event|
- next if 'call' == event.to_s
+ next if :call == event
notifier.subscribe("#{event}.#{namespace}", log_subscriber)
end
@@ -114,7 +114,7 @@ module ActiveSupport
#
def color(text, color, bold=false)
return text unless colorize_logging
- color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol)
+ color = self.class.const_get(color.upcase) if color.is_a?(Symbol)
bold = bold ? BOLD : ""
"#{bold}#{color}#{text}#{CLEAR}"
end
diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb
index 87b1d76026..47336d2143 100644
--- a/activesupport/lib/active_support/multibyte/chars.rb
+++ b/activesupport/lib/active_support/multibyte/chars.rb
@@ -133,7 +133,7 @@ module ActiveSupport #:nodoc:
# "ÉL QUE SE ENTERÓ".mb_chars.titleize # => "Él Que Se Enteró"
# "日本語".mb_chars.titleize # => "日本語"
def titleize
- chars(downcase.to_s.gsub(/\b('?[\S])/u) { Unicode.upcase($1)})
+ chars(downcase.to_s.gsub(/\b('?\S)/u) { Unicode.upcase($1)})
end
alias_method :titlecase, :titleize
diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb
index 9a52c916ec..14ceb7072e 100644
--- a/activesupport/lib/active_support/test_case.rb
+++ b/activesupport/lib/active_support/test_case.rb
@@ -22,8 +22,7 @@ module ActiveSupport
end
Assertion = MiniTest::Assertion
- alias_method :method_name, :name if method_defined? :name
- alias_method :method_name, :__name__ if method_defined? :__name__
+ alias_method :method_name, :__name__
$tags = {}
def self.for_tag(tag)
diff --git a/activesupport/lib/active_support/testing/performance.rb b/activesupport/lib/active_support/testing/performance.rb
index 517926c74d..a6c57cd0ff 100644
--- a/activesupport/lib/active_support/testing/performance.rb
+++ b/activesupport/lib/active_support/testing/performance.rb
@@ -1,5 +1,4 @@
require 'fileutils'
-require 'rails/version'
require 'active_support/concern'
require 'active_support/core_ext/class/delegating_attributes'
require 'active_support/core_ext/string/inflections'
@@ -149,26 +148,20 @@ module ActiveSupport
end
def environment
- unless defined? @env
- app = "#{$1}.#{$2}" if File.directory?('.git') && `git branch -v` =~ /^\* (\S+)\s+(\S+)/
-
- rails = Rails::VERSION::STRING
- if File.directory?('vendor/rails/.git')
- Dir.chdir('vendor/rails') do
- rails += ".#{$1}.#{$2}" if `git branch -v` =~ /^\* (\S+)\s+(\S+)/
- end
- end
-
- ruby = "#{RUBY_ENGINE}-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL}"
-
- @env = [app, rails, ruby, RUBY_PLATFORM] * ','
- end
-
- @env
+ @env ||= [].tap do |env|
+ env << "#{$1}.#{$2}" if File.directory?('.git') && `git branch -v` =~ /^\* (\S+)\s+(\S+)/
+ env << rails_version if defined?(Rails::VERSION::STRING)
+ env << "#{RUBY_ENGINE}-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL}"
+ env << RUBY_PLATFORM
+ end.join(',')
end
protected
- HEADER = 'measurement,created_at,app,rails,ruby,platform'
+ if defined?(Rails::VERSION::STRING)
+ HEADER = 'measurement,created_at,app,rails,ruby,platform'
+ else
+ HEADER = 'measurement,created_at,app,ruby,platform'
+ end
def with_output_file
fname = output_filename
@@ -186,6 +179,18 @@ module ActiveSupport
def output_filename
"#{super}.csv"
end
+
+ def rails_version
+ "rails-#{Rails::VERSION::STRING}#{rails_branch}"
+ end
+
+ def rails_branch
+ if File.directory?('vendor/rails/.git')
+ Dir.chdir('vendor/rails') do
+ ".#{$1}.#{$2}" if `git branch -v` =~ /^\* (\S+)\s+(\S+)/
+ end
+ end
+ end
end
module Metrics
diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb
index 88e18f6fff..88f9acb588 100644
--- a/activesupport/lib/active_support/xml_mini.rb
+++ b/activesupport/lib/active_support/xml_mini.rb
@@ -83,7 +83,7 @@ module ActiveSupport
if name.is_a?(Module)
@backend = name
else
- require "active_support/xml_mini/#{name.to_s.downcase}"
+ require "active_support/xml_mini/#{name.downcase}"
@backend = ActiveSupport.const_get("XmlMini_#{name}")
end
end
diff --git a/activesupport/test/configurable_test.rb b/activesupport/test/configurable_test.rb
index 2e5ea2c360..da7729d066 100644
--- a/activesupport/test/configurable_test.rb
+++ b/activesupport/test/configurable_test.rb
@@ -5,7 +5,8 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
class Parent
include ActiveSupport::Configurable
config_accessor :foo
- config_accessor :bar, :instance_reader => false, :instance_writer => false
+ config_accessor :bar, instance_reader: false, instance_writer: false
+ config_accessor :baz, instance_accessor: false
end
class Child < Parent
@@ -19,13 +20,13 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
end
test "adds a configuration hash" do
- assert_equal({ :foo => :bar }, Parent.config)
+ assert_equal({ foo: :bar }, Parent.config)
end
test "adds a configuration hash to a module as well" do
mixin = Module.new { include ActiveSupport::Configurable }
mixin.config.foo = :bar
- assert_equal({ :foo => :bar }, mixin.config)
+ assert_equal({ foo: :bar }, mixin.config)
end
test "configuration hash is inheritable" do
@@ -39,8 +40,12 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
test "configuration accessors is not available on instance" do
instance = Parent.new
+
assert !instance.respond_to?(:bar)
assert !instance.respond_to?(:bar=)
+
+ assert !instance.respond_to?(:baz)
+ assert !instance.respond_to?(:baz=)
end
test "configuration hash is available on instance" do
@@ -71,6 +76,15 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
assert_method_defined child.new.config, :bar
end
+ test "should raise name error if attribute name is invalid" do
+ assert_raises NameError do
+ Class.new do
+ include ActiveSupport::Configurable
+ config_accessor "invalid attribute name"
+ end
+ end
+ end
+
def assert_method_defined(object, method)
methods = object.public_methods.map(&:to_s)
assert methods.include?(method.to_s), "Expected #{methods.inspect} to include #{method.to_s.inspect}"
@@ -80,4 +94,4 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
methods = object.public_methods.map(&:to_s)
assert !methods.include?(method.to_s), "Expected #{methods.inspect} to not include #{method.to_s.inspect}"
end
-end
+end \ No newline at end of file
diff --git a/activesupport/test/core_ext/kernel_test.rb b/activesupport/test/core_ext/kernel_test.rb
index 99e4506be7..439bc87323 100644
--- a/activesupport/test/core_ext/kernel_test.rb
+++ b/activesupport/test/core_ext/kernel_test.rb
@@ -96,7 +96,6 @@ class KernelDebuggerTest < ActiveSupport::TestCase
end
def test_debugger_not_available_message_to_rails_logger
- Object.send(:remove_const, :Rails) if Object.const_defined?(:Rails)
rails = Class.new do
def self.logger
@logger ||= MockStdErr.new
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index 081e6a16fd..69829bcda5 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -39,6 +39,19 @@ class DependenciesTest < ActiveSupport::TestCase
with_loading 'autoloading_fixtures', &block
end
+ def test_depend_on_path
+ skip "LoadError#path does not exist" if RUBY_VERSION < '2.0.0'
+
+ expected = assert_raises(LoadError) do
+ Kernel.require 'omgwtfbbq'
+ end
+
+ e = assert_raises(LoadError) do
+ ActiveSupport::Dependencies.depend_on 'omgwtfbbq'
+ end
+ assert_equal expected.path, e.path
+ end
+
def test_tracking_loaded_files
require_dependency 'dependencies/service_one'
require_dependency 'dependencies/service_two'
@@ -60,10 +73,6 @@ class DependenciesTest < ActiveSupport::TestCase
assert_raise(MissingSourceFile) { require_dependency("missing_service") }
end
- def test_missing_association_raises_nothing
- assert_nothing_raised { require_association("missing_model") }
- end
-
def test_dependency_which_raises_exception_isnt_added_to_loaded_set
with_loading do
filename = 'dependencies/raises_exception'
diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb
index 11506554a9..2473cec384 100644
--- a/activesupport/test/test_test.rb
+++ b/activesupport/test/test_test.rb
@@ -15,68 +15,64 @@ class AssertDifferenceTest < ActiveSupport::TestCase
@object.num = 0
end
- if lambda { }.respond_to?(:binding)
- def test_assert_no_difference
- assert_no_difference '@object.num' do
- # ...
- end
+ def test_assert_no_difference
+ assert_no_difference '@object.num' do
+ # ...
end
+ end
- def test_assert_difference
- assert_difference '@object.num', +1 do
- @object.increment
- end
+ def test_assert_difference
+ assert_difference '@object.num', +1 do
+ @object.increment
end
+ end
- def test_assert_difference_with_implicit_difference
- assert_difference '@object.num' do
- @object.increment
- end
+ def test_assert_difference_with_implicit_difference
+ assert_difference '@object.num' do
+ @object.increment
end
+ end
- def test_arbitrary_expression
- assert_difference '@object.num + 1', +2 do
- @object.increment
- @object.increment
- end
+ def test_arbitrary_expression
+ assert_difference '@object.num + 1', +2 do
+ @object.increment
+ @object.increment
end
+ end
- def test_negative_differences
- assert_difference '@object.num', -1 do
- @object.decrement
- end
+ def test_negative_differences
+ assert_difference '@object.num', -1 do
+ @object.decrement
end
+ end
- def test_expression_is_evaluated_in_the_appropriate_scope
- silence_warnings do
- local_scope = local_scope = 'foo'
- assert_difference('local_scope; @object.num') { @object.increment }
- end
+ def test_expression_is_evaluated_in_the_appropriate_scope
+ silence_warnings do
+ local_scope = local_scope = 'foo'
+ assert_difference('local_scope; @object.num') { @object.increment }
end
+ end
- def test_array_of_expressions
- assert_difference [ '@object.num', '@object.num + 1' ], +1 do
- @object.increment
- end
+ def test_array_of_expressions
+ assert_difference [ '@object.num', '@object.num + 1' ], +1 do
+ @object.increment
end
+ end
- def test_array_of_expressions_identify_failure
- assert_raises(MiniTest::Assertion) do
- assert_difference ['@object.num', '1 + 1'] do
- @object.increment
- end
+ def test_array_of_expressions_identify_failure
+ assert_raises(MiniTest::Assertion) do
+ assert_difference ['@object.num', '1 + 1'] do
+ @object.increment
end
end
+ end
- def test_array_of_expressions_identify_failure_when_message_provided
- assert_raises(MiniTest::Assertion) do
- assert_difference ['@object.num', '1 + 1'], 1, 'something went wrong' do
- @object.increment
- end
+ def test_array_of_expressions_identify_failure_when_message_provided
+ assert_raises(MiniTest::Assertion) do
+ assert_difference ['@object.num', '1 + 1'], 1, 'something went wrong' do
+ @object.increment
end
end
- else
- def default_test; end
end
end
diff --git a/activesupport/test/testing/performance_test.rb b/activesupport/test/testing/performance_test.rb
index 74d7dae9e7..53073cb8db 100644
--- a/activesupport/test/testing/performance_test.rb
+++ b/activesupport/test/testing/performance_test.rb
@@ -11,7 +11,7 @@ module ActiveSupport
assert_equal "1", amount_metric.format(1.23)
assert_equal "40,000,000", amount_metric.format(40000000)
end
-
+
def test_time_format
time_metric = ActiveSupport::Testing::Performance::Metrics[:time].new
assert_equal "0 ms", time_metric.format(0)
@@ -21,7 +21,7 @@ module ActiveSupport
assert_equal "40000.00 sec", time_metric.format(40000)
assert_equal "-5000 ms", time_metric.format(-5)
end
-
+
def test_space_format
space_metric = ActiveSupport::Testing::Performance::Metrics[:digital_information_unit].new
assert_equal "0 Bytes", space_metric.format(0)
@@ -35,6 +35,25 @@ module ActiveSupport
assert_equal "91 TB", space_metric.format(10**14)
assert_equal "910000 TB", space_metric.format(10**18)
end
+
+ def test_environment_format_without_rails
+ metric = ActiveSupport::Testing::Performance::Metrics[:time].new
+ benchmarker = ActiveSupport::Testing::Performance::Benchmarker.new(self, metric)
+ assert_equal "#{RUBY_ENGINE}-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL},#{RUBY_PLATFORM}", benchmarker.environment
+ end
+
+ def test_environment_format_with_rails
+ rails, version = Module.new, Module.new
+ version.const_set :STRING, "4.0.0"
+ rails.const_set :VERSION, version
+ Object.const_set :Rails, rails
+
+ metric = ActiveSupport::Testing::Performance::Metrics[:time].new
+ benchmarker = ActiveSupport::Testing::Performance::Benchmarker.new(self, metric)
+ assert_equal "rails-4.0.0,#{RUBY_ENGINE}-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL},#{RUBY_PLATFORM}", benchmarker.environment
+ ensure
+ Object.send :remove_const, :Rails
+ end
end
end
end \ No newline at end of file
diff --git a/guides/source/active_model_basics.textile b/guides/source/active_model_basics.textile
index d373f4ac85..7cafff2ad8 100644
--- a/guides/source/active_model_basics.textile
+++ b/guides/source/active_model_basics.textile
@@ -187,7 +187,7 @@ class Person
attr_accessor :name, :email, :token
validates :name, :presence => true
- validates_format_of :email, :with => /^([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})$/i
+ validates_format_of :email, :with => /\A([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})\z/i
validates! :token, :presence => true
end
diff --git a/guides/source/contributing_to_ruby_on_rails.textile b/guides/source/contributing_to_ruby_on_rails.textile
index 8e14297235..b52cd6c6b6 100644
--- a/guides/source/contributing_to_ruby_on_rails.textile
+++ b/guides/source/contributing_to_ruby_on_rails.textile
@@ -190,6 +190,8 @@ $ rake postgresql:build_databases
NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation.
+NOTE: You'll see the following warning (or localized warning) during activating HStore extension in PostgreSQL 9.1.x or earlier: "WARNING: => is deprecated as an operator".
+
If you’re using another database, check the files under +activerecord/test/connections+ for default connection information. You can edit these files to provide different credentials on your machine if you must, but obviously you should not push any such changes back to Rails.
You can now run the tests as you did for +sqlite3+. The tasks are respectively
diff --git a/guides/source/security.textile b/guides/source/security.textile
index 0931dd6393..626d6fa508 100644
--- a/guides/source/security.textile
+++ b/guides/source/security.textile
@@ -588,26 +588,43 @@ h4. Regular Expressions
INFO: _A common pitfall in Ruby's regular expressions is to match the string's beginning and end by ^ and $, instead of \A and \z._
-Ruby uses a slightly different approach than many other languages to match the end and the beginning of a string. That is why even many Ruby and Rails books make this wrong. So how is this a security threat? Imagine you have a File model and you validate the file name by a regular expression like this:
+Ruby uses a slightly different approach than many other languages to match the end and the beginning of a string. That is why even many Ruby and Rails books make this wrong. So how is this a security threat? Say you wanted to loosely validate a URL field and you used a simple regular expression like this:
<ruby>
-class File < ActiveRecord::Base
- validates :name, :format => /^[\w\.\-\<plus>]<plus>$/
-end
+ /^https?:\/\/[^\n]+$/i
</ruby>
-This means, upon saving, the model will validate the file name to consist only of alphanumeric characters, dots, + and -. And the programmer added ^ and $ so that file name will contain these characters from the beginning to the end of the string. However, _(highlight)in Ruby ^ and $ matches the *line* beginning and line end_. And thus a file name like this passes the filter without problems:
+This may work fine in some languages. However, _(highlight)in Ruby ^ and $ match the *line* beginning and line end_. And thus a URL like this passes the filter without problems:
<plain>
-file.txt%0A<script>alert('hello')</script>
+javascript:exploit_code();/*
+http://hi.com
+*/
</plain>
-Whereas %0A is a line feed in URL encoding, so Rails automatically converts it to "file.txt\n&lt;script&gt;alert('hello')&lt;/script&gt;". This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read:
+This URL passes the filter because the regular expression matches – the second line, the rest does not matter. Now imagine we had a view that showed the URL like this:
+
+<ruby>
+ link_to "Homepage", @user.homepage
+</ruby>
+
+The link looks innocent to visitors, but when it's clicked, it will execute the javascript function "exploit_code" or any other javascript the attacker provides.
+
+To fix the regular expression, \A and \z should be used instead of ^ and $, like so:
<ruby>
-/\A[\w\.\-\<plus>]<plus>\z/
+ /\Ahttps?:\/\/[^\n]+\z/i
</ruby>
+Since this is a frequent mistake, the format validator (validates_format_of) now raises an exception if the provided regular expression starts with ^ or ends with $. If you do need to use ^ and $ instead of \A and \z (which is rare), you can set the :multiline option to true, like so:
+
+<ruby>
+ # content should include a line "Meanwhile" anywhere in the string
+ validates :content, :format => { :with => /^Meanwhile$/, :multiline => true }
+</ruby>
+
+Note that this only protects you against the most common mistake when using the format validator - you always need to keep in mind that ^ and $ match the *line* beginning and line end in Ruby, and not the beginning and end of a string.
+
h4. Privilege Escalation
WARNING: _Changing a single parameter may give the user unauthorized access. Remember that every parameter may be changed, no matter how much you hide or obfuscate it._
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index a6abe5ee97..e19aa68407 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,5 +1,7 @@
## Rails 4.0.0 (unreleased) ##
+* Set `config.active_record.migration_error` to `:page_load` for development *Richard Schneeman*
+
* Add runner to Rails::Railtie as a hook called just after runner starts. *José Valim & kennyj*
* Add `/rails/info/routes` path, displays same information as `rake routes` *Richard Schneeman & Andrew White*
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index 63703176de..b61a5fc69d 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -84,10 +84,11 @@ module Rails
end
def namespaced_class_path
- @namespaced_class_path ||= begin
- namespace_path = namespace.name.split("::").map {|m| m.underscore }
- namespace_path + @class_path
- end
+ @namespaced_class_path ||= [namespaced_path] + @class_path
+ end
+
+ def namespaced_path
+ @namespaced_path ||= namespace.name.split("::").map {|m| m.underscore }[0]
end
def class_name
@@ -134,7 +135,7 @@ module Rails
end
def route_url
- @route_url ||= class_path.collect{|dname| "/" + dname }.join('') + "/" + plural_file_name
+ @route_url ||= class_path.collect {|dname| "/" + dname }.join + "/" + plural_file_name
end
# Tries to retrieve the application name or simple return application.
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
index 24bcec854c..01f9396403 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -26,6 +26,9 @@
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL).
config.active_record.auto_explain_threshold_in_seconds = 0.5
+
+ # Raise an error on page load if there are pending migrations
+ config.active_record.migration_error = :page_load
<%- end -%>
<%- unless options.skip_sprockets? -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt
index 19cbf0e4f1..280f777cc0 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt
@@ -9,8 +9,8 @@ ActiveSupport.on_load(:action_controller) do
end
<%- unless options.skip_active_record? -%>
-# Disable root element in JSON by default.
-ActiveSupport.on_load(:active_record) do
- self.include_root_in_json = false
-end
+# To enable root element in JSON for ActiveRecord objects.
+# ActiveSupport.on_load(:active_record) do
+# self.include_root_in_json = true
+# end
<%- end -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/public/404.html b/railties/lib/rails/generators/rails/app/templates/public/404.html
index 276c8c1c6a..3d875c342e 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/404.html
+++ b/railties/lib/rails/generators/rails/app/templates/public/404.html
@@ -22,5 +22,6 @@
<h1>The page you were looking for doesn't exist.</h1>
<p>You may have mistyped the address or the page may have moved.</p>
</div>
+ <p>If you are the application owner check the logs for more information.</p>
</body>
</html>
diff --git a/railties/lib/rails/generators/rails/app/templates/public/500.html b/railties/lib/rails/generators/rails/app/templates/public/500.html
index dfdb7d0b05..012977d3d2 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/500.html
+++ b/railties/lib/rails/generators/rails/app/templates/public/500.html
@@ -21,5 +21,6 @@
<div class="dialog">
<h1>We're sorry, but something went wrong.</h1>
</div>
+ <p>If you are the application owner check the logs for more information.</p>
</body>
</html>
diff --git a/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb
index a8f7aeac7d..0090293200 100644
--- a/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb
+++ b/railties/lib/rails/generators/rails/app/templates/test/test_helper.rb
@@ -4,6 +4,8 @@ require 'rails/test_help'
class ActiveSupport::TestCase
<% unless options[:skip_active_record] -%>
+ ActiveRecord::Migration.check_pending!
+
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
diff --git a/railties/lib/rails/generators/rails/controller/templates/controller.rb b/railties/lib/rails/generators/rails/controller/templates/controller.rb
index 4053113b4b..633e0b3177 100644
--- a/railties/lib/rails/generators/rails/controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/controller/templates/controller.rb
@@ -1,5 +1,5 @@
<% if namespaced? -%>
-require_dependency "<%= namespaced_file_path %>/application_controller"
+require_dependency "<%= namespaced_path %>/application_controller"
<% end -%>
<% module_namespacing do -%>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
index 82ffeebb86..568ed653b7 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
@@ -22,6 +22,8 @@ Gem::Specification.new do |s|
<% if full? && !options[:skip_javascript] -%>
# s.add_dependency "<%= "#{options[:javascript]}-rails" %>"
<% end -%>
+<% unless options[:skip_active_record] -%>
s.add_development_dependency "<%= gem_for_database %>"
+<% end -%>
end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
index 9399c9cb77..7448b386c5 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
@@ -1,17 +1,32 @@
source "http://rubygems.org"
+<% if options[:skip_gemspec] -%>
+<%= '# ' if options.dev? || options.edge? -%>gem "rails", "~> <%= Rails::VERSION::STRING %>"
+<% if full? && !options[:skip_javascript] -%>
+# gem "<%= "#{options[:javascript]}-rails" %>"
+<% end -%>
+<% else -%>
# Declare your gem's dependencies in <%= name %>.gemspec.
# Bundler will treat runtime dependencies like base dependencies, and
# development dependencies will be added by default to the :development group.
gemspec
+<% end -%>
+<% unless options[:javascript] == 'jquery' -%>
# jquery-rails is used by the dummy application
gem "jquery-rails"
+<% end -%>
+<% if options[:skip_gemspec] -%>
+group :development do
+ gem "<%= gem_for_database %>"
+end
+<% else -%>
# Declare any dependencies that are still in development here instead of in
# your gemspec. These might include edge Rails or gems from your path or
# Git. Remember to move these dependencies to your gemspec before releasing
# your gem to rubygems.org.
+<% end -%>
<% if options.dev? || options.edge? -%>
# Your gem is dependent on dev or edge Rails. Once you can lock this
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
index 743036362e..1369140537 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
@@ -14,7 +14,7 @@ RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_files.include('lib/**/*.rb')
end
-<% if full? && !options[:skip_active_record] -%>
+<% if full? && !options[:skip_active_record] && !options[:skip_test_unit] -%>
APP_RAKEFILE = File.expand_path("../<%= dummy_path -%>/Rakefile", __FILE__)
load 'rails/tasks/engine.rake'
<% end %>
diff --git a/railties/lib/rails/tasks/framework.rake b/railties/lib/rails/tasks/framework.rake
index 206ce39773..f9cff5b627 100644
--- a/railties/lib/rails/tasks/framework.rake
+++ b/railties/lib/rails/tasks/framework.rake
@@ -20,7 +20,7 @@ namespace :rails do
project_templates = "#{Rails.root}/lib/templates"
default_templates = { "erb" => %w{controller mailer scaffold},
- "rails" => %w{controller helper scaffold_controller stylesheets} }
+ "rails" => %w{controller helper scaffold_controller assets} }
default_templates.each do |type, names|
local_template_type_dir = File.join(project_templates, type)
diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake
index 55bebb549b..0de4afe905 100644
--- a/railties/lib/rails/test_unit/testing.rake
+++ b/railties/lib/rails/test_unit/testing.rake
@@ -87,7 +87,7 @@ namespace :test do
if File.directory?(".svn")
changed_since_checkin = silence_stderr { `svn status` }.split.map { |path| path.chomp[7 .. -1] }
elsif File.directory?(".git")
- changed_since_checkin = silence_stderr { `git ls-files --modified --others` }.split.map { |path| path.chomp }
+ changed_since_checkin = silence_stderr { `git ls-files --modified --others --exclude-standard` }.split.map { |path| path.chomp }
else
abort "Not a Subversion or Git checkout."
end
diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb
index e23a19d69c..4243a79b58 100644
--- a/railties/test/application/assets_test.rb
+++ b/railties/test/application/assets_test.rb
@@ -17,9 +17,21 @@ module ApplicationTests
teardown_app
end
- def precompile!
+ def precompile!(env = nil)
quietly do
- Dir.chdir(app_path){ `bundle exec rake assets:precompile` }
+ precompile_task = 'bundle exec rake assets:precompile'
+ precompile_task += ' ' + env if env
+ out = Dir.chdir(app_path){ %x[ #{precompile_task} ] }
+ assert $?.exitstatus == 0,
+ "#{precompile_task} has failed: #{out}.\
+ Probably you didn't install JavaScript runtime."
+ return out
+ end
+ end
+
+ def clean_assets!
+ quietly do
+ assert Dir.chdir(app_path){ system('bundle exec rake assets:clean') }
end
end
@@ -253,9 +265,8 @@ module ApplicationTests
# digest is default in false, we must enable it for test environment
add_to_env_config "test", "config.assets.digest = true"
- quietly do
- Dir.chdir(app_path){ `bundle exec rake assets:precompile RAILS_ENV=test` }
- end
+ precompile!('RAILS_ENV=test')
+
file = Dir["#{app_path}/public/assets/application.css"].first
assert_match(/\/assets\/rails\.png/, File.read(file))
file = Dir["#{app_path}/public/assets/application-*.css"].first
@@ -285,9 +296,9 @@ module ApplicationTests
add_to_config "config.assets.compile = true"
ENV["RAILS_ENV"] = nil
- quietly do
- Dir.chdir(app_path){ `bundle exec rake assets:precompile RAILS_GROUPS=assets` }
- end
+
+ precompile!('RAILS_GROUPS=assets')
+
file = Dir["#{app_path}/public/assets/application-*.css"].first
assert_match(/\/assets\/rails-([0-z]+)\.png/, File.read(file))
end
@@ -310,9 +321,7 @@ module ApplicationTests
app_file "public/assets/application.css", "a { color: green; }"
app_file "public/assets/subdir/broken.png", "not really an image file"
- quietly do
- Dir.chdir(app_path){ `bundle exec rake assets:clean` }
- end
+ clean_assets!
files = Dir["#{app_path}/public/assets/**/*", "#{app_path}/tmp/cache/assets/*"]
assert_equal 0, files.length, "Expected no assets, but found #{files.join(', ')}"
@@ -440,9 +449,8 @@ module ApplicationTests
add_to_config "config.assets.compile = true"
add_to_config "config.assets.digest = true"
- quietly do
- Dir.chdir(app_path){ `bundle exec rake assets:clean assets:precompile` }
- end
+ clean_assets!
+ precompile!
files = Dir["#{app_path}/public/assets/application-*.js"]
assert_equal 1, files.length, "Expected digested application.js asset to be generated, but none found"
@@ -453,9 +461,8 @@ module ApplicationTests
add_to_env_config "production", "config.assets.prefix = 'production_assets'"
ENV["RAILS_ENV"] = nil
- quietly do
- Dir.chdir(app_path){ `bundle exec rake assets:clean` }
- end
+
+ clean_assets!
files = Dir["#{app_path}/public/production_assets/application.js"]
assert_equal 0, files.length, "Expected application.js asset to be removed, but still exists"
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index d7689863e6..7193dfdef5 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -41,6 +41,21 @@ module ApplicationTests
FileUtils.rm_rf(new_app) if File.directory?(new_app)
end
+ test "a renders exception on pending migration" do
+ add_to_config <<-RUBY
+ config.active_record.migration_error = :page_load
+ config.consider_all_requests_local = true
+ config.action_dispatch.show_exceptions = true
+ RUBY
+
+ require "#{app_path}/config/environment"
+ ActiveRecord::Migrator.stubs(:needs_migration?).returns(true)
+
+ get "/foo"
+ assert_equal 500, last_response.status
+ assert_match "ActiveRecord::PendingMigrationError", last_response.body
+ end
+
test "multiple queue construction is possible" do
require 'rails'
require "#{app_path}/config/environment"
@@ -361,7 +376,7 @@ module ApplicationTests
assert_equal ActiveModel::MassAssignmentSecurity::WhiteList,
ActiveRecord::Base.active_authorizers[:default].class
- assert_equal [""], ActiveRecord::Base.active_authorizers[:default].to_a
+ assert_equal [], ActiveRecord::Base.active_authorizers[:default].to_a
end
test "registers interceptors with ActionMailer" do
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index 8cf867da3c..eac471a07e 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -190,5 +190,16 @@ module ApplicationTests
end
end
+ def test_copy_templates
+ Dir.chdir(app_path) do
+ `bundle exec rake rails:templates:copy`
+ %w(controller mailer scaffold).each do |dir|
+ assert File.exists?(File.join(app_path, 'lib', 'templates', 'erb', dir))
+ end
+ %w(controller helper scaffold_controller assets).each do |dir|
+ assert File.exists?(File.join(app_path, 'lib', 'templates', 'rails', dir))
+ end
+ end
+ end
end
end
diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb
index 09169ef2d2..2ae9dc61a7 100644
--- a/railties/test/generators/namespaced_generators_test.rb
+++ b/railties/test/generators/namespaced_generators_test.rb
@@ -38,7 +38,9 @@ class NamespacedControllerGeneratorTest < NamespacedGeneratorTestCase
def test_namespaced_controller_with_additional_namespace
run_generator ["admin/account"]
- assert_file "app/controllers/test_app/admin/account_controller.rb", /module TestApp/, / class Admin::AccountController < ApplicationController/
+ assert_file "app/controllers/test_app/admin/account_controller.rb", /module TestApp/, / class Admin::AccountController < ApplicationController/ do |contents|
+ assert_match %r(require_dependency "test_app/application_controller"), contents
+ end
end
def test_helpr_is_also_namespaced
diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb
index 58740978aa..0a235b56d5 100644
--- a/railties/test/generators/plugin_new_generator_test.rb
+++ b/railties/test/generators/plugin_new_generator_test.rb
@@ -58,6 +58,14 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_file "test/integration/navigation_test.rb", /ActionDispatch::IntegrationTest/
end
+ def test_generating_test_files_in_full_mode_without_unit_test_files
+ run_generator [destination_root, "-T", "--full"]
+
+ assert_no_directory "test/integration/"
+ assert_no_file "test"
+ assert_no_match(/APP_RAKEFILE/, File.read(File.join(destination_root, "Rakefile")))
+ 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"]))
@@ -82,6 +90,14 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_file "bukkits.gemspec", /mysql/
end
+ def test_dont_generate_development_dependency
+ run_generator [destination_root, "--skip-active-record"]
+
+ assert_file "bukkits.gemspec" do |contents|
+ assert_no_match(/s.add_development_dependency "sqlite3"/, contents)
+ end
+ 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["']/
@@ -269,6 +285,32 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
def test_skipping_gemspec
run_generator [destination_root, "--skip-gemspec"]
assert_no_file "bukkits.gemspec"
+ assert_file "Gemfile" do |contents|
+ assert_no_match('gemspec', contents)
+ assert_match(/gem "rails", "~> #{Rails::VERSION::STRING}"/, contents)
+ assert_match(/group :development do\n gem "sqlite3"\nend/, contents)
+ assert_no_match(/# gem "jquery-rails"/, contents)
+ end
+ end
+
+ def test_skipping_gemspec_in_full_mode
+ run_generator [destination_root, "--skip-gemspec", "--full"]
+ assert_no_file "bukkits.gemspec"
+ assert_file "Gemfile" do |contents|
+ assert_no_match('gemspec', contents)
+ assert_match(/gem "rails", "~> #{Rails::VERSION::STRING}"/, contents)
+ assert_match(/group :development do\n gem "sqlite3"\nend/, contents)
+ assert_match(/# gem "jquery-rails"/, contents)
+ assert_no_match(/# jquery-rails is used by the dummy application\ngem "jquery-rails"/, contents)
+ end
+ end
+
+ def test_skipping_gemspec_in_full_mode_with_javascript_option
+ run_generator [destination_root, "--skip-gemspec", "--full", "--javascript=prototype"]
+ assert_file "Gemfile" do |contents|
+ assert_match(/# gem "prototype-rails"/, contents)
+ assert_match(/# jquery-rails is used by the dummy application\ngem "jquery-rails"/, contents)
+ end
end
def test_creating_plugin_in_app_directory_adds_gemfile_entry
@@ -303,12 +345,10 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
protected
-
def action(*args, &block)
silence(:stdout){ generator.send(*args, &block) }
end
-protected
def default_files
::DEFAULT_PLUGIN_FILES
end
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 4437e2c8af..52c7fae6c6 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -1009,9 +1009,7 @@ YAML
boot_rails
- methods = Bukkits::Engine.helpers.public_instance_methods.collect(&:to_s).sort
- expected = ["bar", "baz"]
- assert_equal expected, methods
+ assert_equal [:bar, :baz], Bukkits::Engine.helpers.public_instance_methods.sort
end
test "setting priority for engines with config.railties_order" do