aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Gemfile4
-rw-r--r--actionmailer/actionmailer.gemspec2
-rw-r--r--actionmailer/test/abstract_unit.rb10
-rw-r--r--actionpack/actionpack.gemspec4
-rw-r--r--actionpack/lib/abstract_controller/helpers.rb22
-rw-r--r--actionpack/lib/action_controller/metal/helpers.rb52
-rw-r--r--actionpack/lib/action_controller/test_case.rb4
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb3
-rw-r--r--actionpack/lib/action_view/helpers/asset_paths.rb4
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb3
-rw-r--r--actionpack/lib/action_view/helpers/number_helper.rb9
-rw-r--r--actionpack/lib/action_view/helpers/translation_helper.rb6
-rw-r--r--actionpack/test/controller/test_test.rb12
-rw-r--r--actionpack/test/controller/view_paths_test.rb12
-rw-r--r--actionpack/test/dispatch/prefix_generation_test.rb1
-rw-r--r--actionpack/test/template/asset_tag_helper_test.rb15
-rw-r--r--actionpack/test/template/form_helper_test.rb12
-rw-r--r--actionpack/test/template/number_helper_test.rb12
-rw-r--r--activemodel/activemodel.gemspec2
-rw-r--r--activemodel/lib/active_model/mass_assignment_security.rb117
-rw-r--r--activemodel/lib/active_model/observer_array.rb104
-rw-r--r--activemodel/lib/active_model/observing.rb28
-rw-r--r--activemodel/lib/active_model/validations.rb2
-rw-r--r--activemodel/lib/active_model/validations/callbacks.rb4
-rw-r--r--activemodel/test/cases/mass_assignment_security_test.rb39
-rw-r--r--activemodel/test/cases/observer_array_test.rb220
-rw-r--r--activemodel/test/cases/observing_test.rb5
-rw-r--r--activemodel/test/cases/secure_password_test.rb11
-rw-r--r--activemodel/test/cases/validations_test.rb14
-rw-r--r--activemodel/test/models/mass_assignment_specific.rb11
-rw-r--r--activemodel/test/models/observers.rb27
-rw-r--r--activerecord/lib/active_record/base.rb62
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb15
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb9
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb88
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb141
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb9
-rw-r--r--activerecord/lib/active_record/persistence.rb23
-rw-r--r--activerecord/lib/active_record/railtie.rb3
-rw-r--r--activerecord/lib/active_record/railties/databases.rake10
-rw-r--r--activerecord/lib/active_record/railties/jdbcmysql_error.rb16
-rw-r--r--activerecord/lib/active_record/relation.rb6
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb4
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb13
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb5
-rw-r--r--activerecord/test/cases/adapters/postgresql/datatype_test.rb25
-rw-r--r--activerecord/test/cases/base_test.rb8
-rw-r--r--activerecord/test/cases/finder_test.rb23
-rw-r--r--activerecord/test/cases/mass_assignment_security_test.rb71
-rw-r--r--activerecord/test/cases/persistence_test.rb42
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb7
-rw-r--r--activerecord/test/cases/validations/uniqueness_validation_test.rb26
-rw-r--r--activerecord/test/models/loose_person.rb24
-rw-r--r--activerecord/test/models/person.rb19
-rw-r--r--activerecord/test/schema/postgresql_specific_schema.rb10
-rw-r--r--activeresource/test/connection_test.rb2
-rw-r--r--activesupport/activesupport.gemspec2
-rw-r--r--activesupport/lib/active_support/buffered_logger.rb13
-rw-r--r--activesupport/lib/active_support/cache/mem_cache_store.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/array/access.rb4
-rw-r--r--activesupport/lib/active_support/deprecation.rb2
-rw-r--r--activesupport/lib/active_support/inflector/inflections.rb2
-rw-r--r--activesupport/lib/active_support/log_subscriber.rb2
-rw-r--r--activesupport/lib/active_support/whiny_nil.rb2
-rw-r--r--activesupport/test/caching_test.rb38
-rw-r--r--activesupport/test/core_ext/array_ext_test.rb2
-rw-r--r--activesupport/test/inflector_test.rb42
-rw-r--r--railties/guides/source/configuring.textile2
-rw-r--r--railties/guides/source/contributing_to_ruby_on_rails.textile67
-rw-r--r--railties/guides/source/security.textile31
-rw-r--r--railties/lib/rails/application/finisher.rb4
-rw-r--r--railties/lib/rails/commands/console.rb2
-rw-r--r--railties/lib/rails/engine.rb39
-rw-r--r--railties/lib/rails/generators/app_base.rb13
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml30
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml48
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml17
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt8
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb6
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb7
-rw-r--r--railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb7
-rw-r--r--railties/lib/rails/generators/test_unit/integration/templates/integration_test.rb7
-rw-r--r--railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb7
-rw-r--r--railties/lib/rails/generators/test_unit/model/templates/unit_test.rb7
-rw-r--r--railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb7
-rw-r--r--railties/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt7
-rw-r--r--railties/test/application/configuration_test.rb12
-rw-r--r--railties/test/generators/app_generator_test.rb18
-rw-r--r--railties/test/generators/plugin_new_generator_test.rb6
-rw-r--r--railties/test/railties/engine_test.rb45
93 files changed, 1551 insertions, 405 deletions
diff --git a/Gemfile b/Gemfile
index c262b97819..8b6ddbd7c9 100644
--- a/Gemfile
+++ b/Gemfile
@@ -13,7 +13,7 @@ gem "rack-test", :git => "git://github.com/brynary/rack-test.git"
gem "sprockets", :git => "git://github.com/sstephenson/sprockets.git"
gem "coffee-script"
-gem "sass", ">= 3.0"
+gem "sass"
gem "uglifier"
gem "rake", ">= 0.8.7"
@@ -54,7 +54,7 @@ platforms :ruby do
group :db do
gem "pg", ">= 0.11.0"
gem "mysql", ">= 2.8.1"
- gem "mysql2", :git => "git://github.com/brianmario/mysql2.git"
+ gem "mysql2", ">= 0.3.0"
end
end
diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec
index a59069cc37..447e25ca8a 100644
--- a/actionmailer/actionmailer.gemspec
+++ b/actionmailer/actionmailer.gemspec
@@ -18,5 +18,5 @@ Gem::Specification.new do |s|
s.requirements << 'none'
s.add_dependency('actionpack', version)
- s.add_dependency('mail', '~> 2.2.16')
+ s.add_dependency('mail', '~> 2.3.0')
end
diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb
index ce664bf301..0b076e1ff9 100644
--- a/actionmailer/test/abstract_unit.rb
+++ b/actionmailer/test/abstract_unit.rb
@@ -23,11 +23,6 @@ if "ruby".encoding_aware?
end
end
-silence_warnings do
- # These external dependencies have warnings :/
- require 'mail'
-end
-
lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
$:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
@@ -35,6 +30,11 @@ require 'test/unit'
require 'action_mailer'
require 'action_mailer/test_case'
+silence_warnings do
+ # These external dependencies have warnings :/
+ require 'mail'
+end
+
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
index d3c66800d9..0d667a76a7 100644
--- a/actionpack/actionpack.gemspec
+++ b/actionpack/actionpack.gemspec
@@ -21,10 +21,10 @@ Gem::Specification.new do |s|
s.add_dependency('activemodel', version)
s.add_dependency('rack-cache', '~> 1.0.0')
s.add_dependency('builder', '~> 3.0.0')
- s.add_dependency('i18n', '~> 0.5.0')
+ s.add_dependency('i18n', '~> 0.6.0beta1')
s.add_dependency('rack', '~> 1.2.1')
s.add_dependency('rack-test', '~> 0.5.7')
- s.add_dependency('rack-mount', '~> 0.7.1')
+ s.add_dependency('rack-mount', '~> 0.7.2')
s.add_dependency('tzinfo', '~> 0.3.23')
s.add_dependency('erubis', '~> 2.7.0')
end
diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb
index 20f8601a8e..0ff1c0491a 100644
--- a/actionpack/lib/abstract_controller/helpers.rb
+++ b/actionpack/lib/abstract_controller/helpers.rb
@@ -112,17 +112,6 @@ module AbstractController
default_helper_module! unless anonymous?
end
- private
- # Makes all the (instance) methods in the helper module available to templates
- # rendered through this controller.
- #
- # ==== Parameters
- # * <tt>module</tt> - The module to include into the current helper module
- # for the class
- def add_template_helper(mod)
- _helpers.module_eval { include mod }
- end
-
# Returns a list of modules, normalized from the acceptable kinds of
# helpers with the following behavior:
#
@@ -155,6 +144,17 @@ module AbstractController
end
end
+ private
+ # Makes all the (instance) methods in the helper module available to templates
+ # rendered through this controller.
+ #
+ # ==== Parameters
+ # * <tt>module</tt> - The module to include into the current helper module
+ # for the class
+ def add_template_helper(mod)
+ _helpers.module_eval { include mod }
+ end
+
def default_helper_module!
module_name = name.sub(/Controller$/, '')
module_path = module_name.underscore
diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb
index 91a88ab68a..75757db564 100644
--- a/actionpack/lib/action_controller/metal/helpers.rb
+++ b/actionpack/lib/action_controller/metal/helpers.rb
@@ -76,35 +76,35 @@ module ActionController
@helper_proxy ||= ActionView::Base.new.extend(_helpers)
end
- private
- # Overwrite modules_for_helpers to accept :all as argument, which loads
- # all helpers in helpers_path.
- #
- # ==== Parameters
- # * <tt>args</tt> - A list of helpers
- #
- # ==== Returns
- # * <tt>array</tt> - A normalized list of modules for the list of helpers provided.
- def modules_for_helpers(args)
- args += all_application_helpers if args.delete(:all)
- super(args)
- end
+ # Overwrite modules_for_helpers to accept :all as argument, which loads
+ # all helpers in helpers_path.
+ #
+ # ==== Parameters
+ # * <tt>args</tt> - A list of helpers
+ #
+ # ==== Returns
+ # * <tt>array</tt> - A normalized list of modules for the list of helpers provided.
+ def modules_for_helpers(args)
+ args += all_application_helpers if args.delete(:all)
+ super(args)
+ end
- # Extract helper names from files in <tt>app/helpers/**/*_helper.rb</tt>
- def all_application_helpers
- all_helpers_from_path(helpers_path)
+ def all_helpers_from_path(path)
+ helpers = []
+ Array.wrap(path).each do |_path|
+ extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
+ helpers += Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
end
+ helpers.sort!
+ helpers.uniq!
+ helpers
+ end
- def all_helpers_from_path(path)
- helpers = []
- Array.wrap(path).each do |_path|
- extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
- helpers += Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
- end
- helpers.sort!
- helpers.uniq!
- helpers
- end
+ private
+ # Extract helper names from files in <tt>app/helpers/**/*_helper.rb</tt>
+ def all_application_helpers
+ all_helpers_from_path(helpers_path)
+ end
end
end
end
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index bc4f8bb9ce..0085f542aa 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -147,7 +147,9 @@ module ActionController
if value.is_a? Fixnum
value = value.to_s
elsif value.is_a? Array
- value = Result.new(value)
+ value = Result.new(value.map { |v| v.is_a?(String) ? v.dup : v })
+ elsif value.is_a? String
+ value = value.dup
end
if extra_keys.include?(key.to_sym)
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index b28f6c2297..1d09091dc7 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -275,8 +275,7 @@ module ActionDispatch
module MountedHelpers
end
- def mounted_helpers(name = :main_app)
- define_mounted_helper(name) if name
+ def mounted_helpers
MountedHelpers
end
diff --git a/actionpack/lib/action_view/helpers/asset_paths.rb b/actionpack/lib/action_view/helpers/asset_paths.rb
index 55a4c442fd..cb6737b94e 100644
--- a/actionpack/lib/action_view/helpers/asset_paths.rb
+++ b/actionpack/lib/action_view/helpers/asset_paths.rb
@@ -12,7 +12,7 @@ module ActionView
@controller = controller
end
- # Add the extension +ext+ if not present. Return full URLs otherwise untouched.
+ # Add the extension +ext+ if not present. Return full or scheme-relative URLs otherwise untouched.
# Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL
# roots. Rewrite the asset path for cache-busting asset ids. Include
# asset host, if configured, with the correct request protocol.
@@ -33,7 +33,7 @@ module ActionView
end
def is_uri?(path)
- path =~ %r{^[-a-z]+://|^cid:}
+ path =~ %r{^[-a-z]+://|^cid:|^//}
end
private
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
index f7cb1f5b58..9bc847a1ab 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
@@ -57,7 +57,7 @@ module ActionView
# +asset_host+ to a proc like this:
#
# ActionController::Base.asset_host = Proc.new { |source|
- # "http://assets#{source.hash % 2 + 1}.example.com"
+ # "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com"
# }
# image_tag("rails.png")
# # => <img alt="Rails" src="http://assets1.example.com/images/rails.png?1230601161" />
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index 440acafa88..efe30441b1 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -947,7 +947,8 @@ module ActionView
label_tag(name_and_id["id"], options, &block)
else
content = if text.blank?
- I18n.t("helpers.label.#{object_name}.#{method_name}", :default => "").presence
+ method_and_value = tag_value.present? ? "#{method_name}.#{tag_value}" : method_name
+ I18n.t("helpers.label.#{object_name}.#{method_and_value}", :default => "").presence
else
text.to_s
end
diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb
index b545031fcc..63d13a0f0b 100644
--- a/actionpack/lib/action_view/helpers/number_helper.rb
+++ b/actionpack/lib/action_view/helpers/number_helper.rb
@@ -304,6 +304,7 @@ module ActionView
# * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to ".").
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator (defaults to +true+)
+ # * <tt>:prefix</tt> - If +:si+ formats the number using the SI prefix (defaults to :binary)
# ==== Examples
# number_to_human_size(123) # => 123 Bytes
# number_to_human_size(1234) # => 1.21 KB
@@ -341,15 +342,17 @@ module ActionView
options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
storage_units_format = I18n.translate(:'number.human.storage_units.format', :locale => options[:locale], :raise => true)
+
+ base = options[:prefix] == :si ? 1000 : 1024
- if number.to_i < 1024
+ if number.to_i < base
unit = I18n.translate(:'number.human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true)
storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit).html_safe
else
max_exp = STORAGE_UNITS.size - 1
- exponent = (Math.log(number) / Math.log(1024)).to_i # Convert to base 1024
+ exponent = (Math.log(number) / Math.log(base)).to_i # Convert to base
exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
- number /= 1024 ** exponent
+ number /= base ** exponent
unit_key = STORAGE_UNITS[exponent]
unit = I18n.translate(:"number.human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true)
diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb
index 59e6ce878f..26ebae6546 100644
--- a/actionpack/lib/action_view/helpers/translation_helper.rb
+++ b/actionpack/lib/action_view/helpers/translation_helper.rb
@@ -5,7 +5,7 @@ module I18n
class ExceptionHandler
include Module.new {
def call(exception, locale, key, options)
- exception.is_a?(MissingTranslationData) ? super.html_safe : super
+ exception.is_a?(MissingTranslation) ? super.html_safe : super
end
}
end
@@ -17,8 +17,8 @@ module ActionView
module TranslationHelper
# Delegates to I18n#translate but also performs three additional functions.
#
- # First, it'll pass the :rescue_format => :html option to I18n so that any caught
- # MissingTranslationData exceptions will be turned into inline spans that
+ # First, it'll pass the :rescue_format => :html option to I18n so that any
+ # thrown MissingTranslation messages will be turned into inline spans that
#
# * have a "translation-missing" class set,
# * contain the missing key as a title attribute and
diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb
index edda0d0a30..5896222a0a 100644
--- a/actionpack/test/controller/test_test.rb
+++ b/actionpack/test/controller/test_test.rb
@@ -493,6 +493,18 @@ XML
)
end
+ def test_params_passing_with_frozen_values
+ assert_nothing_raised do
+ get :test_params, :frozen => 'icy'.freeze, :frozens => ['icy'.freeze].freeze
+ end
+ parsed_params = eval(@response.body)
+ assert_equal(
+ {'controller' => 'test_test/test', 'action' => 'test_params',
+ 'frozen' => 'icy', 'frozens' => ['icy']},
+ parsed_params
+ )
+ end
+
def test_id_converted_to_string
get :test_params, :id => 20, :foo => Object.new
assert_kind_of String, @request.path_parameters['id']
diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb
index 9280a1c2d3..42356be1ea 100644
--- a/actionpack/test/controller/view_paths_test.rb
+++ b/actionpack/test/controller/view_paths_test.rb
@@ -131,8 +131,8 @@ class ViewLoadPathsTest < ActionController::TestCase
assert_equal "Hello overridden world!", @response.body
end
- def test_override_view_paths_with_custom_resolver
- resolver_class = Class.new(ActionView::PathResolver) do
+ def test_decorate_view_paths_with_custom_resolver
+ decorator_class = Class.new(ActionView::PathResolver) do
def initialize(path_set)
@path_set = path_set
end
@@ -140,7 +140,7 @@ class ViewLoadPathsTest < ActionController::TestCase
def find_all(*args)
@path_set.find_all(*args).collect do |template|
::ActionView::Template.new(
- "Customized body",
+ "Decorated body",
template.identifier,
template.handler,
{
@@ -152,12 +152,12 @@ class ViewLoadPathsTest < ActionController::TestCase
end
end
- resolver = resolver_class.new(TestController.view_paths)
- TestController.view_paths = ActionView::PathSet.new.push(resolver)
+ decorator = decorator_class.new(TestController.view_paths)
+ TestController.view_paths = ActionView::PathSet.new.push(decorator)
get :hello_world
assert_response :success
- assert_equal "Customized body", @response.body
+ assert_equal "Decorated body", @response.body
end
def test_inheritance
diff --git a/actionpack/test/dispatch/prefix_generation_test.rb b/actionpack/test/dispatch/prefix_generation_test.rb
index 18f28deee4..b28a058250 100644
--- a/actionpack/test/dispatch/prefix_generation_test.rb
+++ b/actionpack/test/dispatch/prefix_generation_test.rb
@@ -69,6 +69,7 @@ module TestGenerationPrefix
# force draw
RailsApplication.routes
+ RailsApplication.routes.define_mounted_helper(:main_app)
class ::InsideEngineGeneratingController < ActionController::Base
include BlogEngine.routes.url_helpers
diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb
index 4a93def5a8..2abc806e97 100644
--- a/actionpack/test/template/asset_tag_helper_test.rb
+++ b/actionpack/test/template/asset_tag_helper_test.rb
@@ -66,6 +66,7 @@ class AssetTagHelperTest < ActionView::TestCase
%(auto_discovery_link_tag(:xml)) => %(<link href="http://www.example.com" rel="alternate" title="XML" type="application/xml" />),
%(auto_discovery_link_tag(:rss, :action => "feed")) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />),
%(auto_discovery_link_tag(:rss, "http://localhost/feed")) => %(<link href="http://localhost/feed" rel="alternate" title="RSS" type="application/rss+xml" />),
+ %(auto_discovery_link_tag(:rss, "//localhost/feed")) => %(<link href="//localhost/feed" rel="alternate" title="RSS" type="application/rss+xml" />),
%(auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"})) => %(<link href="http://www.example.com" rel="alternate" title="My RSS" type="application/rss+xml" />),
%(auto_discovery_link_tag(:rss, {}, {:title => "My RSS"})) => %(<link href="http://www.example.com" rel="alternate" title="My RSS" type="application/rss+xml" />),
%(auto_discovery_link_tag(nil, {}, {:type => "text/html"})) => %(<link href="http://www.example.com" rel="alternate" title="" type="text/html" />),
@@ -100,6 +101,7 @@ class AssetTagHelperTest < ActionView::TestCase
%(javascript_include_tag("http://example.com/all")) => %(<script src="http://example.com/all" type="text/javascript"></script>),
%(javascript_include_tag("http://example.com/all.js")) => %(<script src="http://example.com/all.js" type="text/javascript"></script>),
+ %(javascript_include_tag("//example.com/all.js")) => %(<script src="//example.com/all.js" type="text/javascript"></script>),
}
StylePathToTag = {
@@ -129,6 +131,7 @@ class AssetTagHelperTest < ActionView::TestCase
%(stylesheet_link_tag("http://www.example.com/styles/style")) => %(<link href="http://www.example.com/styles/style" media="screen" rel="stylesheet" type="text/css" />),
%(stylesheet_link_tag("http://www.example.com/styles/style.css")) => %(<link href="http://www.example.com/styles/style.css" media="screen" rel="stylesheet" type="text/css" />),
+ %(stylesheet_link_tag("//www.example.com/styles/style.css")) => %(<link href="//www.example.com/styles/style.css" media="screen" rel="stylesheet" type="text/css" />),
}
ImagePathToTag = {
@@ -157,6 +160,7 @@ class AssetTagHelperTest < ActionView::TestCase
%(image_tag("slash..png")) => %(<img alt="Slash." src="/images/slash..png" />),
%(image_tag(".pdf.png")) => %(<img alt=".pdf" src="/images/.pdf.png" />),
%(image_tag("http://www.rubyonrails.com/images/rails.png")) => %(<img alt="Rails" src="http://www.rubyonrails.com/images/rails.png" />),
+ %(image_tag("//www.rubyonrails.com/images/rails.png")) => %(<img alt="Rails" src="//www.rubyonrails.com/images/rails.png" />),
%(image_tag("mouse.png", :mouseover => "/images/mouse_over.png")) => %(<img alt="Mouse" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" src="/images/mouse.png" />),
%(image_tag("mouse.png", :mouseover => image_path("mouse_over.png"))) => %(<img alt="Mouse" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" src="/images/mouse.png" />),
%(image_tag("mouse.png", :alt => nil)) => %(<img src="/images/mouse.png" />)
@@ -195,6 +199,7 @@ class AssetTagHelperTest < ActionView::TestCase
%(video_tag("error.avi", "size" => "100 x 100")) => %(<video src="/videos/error.avi" />),
%(video_tag("error.avi", "size" => "x")) => %(<video src="/videos/error.avi" />),
%(video_tag("http://media.rubyonrails.org/video/rails_blog_2.mov")) => %(<video src="http://media.rubyonrails.org/video/rails_blog_2.mov" />),
+ %(video_tag("//media.rubyonrails.org/video/rails_blog_2.mov")) => %(<video src="//media.rubyonrails.org/video/rails_blog_2.mov" />),
%(video_tag(["multiple.ogg", "multiple.avi"])) => %(<video><source src="multiple.ogg" /><source src="multiple.avi" /></video>),
%(video_tag(["multiple.ogg", "multiple.avi"], :size => "160x120", :controls => true)) => %(<video controls="controls" height="120" width="160"><source src="multiple.ogg" /><source src="multiple.avi" /></video>)
}
@@ -217,6 +222,7 @@ class AssetTagHelperTest < ActionView::TestCase
%(audio_tag("xml.wav")) => %(<audio src="/audios/xml.wav" />),
%(audio_tag("rss.wav", :autoplay => true, :controls => true)) => %(<audio autoplay="autoplay" controls="controls" src="/audios/rss.wav" />),
%(audio_tag("http://media.rubyonrails.org/audio/rails_blog_2.mov")) => %(<audio src="http://media.rubyonrails.org/audio/rails_blog_2.mov" />),
+ %(audio_tag("//media.rubyonrails.org/audio/rails_blog_2.mov")) => %(<audio src="//media.rubyonrails.org/audio/rails_blog_2.mov" />),
}
def test_auto_discovery_link_tag
@@ -505,6 +511,10 @@ class AssetTagHelperTest < ActionView::TestCase
assert_equal %(<img alt="Rails" src="http://www.example.com/rails.png" />), image_tag("http://www.example.com/rails.png")
end
+ def test_should_skip_asset_id_on_scheme_relative_url
+ assert_equal %(<img alt="Rails" src="//www.example.com/rails.png" />), image_tag("//www.example.com/rails.png")
+ end
+
def test_should_use_preset_asset_id
ENV["RAILS_ASSET_ID"] = "4500"
assert_equal %(<img alt="Rails" src="/images/rails.png?4500" />), image_tag("rails.png")
@@ -1095,6 +1105,11 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase
assert_dom_equal(%(<link href="http://bar.example.com/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag("http://bar.example.com/stylesheets/style.css"))
end
+ def test_should_ignore_asset_host_on_scheme_relative_url
+ @controller.config.asset_host = "http://assets.example.com"
+ assert_dom_equal(%(<link href="//bar.example.com/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag("//bar.example.com/stylesheets/style.css"))
+ end
+
def test_should_wildcard_asset_host_between_zero_and_four
@controller.config.asset_host = 'http://a%d.example.com'
assert_match(%r(http://a[0123].example.com/collaboration/hieraki/images/xml.png), image_path('xml.png'))
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index 7afab3179c..c25c850eb3 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -24,7 +24,10 @@ class FormHelperTest < ActionView::TestCase
:helpers => {
:label => {
:post => {
- :body => "Write entire text here"
+ :body => "Write entire text here",
+ :color => {
+ :red => "Rojo"
+ }
}
}
}
@@ -141,6 +144,13 @@ class FormHelperTest < ActionView::TestCase
I18n.locale = old_locale
end
+ def test_label_with_locales_and_value
+ old_locale, I18n.locale = I18n.locale, :label
+ assert_dom_equal('<label for="post_color_red">Rojo</label>', label(:post, :color, :value => "red"))
+ ensure
+ I18n.locale = old_locale
+ end
+
def test_label_with_for_attribute_as_symbol
assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, :for => "my_for"))
end
diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb
index c8d50ebf75..63b92aadf4 100644
--- a/actionpack/test/template/number_helper_test.rb
+++ b/actionpack/test/template/number_helper_test.rb
@@ -32,6 +32,7 @@ class NumberHelperTest < ActionView::TestCase
assert_equal("555-1234", number_to_phone(5551234))
assert_equal("800-555-1212", number_to_phone(8005551212))
assert_equal("(800) 555-1212", number_to_phone(8005551212, {:area_code => true}))
+ assert_equal("", number_to_phone("", {:area_code => true}))
assert_equal("800 555 1212", number_to_phone(8005551212, {:delimiter => " "}))
assert_equal("(800) 555-1212 x 123", number_to_phone(8005551212, {:area_code => true, :extension => 123}))
assert_equal("800-555-1212", number_to_phone(8005551212, :extension => " "))
@@ -171,6 +172,17 @@ class NumberHelperTest < ActionView::TestCase
assert_equal '10 Bytes', number_to_human_size(10)
end
+ def test_number_to_human_size_with_si_prefix
+ assert_equal '3 Bytes', number_to_human_size(3.14159265, :prefix => :si)
+ assert_equal '123 Bytes', number_to_human_size(123.0, :prefix => :si)
+ assert_equal '123 Bytes', number_to_human_size(123, :prefix => :si)
+ assert_equal '1.23 KB', number_to_human_size(1234, :prefix => :si)
+ assert_equal '12.3 KB', number_to_human_size(12345, :prefix => :si)
+ assert_equal '1.23 MB', number_to_human_size(1234567, :prefix => :si)
+ assert_equal '1.23 GB', number_to_human_size(1234567890, :prefix => :si)
+ assert_equal '1.23 TB', number_to_human_size(1234567890123, :prefix => :si)
+ end
+
def test_number_to_human_size_with_options_hash
assert_equal '1.2 MB', number_to_human_size(1234567, :precision => 2)
assert_equal '3 Bytes', number_to_human_size(3.14159265, :precision => 4)
diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec
index 9f80673bb8..ce69c4a201 100644
--- a/activemodel/activemodel.gemspec
+++ b/activemodel/activemodel.gemspec
@@ -19,6 +19,6 @@ Gem::Specification.new do |s|
s.add_dependency('activesupport', version)
s.add_dependency('builder', '~> 3.0.0')
- s.add_dependency('i18n', '~> 0.5.0')
+ s.add_dependency('i18n', '~> 0.6.0beta1')
s.add_dependency('bcrypt-ruby', '~> 2.1.4')
end
diff --git a/activemodel/lib/active_model/mass_assignment_security.rb b/activemodel/lib/active_model/mass_assignment_security.rb
index be48415739..01eef762fd 100644
--- a/activemodel/lib/active_model/mass_assignment_security.rb
+++ b/activemodel/lib/active_model/mass_assignment_security.rb
@@ -24,10 +24,7 @@ module ActiveModel
# include ActiveModel::MassAssignmentSecurity
#
# attr_accessible :first_name, :last_name
- #
- # def self.admin_accessible_attributes
- # accessible_attributes + [ :plan_id ]
- # end
+ # attr_accessible :first_name, :last_name, :plan_id, :as => :admin
#
# def update
# ...
@@ -38,18 +35,17 @@ module ActiveModel
# protected
#
# def account_params
- # sanitize_for_mass_assignment(params[:account])
- # end
- #
- # def mass_assignment_authorizer
- # admin ? admin_accessible_attributes : super
+ # scope = admin ? :admin : :default
+ # sanitize_for_mass_assignment(params[:account], scope)
# end
#
# end
#
module ClassMethods
# Attributes named in this macro are protected from mass-assignment
- # whenever attributes are sanitized before assignment.
+ # whenever attributes are sanitized before assignment. A scope for the
+ # attributes is optional, if no scope is provided then :default is used.
+ # A scope can be defined by using the :as option.
#
# Mass-assignment to these attributes will simply be ignored, to assign
# to them you can use direct writer methods. This is meant to protect
@@ -60,36 +56,58 @@ module ActiveModel
# include ActiveModel::MassAssignmentSecurity
#
# attr_accessor :name, :credit_rating
- # attr_protected :credit_rating
#
- # def attributes=(values)
- # sanitize_for_mass_assignment(values).each do |k, v|
+ # attr_protected :credit_rating, :last_login
+ # attr_protected :last_login, :as => :admin
+ #
+ # def assign_attributes(values, options = {})
+ # sanitize_for_mass_assignment(values, options[:as]).each do |k, v|
# send("#{k}=", v)
# end
# end
# end
#
+ # When using a :default scope :
+ #
# customer = Customer.new
- # customer.attributes = { "name" => "David", "credit_rating" => "Excellent" }
+ # customer.assign_attributes({ "name" => "David", "credit_rating" => "Excellent", :last_login => 1.day.ago }, :as => :default)
# customer.name # => "David"
# customer.credit_rating # => nil
+ # customer.last_login # => nil
#
# customer.credit_rating = "Average"
# customer.credit_rating # => "Average"
#
+ # And using the :admin scope :
+ #
+ # customer = Customer.new
+ # customer.assign_attributes({ "name" => "David", "credit_rating" => "Excellent", :last_login => 1.day.ago }, :as => :admin)
+ # customer.name # => "David"
+ # customer.credit_rating # => "Excellent"
+ # customer.last_login # => nil
+ #
# To start from an all-closed default and enable attributes as needed,
# have a look at +attr_accessible+.
#
# Note that using <tt>Hash#except</tt> or <tt>Hash#slice</tt> in place of +attr_protected+
# to sanitize attributes won't provide sufficient protection.
- def attr_protected(*names)
- self._protected_attributes = self.protected_attributes + names
+ def attr_protected(*args)
+ options = args.extract_options!
+ scope = options[:as] || :default
+
+ self._protected_attributes = protected_attributes_configs.dup
+ self._protected_attributes[scope] = self.protected_attributes(scope) + args
+
self._active_authorizer = self._protected_attributes
end
# Specifies a white list of model attributes that can be set via
# mass-assignment.
#
+ # Like +attr_protected+, a scope for the attributes is optional,
+ # if no scope is provided then :default is used. A scope can be defined by
+ # using the :as option.
+ #
# This is the opposite of the +attr_protected+ macro: Mass-assignment
# will only set attributes in this list, to assign to the rest of
# attributes you can use direct writer methods. This is meant to protect
@@ -102,57 +120,90 @@ module ActiveModel
# include ActiveModel::MassAssignmentSecurity
#
# attr_accessor :name, :credit_rating
+ #
# attr_accessible :name
+ # attr_accessible :name, :credit_rating, :as => :admin
#
- # def attributes=(values)
- # sanitize_for_mass_assignment(values).each do |k, v|
+ # def assign_attributes(values, options = {})
+ # sanitize_for_mass_assignment(values, options[:as]).each do |k, v|
# send("#{k}=", v)
# end
# end
# end
#
+ # When using a :default scope :
+ #
# customer = Customer.new
- # customer.attributes = { :name => "David", :credit_rating => "Excellent" }
+ # customer.assign_attributes({ "name" => "David", "credit_rating" => "Excellent", :last_login => 1.day.ago }, :as => :default)
# customer.name # => "David"
# customer.credit_rating # => nil
#
# customer.credit_rating = "Average"
# customer.credit_rating # => "Average"
#
+ # And using the :admin scope :
+ #
+ # customer = Customer.new
+ # customer.assign_attributes({ "name" => "David", "credit_rating" => "Excellent", :last_login => 1.day.ago }, :as => :admin)
+ # customer.name # => "David"
+ # customer.credit_rating # => "Excellent"
+ #
# Note that using <tt>Hash#except</tt> or <tt>Hash#slice</tt> in place of +attr_accessible+
# to sanitize attributes won't provide sufficient protection.
- def attr_accessible(*names)
- self._accessible_attributes = self.accessible_attributes + names
+ def attr_accessible(*args)
+ options = args.extract_options!
+ scope = options[:as] || :default
+
+ self._accessible_attributes = accessible_attributes_configs.dup
+ self._accessible_attributes[scope] = self.accessible_attributes(scope) + args
+
self._active_authorizer = self._accessible_attributes
end
- def protected_attributes
- self._protected_attributes ||= BlackList.new(attributes_protected_by_default).tap do |w|
- w.logger = self.logger if self.respond_to?(:logger)
- end
+ def protected_attributes(scope = :default)
+ protected_attributes_configs[scope]
end
- def accessible_attributes
- self._accessible_attributes ||= WhiteList.new.tap { |w| w.logger = self.logger if self.respond_to?(:logger) }
+ def accessible_attributes(scope = :default)
+ accessible_attributes_configs[scope]
end
- def active_authorizer
- self._active_authorizer ||= protected_attributes
+ def active_authorizers
+ self._active_authorizer ||= protected_attributes_configs
end
+ alias active_authorizer active_authorizers
def attributes_protected_by_default
[]
end
+
+ private
+
+ def protected_attributes_configs
+ self._protected_attributes ||= begin
+ default_black_list = BlackList.new(attributes_protected_by_default).tap do |w|
+ w.logger = self.logger if self.respond_to?(:logger)
+ end
+ Hash.new(default_black_list)
+ end
+ end
+
+ def accessible_attributes_configs
+ self._accessible_attributes ||= begin
+ default_white_list = WhiteList.new.tap { |w| w.logger = self.logger if self.respond_to?(:logger) }
+ Hash.new(default_white_list)
+ end
+ end
end
protected
- def sanitize_for_mass_assignment(attributes)
- mass_assignment_authorizer.sanitize(attributes)
+ def sanitize_for_mass_assignment(attributes, scope = :default)
+ mass_assignment_authorizer(scope).sanitize(attributes)
end
- def mass_assignment_authorizer
- self.class.active_authorizer
+ def mass_assignment_authorizer(scope = :default)
+ self.class.active_authorizer[scope]
end
end
end
diff --git a/activemodel/lib/active_model/observer_array.rb b/activemodel/lib/active_model/observer_array.rb
new file mode 100644
index 0000000000..ab7f86007f
--- /dev/null
+++ b/activemodel/lib/active_model/observer_array.rb
@@ -0,0 +1,104 @@
+require 'set'
+
+module ActiveModel
+ # Stores the enabled/disabled state of individual observers for
+ # a particular model classes.
+ class ObserverArray < Array
+ attr_reader :model_class
+ def initialize(model_class, *args)
+ @model_class = model_class
+ super(*args)
+ end
+
+ def disabled_for?(observer)
+ disabled_observers.include?(observer.class)
+ end
+
+ def disable(*observers, &block)
+ set_enablement(false, observers, &block)
+ end
+
+ def enable(*observers, &block)
+ set_enablement(true, observers, &block)
+ end
+
+ protected
+
+ def disabled_observers
+ @disabled_observers ||= Set.new
+ end
+
+ def observer_class_for(observer)
+ return observer if observer.is_a?(Class)
+
+ if observer.respond_to?(:to_sym) # string/symbol
+ observer.to_s.camelize.constantize
+ else
+ raise ArgumentError, "#{observer} was not a class or a " +
+ "lowercase, underscored class name as expected."
+ end
+ end
+
+ def start_transaction
+ disabled_observer_stack.push(disabled_observers.dup)
+ each_subclass_array do |array|
+ array.start_transaction
+ end
+ end
+
+ def disabled_observer_stack
+ @disabled_observer_stack ||= []
+ end
+
+ def end_transaction
+ @disabled_observers = disabled_observer_stack.pop
+ each_subclass_array do |array|
+ array.end_transaction
+ end
+ end
+
+ def transaction
+ start_transaction
+
+ begin
+ yield
+ ensure
+ end_transaction
+ end
+ end
+
+ def each_subclass_array
+ model_class.descendants.each do |subclass|
+ yield subclass.observers
+ end
+ end
+
+ def set_enablement(enabled, observers)
+ if block_given?
+ transaction do
+ set_enablement(enabled, observers)
+ yield
+ end
+ else
+ observers = ActiveModel::Observer.descendants if observers == [:all]
+ observers.each do |obs|
+ klass = observer_class_for(obs)
+
+ unless klass < ActiveModel::Observer
+ raise ArgumentError.new("#{obs} does not refer to a valid observer")
+ end
+
+ if enabled
+ disabled_observers.delete(klass)
+ else
+ disabled_observers << klass
+ end
+ end
+
+ each_subclass_array do |array|
+ array.set_enablement(enabled, observers)
+ end
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/observing.rb b/activemodel/lib/active_model/observing.rb
index 3c80d584fe..c1ac4eb4af 100644
--- a/activemodel/lib/active_model/observing.rb
+++ b/activemodel/lib/active_model/observing.rb
@@ -1,13 +1,20 @@
require 'singleton'
+require 'active_model/observer_array'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/module/aliasing'
require 'active_support/core_ext/module/remove_method'
require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/enumerable'
+require 'active_support/descendants_tracker'
module ActiveModel
module Observing
extend ActiveSupport::Concern
+ included do
+ extend ActiveSupport::DescendantsTracker
+ end
+
module ClassMethods
# == Active Model Observers Activation
#
@@ -30,12 +37,12 @@ module ActiveModel
# +instantiate_observers+ is called during startup, and before
# each development request.
def observers=(*values)
- @observers = values.flatten
+ observers.replace(values.flatten)
end
# Gets the current observers.
def observers
- @observers ||= []
+ @observers ||= ObserverArray.new(self)
end
# Gets the current observer instances.
@@ -76,7 +83,11 @@ module ActiveModel
elsif observer.respond_to?(:instance)
observer.instance
else
- raise ArgumentError, "#{observer} must be a lowercase, underscored class name (or an instance of the class itself) responding to the instance method. Example: Person.observers = :big_brother # calls BigBrother.instance"
+ raise ArgumentError,
+ "#{observer} must be a lowercase, underscored class name (or an " +
+ "instance of the class itself) responding to the instance " +
+ "method. Example: Person.observers = :big_brother # calls " +
+ "BigBrother.instance"
end
end
@@ -165,6 +176,7 @@ module ActiveModel
#
class Observer
include Singleton
+ extend ActiveSupport::DescendantsTracker
class << self
# Attaches the observer to the supplied model classes.
@@ -210,7 +222,9 @@ module ActiveModel
# Send observed_method(object) if the method exists.
def update(observed_method, object) #:nodoc:
- send(observed_method, object) if respond_to?(observed_method)
+ return unless respond_to?(observed_method)
+ return if disabled_for?(object)
+ send(observed_method, object)
end
# Special method sent by the observed class when it is inherited.
@@ -224,5 +238,11 @@ module ActiveModel
def add_observer!(klass) #:nodoc:
klass.add_observer(self)
end
+
+ def disabled_for?(object)
+ klass = object.class
+ return false unless klass.respond_to?(:observers)
+ klass.observers.disabled_for?(self)
+ end
end
end
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
index d968609e67..5e567307f3 100644
--- a/activemodel/lib/active_model/validations.rb
+++ b/activemodel/lib/active_model/validations.rb
@@ -133,7 +133,7 @@ module ActiveModel
if options.key?(:on)
options = options.dup
options[:if] = Array.wrap(options[:if])
- options[:if] << "validation_context == :#{options[:on]}"
+ options[:if].unshift("validation_context == :#{options[:on]}")
end
args << options
set_callback(:validate, *args, &block)
diff --git a/activemodel/lib/active_model/validations/callbacks.rb b/activemodel/lib/active_model/validations/callbacks.rb
index adc2867ad0..22a77320dc 100644
--- a/activemodel/lib/active_model/validations/callbacks.rb
+++ b/activemodel/lib/active_model/validations/callbacks.rb
@@ -31,7 +31,7 @@ module ActiveModel
options = args.last
if options.is_a?(Hash) && options[:on]
options[:if] = Array.wrap(options[:if])
- options[:if] << "self.validation_context == :#{options[:on]}"
+ options[:if].unshift("self.validation_context == :#{options[:on]}")
end
set_callback(:validation, :before, *args, &block)
end
@@ -41,7 +41,7 @@ module ActiveModel
options[:prepend] = true
options[:if] = Array.wrap(options[:if])
options[:if] << "!halted"
- options[:if] << "self.validation_context == :#{options[:on]}" if options[:on]
+ options[:if].unshift("self.validation_context == :#{options[:on]}") if options[:on]
set_callback(:validation, :after, *(args << options), &block)
end
end
diff --git a/activemodel/test/cases/mass_assignment_security_test.rb b/activemodel/test/cases/mass_assignment_security_test.rb
index f84e55e8d9..b22ce874ea 100644
--- a/activemodel/test/cases/mass_assignment_security_test.rb
+++ b/activemodel/test/cases/mass_assignment_security_test.rb
@@ -10,10 +10,27 @@ class MassAssignmentSecurityTest < ActiveModel::TestCase
assert_equal expected, sanitized
end
+ def test_only_moderator_scope_attribute_accessible
+ user = SpecialUser.new
+ expected = { "name" => "John Smith", "email" => "john@smith.com" }
+ sanitized = user.sanitize_for_mass_assignment(expected.merge("admin" => true), :moderator)
+ assert_equal expected, sanitized
+
+ sanitized = user.sanitize_for_mass_assignment({ "name" => "John Smith", "email" => "john@smith.com", "admin" => true })
+ assert_equal({}, sanitized)
+ end
+
def test_attributes_accessible
user = Person.new
expected = { "name" => "John Smith", "email" => "john@smith.com" }
- sanitized = user.sanitize_for_mass_assignment(expected.merge("super_powers" => true))
+ sanitized = user.sanitize_for_mass_assignment(expected.merge("admin" => true))
+ assert_equal expected, sanitized
+ end
+
+ def test_admin_scoped_attributes_accessible
+ user = Person.new
+ expected = { "name" => "John Smith", "email" => "john@smith.com", "admin" => true }
+ sanitized = user.sanitize_for_mass_assignment(expected.merge("super_powers" => true), :admin)
assert_equal expected, sanitized
end
@@ -26,20 +43,30 @@ class MassAssignmentSecurityTest < ActiveModel::TestCase
def test_mass_assignment_protection_inheritance
assert_blank LoosePerson.accessible_attributes
- assert_equal Set.new([ 'credit_rating', 'administrator']), LoosePerson.protected_attributes
+ assert_equal Set.new(['credit_rating', 'administrator']), LoosePerson.protected_attributes
+
+ assert_blank LoosePerson.accessible_attributes
+ assert_equal Set.new(['credit_rating']), LoosePerson.protected_attributes(:admin)
assert_blank LooseDescendant.accessible_attributes
- assert_equal Set.new([ 'credit_rating', 'administrator', 'phone_number']), LooseDescendant.protected_attributes
+ assert_equal Set.new(['credit_rating', 'administrator', 'phone_number']), LooseDescendant.protected_attributes
assert_blank LooseDescendantSecond.accessible_attributes
- assert_equal Set.new([ 'credit_rating', 'administrator', 'phone_number', 'name']), LooseDescendantSecond.protected_attributes,
+ assert_equal Set.new(['credit_rating', 'administrator', 'phone_number', 'name']), LooseDescendantSecond.protected_attributes,
'Running attr_protected twice in one class should merge the protections'
assert_blank TightPerson.protected_attributes - TightPerson.attributes_protected_by_default
- assert_equal Set.new([ 'name', 'address' ]), TightPerson.accessible_attributes
+ assert_equal Set.new(['name', 'address']), TightPerson.accessible_attributes
+
+ assert_blank TightPerson.protected_attributes(:admin) - TightPerson.attributes_protected_by_default
+ assert_equal Set.new(['name', 'address', 'admin']), TightPerson.accessible_attributes(:admin)
assert_blank TightDescendant.protected_attributes - TightDescendant.attributes_protected_by_default
- assert_equal Set.new([ 'name', 'address', 'phone_number' ]), TightDescendant.accessible_attributes
+ assert_equal Set.new(['name', 'address', 'phone_number']), TightDescendant.accessible_attributes
+
+ assert_blank TightDescendant.protected_attributes(:admin) - TightDescendant.attributes_protected_by_default
+ assert_equal Set.new(['name', 'address', 'admin', 'super_powers']), TightDescendant.accessible_attributes(:admin)
+
end
def test_mass_assignment_multiparameter_protector
diff --git a/activemodel/test/cases/observer_array_test.rb b/activemodel/test/cases/observer_array_test.rb
new file mode 100644
index 0000000000..fc5f18008b
--- /dev/null
+++ b/activemodel/test/cases/observer_array_test.rb
@@ -0,0 +1,220 @@
+require 'cases/helper'
+require 'models/observers'
+
+class ObserverArrayTest < ActiveModel::TestCase
+ def teardown
+ ORM.observers.enable :all
+ Budget.observers.enable :all
+ Widget.observers.enable :all
+ end
+
+ def assert_observer_notified(model_class, observer_class)
+ observer_class.instance.before_save_invocations.clear
+ model_instance = model_class.new
+ model_instance.save
+ assert_equal [model_instance], observer_class.instance.before_save_invocations
+ end
+
+ def assert_observer_not_notified(model_class, observer_class)
+ observer_class.instance.before_save_invocations.clear
+ model_instance = model_class.new
+ model_instance.save
+ assert_equal [], observer_class.instance.before_save_invocations
+ end
+
+ test "all observers are enabled by default" do
+ assert_observer_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "can disable individual observers using a class constant" do
+ ORM.observers.disable WidgetObserver
+
+ assert_observer_not_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "can enable individual observers using a class constant" do
+ ORM.observers.disable :all
+ ORM.observers.enable AuditTrail
+
+ assert_observer_not_notified Widget, WidgetObserver
+ assert_observer_not_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "can disable individual observers using a symbol" do
+ ORM.observers.disable :budget_observer
+
+ assert_observer_notified Widget, WidgetObserver
+ assert_observer_not_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "can enable individual observers using a symbol" do
+ ORM.observers.disable :all
+ ORM.observers.enable :audit_trail
+
+ assert_observer_not_notified Widget, WidgetObserver
+ assert_observer_not_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "can disable multiple observers at a time" do
+ ORM.observers.disable :widget_observer, :budget_observer
+
+ assert_observer_not_notified Widget, WidgetObserver
+ assert_observer_not_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "can enable multiple observers at a time" do
+ ORM.observers.disable :all
+ ORM.observers.enable :widget_observer, :budget_observer
+
+ assert_observer_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_not_notified Widget, AuditTrail
+ assert_observer_not_notified Budget, AuditTrail
+ end
+
+ test "can disable all observers using :all" do
+ ORM.observers.disable :all
+
+ assert_observer_not_notified Widget, WidgetObserver
+ assert_observer_not_notified Budget, BudgetObserver
+ assert_observer_not_notified Widget, AuditTrail
+ assert_observer_not_notified Budget, AuditTrail
+ end
+
+ test "can enable all observers using :all" do
+ ORM.observers.disable :all
+ ORM.observers.enable :all
+
+ assert_observer_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "can disable observers on individual models without affecting those observers on other models" do
+ Widget.observers.disable :all
+
+ assert_observer_not_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_not_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "can enable observers on individual models without affecting those observers on other models" do
+ ORM.observers.disable :all
+ Budget.observers.enable AuditTrail
+
+ assert_observer_not_notified Widget, WidgetObserver
+ assert_observer_not_notified Budget, BudgetObserver
+ assert_observer_not_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "can disable observers for the duration of a block" do
+ yielded = false
+ ORM.observers.disable :budget_observer do
+ yielded = true
+ assert_observer_notified Widget, WidgetObserver
+ assert_observer_not_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ assert yielded
+ assert_observer_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "can enable observers for the duration of a block" do
+ yielded = false
+ Widget.observers.disable :all
+
+ Widget.observers.enable :all do
+ yielded = true
+ assert_observer_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ assert yielded
+ assert_observer_not_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_not_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "raises an appropriate error when a developer accidentally enables or disables the wrong class (i.e. Widget instead of WidgetObserver)" do
+ assert_raise ArgumentError do
+ ORM.observers.enable :widget
+ end
+
+ assert_raise ArgumentError do
+ ORM.observers.enable Widget
+ end
+
+ assert_raise ArgumentError do
+ ORM.observers.disable :widget
+ end
+
+ assert_raise ArgumentError do
+ ORM.observers.disable Widget
+ end
+ end
+
+ test "allows #enable at the superclass level to override #disable at the subclass level when called last" do
+ Widget.observers.disable :all
+ ORM.observers.enable :all
+
+ assert_observer_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ test "allows #disable at the superclass level to override #enable at the subclass level when called last" do
+ Budget.observers.enable :audit_trail
+ ORM.observers.disable :audit_trail
+
+ assert_observer_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_not_notified Widget, AuditTrail
+ assert_observer_not_notified Budget, AuditTrail
+ end
+
+ test "can use the block form at different levels of the hierarchy" do
+ yielded = false
+ Widget.observers.disable :all
+
+ ORM.observers.enable :all do
+ yielded = true
+ assert_observer_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+
+ assert yielded
+ assert_observer_not_notified Widget, WidgetObserver
+ assert_observer_notified Budget, BudgetObserver
+ assert_observer_not_notified Widget, AuditTrail
+ assert_observer_notified Budget, AuditTrail
+ end
+end
+
diff --git a/activemodel/test/cases/observing_test.rb b/activemodel/test/cases/observing_test.rb
index 63686843b6..99b1f407ae 100644
--- a/activemodel/test/cases/observing_test.rb
+++ b/activemodel/test/cases/observing_test.rb
@@ -43,6 +43,11 @@ class ObservingTest < ActiveModel::TestCase
assert ObservedModel.observers.include?(:bar), ":bar not in #{ObservedModel.observers.inspect}"
end
+ test "uses an ObserverArray so observers can be disabled" do
+ ObservedModel.observers = [:foo, :bar]
+ assert ObservedModel.observers.is_a?(ActiveModel::ObserverArray)
+ end
+
test "instantiates observer names passed as strings" do
ObservedModel.observers << 'foo_observer'
FooObserver.expects(:instance)
diff --git a/activemodel/test/cases/secure_password_test.rb b/activemodel/test/cases/secure_password_test.rb
index c455cf57b3..6950c3be1f 100644
--- a/activemodel/test/cases/secure_password_test.rb
+++ b/activemodel/test/cases/secure_password_test.rb
@@ -45,13 +45,14 @@ class SecurePasswordTest < ActiveModel::TestCase
end
test "visitor#password_digest should be protected against mass assignment" do
- assert Visitor.active_authorizer.kind_of?(ActiveModel::MassAssignmentSecurity::BlackList)
- assert Visitor.active_authorizer.include?(:password_digest)
+ assert Visitor.active_authorizers[:default].kind_of?(ActiveModel::MassAssignmentSecurity::BlackList)
+ assert Visitor.active_authorizers[:default].include?(:password_digest)
end
test "Administrator's mass_assignment_authorizer should be WhiteList" do
- assert Administrator.active_authorizer.kind_of?(ActiveModel::MassAssignmentSecurity::WhiteList)
- assert !Administrator.active_authorizer.include?(:password_digest)
- assert Administrator.active_authorizer.include?(:name)
+ active_authorizer = Administrator.active_authorizers[:default]
+ assert active_authorizer.kind_of?(ActiveModel::MassAssignmentSecurity::WhiteList)
+ assert !active_authorizer.include?(:password_digest)
+ assert active_authorizer.include?(:name)
end
end
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
index 2f36195627..0b50acf913 100644
--- a/activemodel/test/cases/validations_test.rb
+++ b/activemodel/test/cases/validations_test.rb
@@ -212,6 +212,20 @@ class ValidationsTest < ActiveModel::TestCase
assert_equal 'is too short (minimum is 2 characters)', t.errors[key][0]
end
+ def test_validaton_with_if_and_on
+ Topic.validates_presence_of :title, :if => Proc.new{|x| x.author_name = "bad"; true }, :on => :update
+
+ t = Topic.new(:title => "")
+
+ # If block should not fire
+ assert t.valid?
+ assert t.author_name.nil?
+
+ # If block should fire
+ assert t.invalid?(:update)
+ assert t.author_name == "bad"
+ end
+
def test_invalid_should_be_the_opposite_of_valid
Topic.validates_presence_of :title
diff --git a/activemodel/test/models/mass_assignment_specific.rb b/activemodel/test/models/mass_assignment_specific.rb
index 2a8fe170c2..53b37369ff 100644
--- a/activemodel/test/models/mass_assignment_specific.rb
+++ b/activemodel/test/models/mass_assignment_specific.rb
@@ -5,9 +5,17 @@ class User
public :sanitize_for_mass_assignment
end
+class SpecialUser
+ include ActiveModel::MassAssignmentSecurity
+ attr_accessible :name, :email, :as => :moderator
+
+ public :sanitize_for_mass_assignment
+end
+
class Person
include ActiveModel::MassAssignmentSecurity
attr_accessible :name, :email
+ attr_accessible :name, :email, :admin, :as => :admin
public :sanitize_for_mass_assignment
end
@@ -32,6 +40,7 @@ end
class LoosePerson
include ActiveModel::MassAssignmentSecurity
attr_protected :credit_rating, :administrator
+ attr_protected :credit_rating, :as => :admin
end
class LooseDescendant < LoosePerson
@@ -46,6 +55,7 @@ end
class TightPerson
include ActiveModel::MassAssignmentSecurity
attr_accessible :name, :address
+ attr_accessible :name, :address, :admin, :as => :admin
def self.attributes_protected_by_default
["mobile_number"]
@@ -54,4 +64,5 @@ end
class TightDescendant < TightPerson
attr_accessible :phone_number
+ attr_accessible :super_powers, :as => :admin
end \ No newline at end of file
diff --git a/activemodel/test/models/observers.rb b/activemodel/test/models/observers.rb
new file mode 100644
index 0000000000..3729b3435e
--- /dev/null
+++ b/activemodel/test/models/observers.rb
@@ -0,0 +1,27 @@
+class ORM
+ include ActiveModel::Observing
+
+ def save
+ notify_observers :before_save
+ end
+
+ class Observer < ActiveModel::Observer
+ def before_save_invocations
+ @before_save_invocations ||= []
+ end
+
+ def before_save(record)
+ before_save_invocations << record
+ end
+ end
+end
+
+class Widget < ORM; end
+class Budget < ORM; end
+class WidgetObserver < ORM::Observer; end
+class BudgetObserver < ORM::Observer; end
+class AuditTrail < ORM::Observer
+ observe :widget, :budget
+end
+
+ORM.instantiate_observers
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 9a01d793f9..04c12f86b6 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -1621,11 +1621,11 @@ end
# Allows you to set all the attributes at once by passing in a hash with keys
# matching the attribute names (which again matches the column names).
#
- # If +guard_protected_attributes+ is true (the default), then sensitive
- # attributes can be protected from this form of mass-assignment by using
- # the +attr_protected+ macro. Or you can alternatively specify which
- # attributes *can* be accessed with the +attr_accessible+ macro. Then all the
- # attributes not included in that won't be allowed to be mass-assigned.
+ # If any attributes are protected by either +attr_protected+ or
+ # +attr_accessible+ then only settable attributes will be assigned.
+ #
+ # The +guard_protected_attributes+ argument is now deprecated, use
+ # the +assign_attributes+ method if you want to bypass mass-assignment security.
#
# class User < ActiveRecord::Base
# attr_protected :is_admin
@@ -1635,15 +1635,59 @@ end
# user.attributes = { :username => 'Phusion', :is_admin => true }
# user.username # => "Phusion"
# user.is_admin? # => false
+ def attributes=(new_attributes, guard_protected_attributes = nil)
+ unless guard_protected_attributes.nil?
+ message = "the use of 'guard_protected_attributes' will be removed from the next major release of rails, " +
+ "if you want to bypass mass-assignment security then look into using assign_attributes"
+ ActiveSupport::Deprecation.warn(message)
+ end
+
+ return unless new_attributes.is_a?(Hash)
+
+ guard_protected_attributes ||= true
+ if guard_protected_attributes
+ assign_attributes(new_attributes)
+ else
+ assign_attributes(new_attributes, :without_protection => true)
+ end
+ end
+
+ # Allows you to set all the attributes for a particular mass-assignment
+ # security scope by passing in a hash of attributes with keys matching
+ # the attribute names (which again matches the column names) and the scope
+ # name using the :as option.
#
- # user.send(:attributes=, { :username => 'Phusion', :is_admin => true }, false)
+ # To bypass mass-assignment security you can use the :without_protection => true
+ # option.
+ #
+ # class User < ActiveRecord::Base
+ # attr_accessible :name
+ # attr_accessible :name, :is_admin, :as => :admin
+ # end
+ #
+ # user = User.new
+ # user.assign_attributes({ :name => 'Josh', :is_admin => true })
+ # user.name # => "Josh"
+ # user.is_admin? # => false
+ #
+ # user = User.new
+ # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :as => :admin)
+ # user.name # => "Josh"
# user.is_admin? # => true
- def attributes=(new_attributes, guard_protected_attributes = true)
- return unless new_attributes.is_a?(Hash)
+ #
+ # user = User.new
+ # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true)
+ # user.name # => "Josh"
+ # user.is_admin? # => true
+ def assign_attributes(new_attributes, options = {})
attributes = new_attributes.stringify_keys
+ scope = options[:as] || :default
multi_parameter_attributes = []
- attributes = sanitize_for_mass_assignment(attributes) if guard_protected_attributes
+
+ unless options[:without_protection]
+ attributes = sanitize_for_mass_assignment(attributes, scope)
+ end
attributes.each do |k, v|
if k.include?("(")
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
index 5ff81aa023..6d52cc344d 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -62,6 +62,13 @@ module ActiveRecord
exec_query(sql, name, binds)
end
+ # Executes delete +sql+ statement in the context of this connection using
+ # +binds+ as the bind substitutes. +name+ is the logged along with
+ # the executed +sql+ statement.
+ def exec_delete(sql, name, binds)
+ exec_query(sql, name, binds)
+ end
+
# Returns the last auto-generated ID from the affected table.
#
# +id_value+ will be returned unless the value is nil, in
@@ -82,8 +89,8 @@ module ActiveRecord
end
# Executes the delete statement and returns the number of rows affected.
- def delete(sql, name = nil)
- delete_sql(sql, name)
+ def delete(sql, name = nil, binds = [])
+ exec_delete(sql, name, binds)
end
# Checks whether there is currently no transaction active. This is done
@@ -287,10 +294,6 @@ module ActiveRecord
execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert'
end
- def null_insert_value
- Arel.sql 'DEFAULT'
- end
-
def empty_insert_statement_value
"VALUES(DEFAULT)"
end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
index fc91814275..dee5c93b24 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -1,5 +1,6 @@
# encoding: utf-8
+gem 'mysql2', '~> 0.3.0'
require 'mysql2'
module ActiveRecord
@@ -291,6 +292,14 @@ module ActiveRecord
execute sql.gsub('?') { quote(*binds.shift.reverse) }, name
end
+ def exec_delete(sql, name, binds)
+ binds = binds.dup
+
+ # Pretend to support bind parameters
+ execute sql.gsub('?') { quote(*binds.shift.reverse) }, name
+ @connection.affected_rows
+ end
+
def last_inserted_id(result)
@connection.last_id
end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
index eaadbc179b..6bc3b1548f 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -3,15 +3,8 @@ require 'active_support/core_ext/kernel/requires'
require 'active_support/core_ext/object/blank'
require 'set'
-begin
- require 'mysql'
-rescue LoadError
- raise "!!! Missing the mysql gem. Add it to your Gemfile: gem 'mysql'"
-end
-
-unless defined?(Mysql::Result) && Mysql::Result.method_defined?(:each_hash)
- raise "!!! Outdated mysql gem. Upgrade to 2.8.1 or later. In your Gemfile: gem 'mysql', '2.8.1'. Or use gem 'mysql2'"
-end
+gem 'mysql', '~> 2.8.1'
+require 'mysql'
class Mysql
class Time
@@ -402,34 +395,9 @@ module ActiveRecord
def exec_query(sql, name = 'SQL', binds = [])
log(sql, name, binds) do
- result = nil
-
- cache = {}
- if binds.empty?
- stmt = @connection.prepare(sql)
- else
- cache = @statements[sql] ||= {
- :stmt => @connection.prepare(sql)
- }
- stmt = cache[:stmt]
- end
-
- stmt.execute(*binds.map { |col, val|
- type_cast(val, col)
- })
- if metadata = stmt.result_metadata
- cols = cache[:cols] ||= metadata.fetch_fields.map { |field|
- field.name
- }
-
- metadata.free
- result = ActiveRecord::Result.new(cols, stmt.to_a)
+ exec_stmt(sql, name, binds) do |cols, stmt|
+ ActiveRecord::Result.new(cols, stmt.to_a) if cols
end
-
- stmt.free_result
- stmt.close if binds.empty?
-
- result
end
end
@@ -481,6 +449,14 @@ module ActiveRecord
@connection.affected_rows
end
+ def exec_delete(sql, name, binds)
+ log(sql, name, binds) do
+ exec_stmt(sql, name, binds) do |cols, stmt|
+ stmt.affected_rows
+ end
+ end
+ end
+
def begin_db_transaction #:nodoc:
exec_without_stmt "BEGIN"
rescue Mysql::Error
@@ -840,6 +816,46 @@ module ActiveRecord
end
private
+ def exec_stmt(sql, name, binds)
+ cache = {}
+ if binds.empty?
+ stmt = @connection.prepare(sql)
+ else
+ cache = @statements[sql] ||= {
+ :stmt => @connection.prepare(sql)
+ }
+ stmt = cache[:stmt]
+ end
+
+
+ begin
+ stmt.execute(*binds.map { |col, val| type_cast(val, col) })
+ rescue Mysql::Error => e
+ # Older versions of MySQL leave the prepared statement in a bad
+ # place when an error occurs. To support older mysql versions, we
+ # need to close the statement and delete the statement from the
+ # cache.
+ stmt.close
+ @statements.delete sql
+ raise e
+ end
+
+ cols = nil
+ if metadata = stmt.result_metadata
+ cols = cache[:cols] ||= metadata.fetch_fields.map { |field|
+ field.name
+ }
+ end
+
+ result = yield [cols, stmt]
+
+ stmt.result_metadata.free if cols
+ stmt.free_result
+ stmt.close if binds.empty?
+
+ result
+ end
+
def connect
encoding = @config[:encoding]
if encoding
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index aa9c9f5889..70d3d58c8f 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -98,6 +98,9 @@ module ActiveRecord
# XML type
when 'xml'
:xml
+ # tsvector type
+ when 'tsvector'
+ :tsvector
# Arrays
when /^\D+\[\]$/
:string
@@ -119,6 +122,14 @@ module ActiveRecord
# Extracts the value from a PostgreSQL column default definition.
def self.extract_value_from_default(default)
case default
+ # This is a performance optimization for Ruby 1.9.2 in development.
+ # If the value is nil, we return nil straight away without checking
+ # the regular expressions. If we check each regular expression,
+ # Regexp#=== will call NilClass#to_str, which will trigger
+ # method_missing (defined by whiny nil in ActiveSupport) which
+ # makes this method very very slow.
+ when NilClass
+ nil
# Numeric types
when /\A\(?(-?\d+(\.\d*)?\)?)\z/
$1
@@ -189,6 +200,11 @@ module ActiveRecord
options = args.extract_options!
column(args[0], 'xml', options)
end
+
+ def tsvector(*args)
+ options = args.extract_options!
+ column(args[0], 'tsvector', options)
+ end
end
ADAPTER_NAME = 'PostgreSQL'
@@ -206,7 +222,8 @@ module ActiveRecord
:date => { :name => "date" },
:binary => { :name => "bytea" },
:boolean => { :name => "boolean" },
- :xml => { :name => "xml" }
+ :xml => { :name => "xml" },
+ :tsvector => { :name => "tsvector" }
}
# Returns 'PostgreSQL' as adapter name for identification purposes.
@@ -228,7 +245,6 @@ module ActiveRecord
# @local_tz is initialized as nil to avoid warnings when connect tries to use it
@local_tz = nil
@table_alias_length = nil
- @postgresql_version = nil
@statements = {}
connect
@@ -250,28 +266,16 @@ module ActiveRecord
# Is this connection alive and ready for queries?
def active?
- if @connection.respond_to?(:status)
- @connection.status == PGconn::CONNECTION_OK
- else
- # We're asking the driver, not Active Record, so use @connection.query instead of #query
- @connection.query 'SELECT 1'
- true
- end
- # postgres-pr raises a NoMethodError when querying if no connection is available.
- rescue PGError, NoMethodError
+ @connection.status == PGconn::CONNECTION_OK
+ rescue PGError
false
end
# Close then reopen the connection.
def reconnect!
- if @connection.respond_to?(:reset)
- clear_cache!
- @connection.reset
- configure_connection
- else
- disconnect!
- connect
- end
+ clear_cache!
+ @connection.reset
+ configure_connection
end
def reset!
@@ -425,17 +429,17 @@ module ActiveRecord
# REFERENTIAL INTEGRITY ====================================
- def supports_disable_referential_integrity?() #:nodoc:
+ def supports_disable_referential_integrity? #:nodoc:
true
end
def disable_referential_integrity #:nodoc:
- if supports_disable_referential_integrity?() then
+ if supports_disable_referential_integrity? then
execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";"))
end
yield
ensure
- if supports_disable_referential_integrity?() then
+ if supports_disable_referential_integrity? then
execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";"))
end
end
@@ -509,12 +513,7 @@ module ActiveRecord
# Queries the database and returns the results in an Array-like object
def query(sql, name = nil) #:nodoc:
log(sql, name) do
- if @async
- res = @connection.async_exec(sql)
- else
- res = @connection.exec(sql)
- end
- return result_as_array(res)
+ result_as_array @connection.async_exec(sql)
end
end
@@ -522,11 +521,7 @@ module ActiveRecord
# or raising a PGError exception otherwise.
def execute(sql, name = nil)
log(sql, name) do
- if @async
- @connection.async_exec(sql)
- else
- @connection.exec(sql)
- end
+ @connection.async_exec(sql)
end
end
@@ -535,30 +530,26 @@ module ActiveRecord
end
def exec_query(sql, name = 'SQL', binds = [])
- return exec_no_cache(sql, name) if binds.empty?
-
log(sql, name, binds) do
- unless @statements.key? sql
- nextkey = "a#{@statements.length + 1}"
- @connection.prepare nextkey, sql
- @statements[sql] = nextkey
- end
-
- key = @statements[sql]
+ result = binds.empty? ? exec_no_cache(sql, binds) :
+ exec_cache(sql, binds)
- # Clear the queue
- @connection.get_last_result
- @connection.send_query_prepared(key, binds.map { |col, val|
- type_cast(val, col)
- })
- @connection.block
- result = @connection.get_last_result
ret = ActiveRecord::Result.new(result.fields, result_as_array(result))
result.clear
return ret
end
end
+ def exec_delete(sql, name = 'SQL', binds = [])
+ log(sql, name, binds) do
+ result = binds.empty? ? exec_no_cache(sql, binds) :
+ exec_cache(sql, binds)
+ affected = result.cmd_tuples
+ result.clear
+ affected
+ end
+ end
+
def sql_for_insert(sql, pk, id_value, sequence_name, binds)
unless pk
_, table = extract_schema_and_table(sql.split(" ", 4)[2])
@@ -945,22 +936,7 @@ module ActiveRecord
protected
# Returns the version of the connected PostgreSQL server.
def postgresql_version
- @postgresql_version ||=
- if @connection.respond_to?(:server_version)
- @connection.server_version
- else
- # Mimic PGconn.server_version behavior
- begin
- if query('SELECT version()')[0][0] =~ /PostgreSQL ([0-9.]+)/
- major, minor, tiny = $1.split(".")
- (major.to_i * 10000) + (minor.to_i * 100) + tiny.to_i
- else
- 0
- end
- rescue
- 0
- end
- end
+ @connection.server_version
end
def translate_exception(exception, message)
@@ -975,13 +951,26 @@ module ActiveRecord
end
private
- def exec_no_cache(sql, name)
- log(sql, name) do
- result = @connection.async_exec(sql)
- ret = ActiveRecord::Result.new(result.fields, result_as_array(result))
- result.clear
- ret
+ def exec_no_cache(sql, binds)
+ @connection.async_exec(sql)
+ end
+
+ def exec_cache(sql, binds)
+ unless @statements.key? sql
+ nextkey = "a#{@statements.length + 1}"
+ @connection.prepare nextkey, sql
+ @statements[sql] = nextkey
end
+
+ key = @statements[sql]
+
+ # Clear the queue
+ @connection.get_last_result
+ @connection.send_query_prepared(key, binds.map { |col, val|
+ type_cast(val, col)
+ })
+ @connection.block
+ @connection.get_last_result
end
# The internal PostgreSQL identifier of the money data type.
@@ -993,10 +982,6 @@ module ActiveRecord
# connected server's characteristics.
def connect
@connection = PGconn.connect(*@connection_parameters)
- PGconn.translate_results = false if PGconn.respond_to?(:translate_results=)
-
- # Ignore async_exec and async_query when using postgres-pr.
- @async = @connection.respond_to?(:async_exec)
# Money type has a fixed precision of 10 in PostgreSQL 8.2 and below, and as of
# PostgreSQL 8.3 it has a fixed precision of 19. PostgreSQLColumn.extract_precision
@@ -1010,11 +995,7 @@ module ActiveRecord
# This is called by #connect and should not be called manually.
def configure_connection
if @config[:encoding]
- if @connection.respond_to?(:set_client_encoding)
- @connection.set_client_encoding(@config[:encoding])
- else
- execute("SET client_encoding TO '#{@config[:encoding]}'")
- end
+ @connection.set_client_encoding(@config[:encoding])
end
self.client_min_messages = @config[:min_messages] if @config[:min_messages]
self.schema_search_path = @config[:schema_search_path] || @config[:schema_order]
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
index 4540cf015b..fe2868f367 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
@@ -183,6 +183,11 @@ module ActiveRecord
end
end
+ def exec_delete(sql, name = 'SQL', binds = [])
+ exec_query(sql, name, binds)
+ @connection.changes
+ end
+
def last_inserted_id(result)
@connection.last_insert_row_id
end
@@ -357,10 +362,6 @@ module ActiveRecord
alter_table(table_name, :rename => {column_name.to_s => new_column_name.to_s})
end
- def null_insert_value
- Arel.sql 'NULL'
- end
-
def empty_insert_statement_value
"VALUES(NULL)"
end
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index a916c88348..b4531ed35f 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -77,7 +77,15 @@ module ActiveRecord
def destroy
if persisted?
IdentityMap.remove(self) if IdentityMap.enabled?
- self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).delete_all
+ pk = self.class.primary_key
+ column = self.class.columns_hash[pk]
+ substitute = connection.substitute_at(column, 0)
+
+ relation = self.class.unscoped.where(
+ self.class.arel_table[pk].eq(substitute))
+
+ relation.bind_values = [[column, id]]
+ relation.delete_all
end
@destroyed = true
@@ -136,22 +144,27 @@ module ActiveRecord
# Updates the attributes of the model from the passed-in hash and saves the
# record, all wrapped in a transaction. If the object is invalid, the saving
# will fail and false will be returned.
- def update_attributes(attributes)
+ #
+ # When updating model attributes, mass-assignment security protection is respected.
+ # If no +:as+ option is supplied then the +:default+ scope will be used.
+ # If you want to bypass the protection given by +attr_protected+ and
+ # +attr_accessible+ then you can do so using the +:without_protection+ option.
+ def update_attributes(attributes, options = {})
# The following transaction covers any possible database side-effects of the
# attributes assignment. For example, setting the IDs of a child collection.
with_transaction_returning_status do
- self.attributes = attributes
+ self.assign_attributes(attributes, options)
save
end
end
# Updates its receiver just like +update_attributes+ but calls <tt>save!</tt> instead
# of +save+, so an exception is raised if the record is invalid.
- def update_attributes!(attributes)
+ def update_attributes!(attributes, options = {})
# The following transaction covers any possible database side-effects of the
# attributes assignment. For example, setting the IDs of a child collection.
with_transaction_returning_status do
- self.attributes = attributes
+ self.assign_attributes(attributes, options)
save!
end
end
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index cace6f0cc0..d38588519b 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -50,6 +50,9 @@ module ActiveRecord
initializer "active_record.set_configs" do |app|
ActiveSupport.on_load(:active_record) do
+ if app.config.active_record.delete(:whitelist_attributes)
+ attr_accessible(nil)
+ end
app.config.active_record.each do |k,v|
send "#{k}=", v
end
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 6b3c38cb58..7d76d7a19f 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -70,7 +70,13 @@ db_namespace = namespace :db do
@charset = ENV['CHARSET'] || 'utf8'
@collation = ENV['COLLATION'] || 'utf8_unicode_ci'
creation_options = {:charset => (config['charset'] || @charset), :collation => (config['collation'] || @collation)}
- error_class = config['adapter'] =~ /mysql2/ ? Mysql2::Error : Mysql::Error
+ if config['adapter'] =~ /jdbc/
+ #FIXME After Jdbcmysql gives this class
+ require 'active_record/railties/jdbcmysql_error'
+ error_class = ArJdbcMySQL::Error
+ else
+ error_class = config['adapter'] =~ /mysql2/ ? Mysql2::Error : Mysql::Error
+ end
access_denied_error = 1045
begin
ActiveRecord::Base.establish_connection(config.merge('database' => nil))
@@ -94,7 +100,7 @@ db_namespace = namespace :db do
$stderr.puts "(if you set the charset manually, make sure you have a matching collation)" if config['charset']
end
end
- when 'postgresql'
+ when /postgresql/
@encoding = config['encoding'] || ENV['CHARSET'] || 'utf8'
begin
ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
diff --git a/activerecord/lib/active_record/railties/jdbcmysql_error.rb b/activerecord/lib/active_record/railties/jdbcmysql_error.rb
new file mode 100644
index 0000000000..6b9af2a0cb
--- /dev/null
+++ b/activerecord/lib/active_record/railties/jdbcmysql_error.rb
@@ -0,0 +1,16 @@
+#FIXME Remove if ArJdbcMysql will give.
+module ArJdbcMySQL
+ class Error < StandardError
+ attr_accessor :error_number, :sql_state
+
+ def initialize msg
+ super
+ @error_number = nil
+ @sql_state = nil
+ end
+
+ # Mysql gem compatibility
+ alias_method :errno, :error_number
+ alias_method :error, :message
+ end
+end
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 45a7000cce..658a949331 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -60,7 +60,7 @@ module ActiveRecord
end
if values.empty? # empty insert
- im.values = im.create_values [connection.null_insert_value], []
+ im.values = Arel.sql(connection.empty_insert_statement_value)
else
im.insert substitutes
end
@@ -338,7 +338,9 @@ module ActiveRecord
where(conditions).delete_all
else
statement = arel.compile_delete
- affected = @klass.connection.delete statement.to_sql
+ affected = @klass.connection.delete(
+ statement.to_sql, 'SQL', bind_values)
+
reset
affected
end
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index a3d4b7f45a..57c9921ea8 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -279,8 +279,8 @@ module ActiveRecord
unless record
record = @klass.new do |r|
- r.send(:attributes=, protected_attributes_for_create, true) unless protected_attributes_for_create.empty?
- r.send(:attributes=, unprotected_attributes_for_create, false) unless unprotected_attributes_for_create.empty?
+ r.assign_attributes(protected_attributes_for_create)
+ r.assign_attributes(unprotected_attributes_for_create, :without_protection => true)
end
yield(record) if block_given?
record.save if match.instantiator == :create
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
index 982b3d7e9f..2814771002 100644
--- a/activerecord/lib/active_record/relation/predicate_builder.rb
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -25,7 +25,18 @@ module ActiveRecord
values = value.to_a.map { |x|
x.is_a?(ActiveRecord::Base) ? x.id : x
}
- attribute.in(values)
+
+ if values.include?(nil)
+ values = values.compact
+ if values.empty?
+ attribute.eq nil
+ else
+ attribute.in(values.compact).or attribute.eq(nil)
+ end
+ else
+ attribute.in(values)
+ end
+
when Range, Arel::Relation
attribute.in(value)
when ActiveRecord::Base
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index d1225a9ed9..4db4105389 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -56,8 +56,9 @@ module ActiveRecord
column = klass.columns_hash[attribute.to_s]
value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s if column.text?
- if !options[:case_sensitive] && column.text?
- relation = table[attribute].matches(value)
+ if !options[:case_sensitive] && value && column.text?
+ # will use SQL LOWER function before comparison
+ relation = table[attribute].lower.eq(table.lower(value))
else
value = klass.connection.case_sensitive_modifier(value)
relation = table[attribute].eq(value)
diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
index 5bb8fa2f93..ce08e4c6a7 100644
--- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
@@ -3,6 +3,9 @@ require "cases/helper"
class PostgresqlArray < ActiveRecord::Base
end
+class PostgresqlTsvector < ActiveRecord::Base
+end
+
class PostgresqlMoney < ActiveRecord::Base
end
@@ -34,6 +37,9 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase
@connection.execute("INSERT INTO postgresql_arrays (commission_by_quarter, nicknames) VALUES ( '{35000,21000,18000,17000}', '{foo,bar,baz}' )")
@first_array = PostgresqlArray.find(1)
+ @connection.execute("INSERT INTO postgresql_tsvectors (text_vector) VALUES (' ''text'' ''vector'' ')")
+ @first_tsvector = PostgresqlTsvector.find(1)
+
@connection.execute("INSERT INTO postgresql_moneys (wealth) VALUES ('567.89'::money)")
@connection.execute("INSERT INTO postgresql_moneys (wealth) VALUES ('-567.89'::money)")
@first_money = PostgresqlMoney.find(1)
@@ -62,6 +68,10 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase
assert_equal :string, @first_array.column_for_attribute(:nicknames).type
end
+ def test_data_type_of_tsvector_types
+ assert_equal :tsvector, @first_tsvector.column_for_attribute(:text_vector).type
+ end
+
def test_data_type_of_money_types
assert_equal :decimal, @first_money.column_for_attribute(:wealth).type
end
@@ -95,11 +105,26 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase
assert_equal '{foo,bar,baz}', @first_array.nicknames
end
+ def test_tsvector_values
+ assert_equal "'text' 'vector'", @first_tsvector.text_vector
+ end
+
def test_money_values
assert_equal 567.89, @first_money.wealth
assert_equal(-567.89, @second_money.wealth)
end
+ def test_update_tsvector
+ new_text_vector = "'new' 'text' 'vector'"
+ assert @first_tsvector.text_vector = new_text_vector
+ assert @first_tsvector.save
+ assert @first_tsvector.reload
+ assert @first_tsvector.text_vector = new_text_vector
+ assert @first_tsvector.save
+ assert @first_tsvector.reload
+ assert_equal @first_tsvector.text_vector, new_text_vector
+ end
+
def test_number_values
assert_equal 123.456, @first_number.single
assert_equal 123456.789, @first_number.double
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index 815ff7b825..5ee3b2d776 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -18,7 +18,7 @@ require 'models/comment'
require 'models/minimalistic'
require 'models/warehouse_thing'
require 'models/parrot'
-require 'models/loose_person'
+require 'models/person'
require 'models/edge'
require 'models/joke'
require 'rexml/document'
@@ -489,6 +489,12 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal 'value2', weird.send('a$b')
end
+ def test_attributes_guard_protected_attributes_is_deprecated
+ attributes = { "title" => "An amazing title" }
+ topic = Topic.new
+ assert_deprecated { topic.send(:attributes=, attributes, false) }
+ end
+
def test_multiparameter_attributes_on_date
attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "24" }
topic = Topic.find(1)
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 655437318f..be4ba18555 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -1045,6 +1045,29 @@ class FinderTest < ActiveRecord::TestCase
:order => ' author_addresses_authors.id DESC ', :limit => 3).size
end
+ def test_find_with_nil_inside_set_passed_for_one_attribute
+ client_of = Company.find(
+ :all,
+ :conditions => {
+ :client_of => [2, 1, nil],
+ :name => ['37signals', 'Summit', 'Microsoft'] },
+ :order => 'client_of DESC'
+ ).map { |x| x.client_of }
+
+ assert client_of.include?(nil)
+ assert_equal [2, 1].sort, client_of.compact.sort
+ end
+
+ def test_find_with_nil_inside_set_passed_for_attribute
+ client_of = Company.find(
+ :all,
+ :conditions => { :client_of => [nil] },
+ :order => 'client_of DESC'
+ ).map { |x| x.client_of }
+
+ assert_equal [], client_of.compact
+ end
+
def test_with_limiting_with_custom_select
posts = Post.find(:all, :include => :author, :select => ' posts.*, authors.id as "author_id"', :limit => 3, :order => 'posts.id')
assert_equal 3, posts.size
diff --git a/activerecord/test/cases/mass_assignment_security_test.rb b/activerecord/test/cases/mass_assignment_security_test.rb
index 025ec1d3fa..2c051bff84 100644
--- a/activerecord/test/cases/mass_assignment_security_test.rb
+++ b/activerecord/test/cases/mass_assignment_security_test.rb
@@ -3,6 +3,7 @@ require 'models/company'
require 'models/subscriber'
require 'models/keyboard'
require 'models/task'
+require 'models/person'
class MassAssignmentSecurityTest < ActiveRecord::TestCase
@@ -30,6 +31,66 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase
end
end
+ def test_assign_attributes_uses_default_scope_when_no_scope_is_provided
+ p = LoosePerson.new
+ p.assign_attributes(attributes_hash)
+
+ assert_equal nil, p.id
+ assert_equal 'Josh', p.first_name
+ assert_equal 'm', p.gender
+ assert_equal nil, p.comments
+ end
+
+ def test_assign_attributes_skips_mass_assignment_security_protection_when_without_protection_is_used
+ p = LoosePerson.new
+ p.assign_attributes(attributes_hash, :without_protection => true)
+
+ assert_equal 5, p.id
+ assert_equal 'Josh', p.first_name
+ assert_equal 'm', p.gender
+ assert_equal 'rides a sweet bike', p.comments
+ end
+
+ def test_assign_attributes_with_default_scope_and_attr_protected_attributes
+ p = LoosePerson.new
+ p.assign_attributes(attributes_hash, :as => :default)
+
+ assert_equal nil, p.id
+ assert_equal 'Josh', p.first_name
+ assert_equal 'm', p.gender
+ assert_equal nil, p.comments
+ end
+
+ def test_assign_attributes_with_admin_scope_and_attr_protected_attributes
+ p = LoosePerson.new
+ p.assign_attributes(attributes_hash, :as => :admin)
+
+ assert_equal nil, p.id
+ assert_equal 'Josh', p.first_name
+ assert_equal 'm', p.gender
+ assert_equal 'rides a sweet bike', p.comments
+ end
+
+ def test_assign_attributes_with_default_scope_and_attr_accessible_attributes
+ p = TightPerson.new
+ p.assign_attributes(attributes_hash, :as => :default)
+
+ assert_equal nil, p.id
+ assert_equal 'Josh', p.first_name
+ assert_equal 'm', p.gender
+ assert_equal nil, p.comments
+ end
+
+ def test_assign_attributes_with_admin_scope_and_attr_accessible_attributes
+ p = TightPerson.new
+ p.assign_attributes(attributes_hash, :as => :admin)
+
+ assert_equal nil, p.id
+ assert_equal 'Josh', p.first_name
+ assert_equal 'm', p.gender
+ assert_equal 'rides a sweet bike', p.comments
+ end
+
def test_protection_against_class_attribute_writers
[:logger, :configurations, :primary_key_prefix_type, :table_name_prefix, :table_name_suffix, :pluralize_table_names,
:default_timezone, :schema_format, :lock_optimistically, :record_timestamps].each do |method|
@@ -40,4 +101,14 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase
end
end
+ private
+
+ def attributes_hash
+ {
+ :id => 5,
+ :first_name => 'Josh',
+ :gender => 'm',
+ :comments => 'rides a sweet bike'
+ }
+ end
end \ No newline at end of file
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index 9aa13f04cd..b066575af8 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -12,7 +12,7 @@ require 'models/minimalistic'
require 'models/warehouse_thing'
require 'models/parrot'
require 'models/minivan'
-require 'models/loose_person'
+require 'models/person'
require 'rexml/document'
require 'active_support/core_ext/exception'
@@ -491,6 +491,26 @@ class PersistencesTest < ActiveRecord::TestCase
assert_equal "The First Topic", topic.title
end
+ def test_update_attributes_as_admin
+ person = TightPerson.create({ "first_name" => 'Joshua' })
+ person.update_attributes({ "first_name" => 'Josh', "gender" => 'm', "comments" => 'from NZ' }, :as => :admin)
+ person.reload
+
+ assert_equal 'Josh', person.first_name
+ assert_equal 'm', person.gender
+ assert_equal 'from NZ', person.comments
+ end
+
+ def test_update_attributes_without_protection
+ person = TightPerson.create({ "first_name" => 'Joshua' })
+ person.update_attributes({ "first_name" => 'Josh', "gender" => 'm', "comments" => 'from NZ' }, :without_protection => true)
+ person.reload
+
+ assert_equal 'Josh', person.first_name
+ assert_equal 'm', person.gender
+ assert_equal 'from NZ', person.comments
+ end
+
def test_update_attributes!
Reply.validates_presence_of(:title)
reply = Reply.find(2)
@@ -512,6 +532,26 @@ class PersistencesTest < ActiveRecord::TestCase
Reply.reset_callbacks(:validate)
end
+ def test_update_attributes_with_bang_as_admin
+ person = TightPerson.create({ "first_name" => 'Joshua' })
+ person.update_attributes!({ "first_name" => 'Josh', "gender" => 'm', "comments" => 'from NZ' }, :as => :admin)
+ person.reload
+
+ assert_equal 'Josh', person.first_name
+ assert_equal 'm', person.gender
+ assert_equal 'from NZ', person.comments
+ end
+
+ def test_update_attributestes_with_bang_without_protection
+ person = TightPerson.create({ "first_name" => 'Joshua' })
+ person.update_attributes!({ "first_name" => 'Josh', "gender" => 'm', "comments" => 'from NZ' }, :without_protection => true)
+ person.reload
+
+ assert_equal 'Josh', person.first_name
+ assert_equal 'm', person.gender
+ assert_equal 'from NZ', person.comments
+ end
+
def test_destroyed_returns_boolean
developer = Developer.first
assert_equal false, developer.destroyed?
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index 9b2c7c00df..e8f2f44189 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -203,6 +203,13 @@ class SchemaDumperTest < ActiveRecord::TestCase
assert_match %r{t.xml "data"}, output
end
end
+
+ def test_schema_dump_includes_tsvector_shorthand_definition
+ output = standard_dump
+ if %r{create_table "postgresql_tsvectors"} =~ output
+ assert_match %r{t.tsvector "text_vector"}, output
+ end
+ end
end
def test_schema_dump_keeps_large_precision_integer_columns_as_decimal
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
index b4f3dd034c..0f1b3667cc 100644
--- a/activerecord/test/cases/validations/uniqueness_validation_test.rb
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -162,6 +162,32 @@ class UniquenessValidationTest < ActiveRecord::TestCase
end
end
+ def test_validate_case_sensitive_uniqueness_with_special_sql_like_chars
+ Topic.validates_uniqueness_of(:title, :case_sensitive => true)
+
+ t = Topic.new("title" => "I'm unique!")
+ assert t.save, "Should save t as unique"
+
+ t2 = Topic.new("title" => "I'm %")
+ assert t2.save, "Should save t2 as unique"
+
+ t3 = Topic.new("title" => "I'm uniqu_!")
+ assert t3.save, "Should save t3 as unique"
+ end
+
+ def test_validate_case_insensitive_uniqueness_with_special_sql_like_chars
+ Topic.validates_uniqueness_of(:title, :case_sensitive => false)
+
+ t = Topic.new("title" => "I'm unique!")
+ assert t.save, "Should save t as unique"
+
+ t2 = Topic.new("title" => "I'm %")
+ assert t2.save, "Should save t2 as unique"
+
+ t3 = Topic.new("title" => "I'm uniqu_!")
+ assert t3.save, "Should save t3 as unique"
+ end
+
def test_validate_case_sensitive_uniqueness
Topic.validates_uniqueness_of(:title, :case_sensitive => true, :allow_nil => true)
diff --git a/activerecord/test/models/loose_person.rb b/activerecord/test/models/loose_person.rb
deleted file mode 100644
index 256c281d0d..0000000000
--- a/activerecord/test/models/loose_person.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-class LoosePerson < ActiveRecord::Base
- self.table_name = 'people'
- self.abstract_class = true
-
- attr_protected :credit_rating, :administrator
-end
-
-class LooseDescendant < LoosePerson
- attr_protected :phone_number
-end
-
-class LooseDescendantSecond< LoosePerson
- attr_protected :phone_number
- attr_protected :name
-end
-
-class TightPerson < ActiveRecord::Base
- self.table_name = 'people'
- attr_accessible :name, :address
-end
-
-class TightDescendant < TightPerson
- attr_accessible :phone_number
-end \ No newline at end of file
diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb
index ad59d12672..9c4794902d 100644
--- a/activerecord/test/models/person.rb
+++ b/activerecord/test/models/person.rb
@@ -48,3 +48,22 @@ class PersonWithDependentNullifyJobs < ActiveRecord::Base
has_many :references, :foreign_key => :person_id
has_many :jobs, :source => :job, :through => :references, :dependent => :nullify
end
+
+
+class LoosePerson < ActiveRecord::Base
+ self.table_name = 'people'
+ self.abstract_class = true
+
+ attr_protected :comments
+ attr_protected :as => :admin
+end
+
+class LooseDescendant < LoosePerson; end
+
+class TightPerson < ActiveRecord::Base
+ self.table_name = 'people'
+ attr_accessible :first_name, :gender
+ attr_accessible :first_name, :gender, :comments, :as => :admin
+end
+
+class TightDescendant < TightPerson; end \ No newline at end of file
diff --git a/activerecord/test/schema/postgresql_specific_schema.rb b/activerecord/test/schema/postgresql_specific_schema.rb
index f38f4f3b44..5cf9a207f3 100644
--- a/activerecord/test/schema/postgresql_specific_schema.rb
+++ b/activerecord/test/schema/postgresql_specific_schema.rb
@@ -1,6 +1,6 @@
ActiveRecord::Schema.define do
- %w(postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times postgresql_network_addresses postgresql_bit_strings
+ %w(postgresql_tsvectors postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times postgresql_network_addresses postgresql_bit_strings
postgresql_oids postgresql_xml_data_type defaults geometrics postgresql_timestamp_with_zones).each do |table_name|
execute "DROP TABLE IF EXISTS #{quote_table_name table_name}"
end
@@ -55,6 +55,14 @@ _SQL
nicknames TEXT[]
);
_SQL
+
+ execute <<_SQL
+ CREATE TABLE postgresql_tsvectors (
+ id SERIAL PRIMARY KEY,
+ text_vector tsvector
+ );
+_SQL
+
execute <<_SQL
CREATE TABLE postgresql_moneys (
id SERIAL PRIMARY KEY,
diff --git a/activeresource/test/connection_test.rb b/activeresource/test/connection_test.rb
index 6e79845aa0..7c36393cf2 100644
--- a/activeresource/test/connection_test.rb
+++ b/activeresource/test/connection_test.rb
@@ -50,7 +50,7 @@ class ConnectionTest < Test::Unit::TestCase
# 404 is a missing resource.
assert_response_raises ActiveResource::ResourceNotFound, 404
- # 405 is a missing not allowed error
+ # 405 is a method not allowed error
assert_response_raises ActiveResource::MethodNotAllowed, 405
# 409 is an optimistic locking error
diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec
index 968d6ff4d0..37a74a9e62 100644
--- a/activesupport/activesupport.gemspec
+++ b/activesupport/activesupport.gemspec
@@ -17,5 +17,5 @@ Gem::Specification.new do |s|
s.files = Dir['CHANGELOG', 'README.rdoc', 'lib/**/*']
s.require_path = 'lib'
- s.add_dependency('multi_json', '~> 1.0.0.rc3')
+ s.add_dependency('multi_json', '~> 1.0.0')
end
diff --git a/activesupport/lib/active_support/buffered_logger.rb b/activesupport/lib/active_support/buffered_logger.rb
index e41731f3e7..88b50fc506 100644
--- a/activesupport/lib/active_support/buffered_logger.rb
+++ b/activesupport/lib/active_support/buffered_logger.rb
@@ -41,7 +41,7 @@ module ActiveSupport
def initialize(log, level = DEBUG)
@level = level
- @buffer = {}
+ @buffer = Hash.new { |h,k| h[k] = [] }
@auto_flushing = 1
@guard = Mutex.new
@@ -100,13 +100,8 @@ module ActiveSupport
def flush
@guard.synchronize do
- unless buffer.empty?
- old_buffer = buffer
- all_content = StringIO.new
- old_buffer.each do |content|
- all_content << content
- end
- @log.write(all_content.string)
+ buffer.each do |content|
+ @log.write(content)
end
# Important to do this even if buffer was empty or else @buffer will
@@ -127,7 +122,7 @@ module ActiveSupport
end
def buffer
- @buffer[Thread.current] ||= []
+ @buffer[Thread.current]
end
def clear_buffer
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
index 45263d482f..7ef1497ac2 100644
--- a/activesupport/lib/active_support/cache/mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -4,7 +4,9 @@ rescue LoadError => e
$stderr.puts "You don't have memcache-client installed in your application. Please add it to your Gemfile and run bundle install"
raise e
end
+
require 'digest/md5'
+require 'active_support/core_ext/string/encoding'
module ActiveSupport
module Cache
@@ -157,8 +159,14 @@ module ActiveSupport
end
private
+
+ # Memcache keys are binaries. So we need to force their encoding to binary
+ # before applying the regular expression to ensure we are escaping all
+ # characters properly.
def escape_key(key)
- key = key.to_s.gsub(ESCAPE_KEY_CHARS){|match| "%#{match.getbyte(0).to_s(16).upcase}"}
+ key = key.to_s.dup
+ key = key.force_encoding("BINARY") if key.encoding_aware?
+ key = key.gsub(ESCAPE_KEY_CHARS){ |match| "%#{match.getbyte(0).to_s(16).upcase}" }
key = "#{key[0, 213]}:md5:#{Digest::MD5.hexdigest(key)}" if key.size > 250
key
end
diff --git a/activesupport/lib/active_support/core_ext/array/access.rb b/activesupport/lib/active_support/core_ext/array/access.rb
index c69a015f12..2df4fd1da1 100644
--- a/activesupport/lib/active_support/core_ext/array/access.rb
+++ b/activesupport/lib/active_support/core_ext/array/access.rb
@@ -3,10 +3,10 @@ class Array
#
# %w( a b c d ).from(0) # => %w( a b c d )
# %w( a b c d ).from(2) # => %w( c d )
- # %w( a b c d ).from(10) # => nil
+ # %w( a b c d ).from(10) # => %w()
# %w().from(0) # => %w()
def from(position)
- self[position..-1]
+ self[position, length] || []
end
# Returns the beginning of the array up to +position+.
diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb
index ce0775a690..45b9dda5ca 100644
--- a/activesupport/lib/active_support/deprecation.rb
+++ b/activesupport/lib/active_support/deprecation.rb
@@ -9,7 +9,7 @@ module ActiveSupport
# The version the deprecated behavior will be removed, by default.
attr_accessor :deprecation_horizon
end
- self.deprecation_horizon = '3.1'
+ self.deprecation_horizon = '3.2'
# By default, warnings are not silenced and debugging is off.
self.silenced = false
diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb
index e136e4c5b3..d5d55b7207 100644
--- a/activesupport/lib/active_support/inflector/inflections.rb
+++ b/activesupport/lib/active_support/inflector/inflections.rb
@@ -96,7 +96,7 @@ module ActiveSupport
def clear(scope = :all)
case scope
when :all
- @plurals, @singulars, @uncountables = [], [], []
+ @plurals, @singulars, @uncountables, @humans = [], [], [], []
else
instance_variable_set "@#{scope}", []
end
diff --git a/activesupport/lib/active_support/log_subscriber.rb b/activesupport/lib/active_support/log_subscriber.rb
index 10675edac5..1c4dd24227 100644
--- a/activesupport/lib/active_support/log_subscriber.rb
+++ b/activesupport/lib/active_support/log_subscriber.rb
@@ -81,7 +81,7 @@ module ActiveSupport
# Flush all log_subscribers' logger.
def flush_all!
- flushable_loggers.each(&:flush)
+ flushable_loggers.each { |log| log.flush }
end
end
diff --git a/activesupport/lib/active_support/whiny_nil.rb b/activesupport/lib/active_support/whiny_nil.rb
index bcedbfd57a..577db5018e 100644
--- a/activesupport/lib/active_support/whiny_nil.rb
+++ b/activesupport/lib/active_support/whiny_nil.rb
@@ -41,7 +41,7 @@ class NilClass
end
private
- def method_missing(method, *args, &block)
+ def method_missing(method, *args)
if klass = METHOD_CLASS_MAP[method]
raise_nil_warning_for klass, method, caller
else
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index e5668e29d7..476d55fffd 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -352,6 +352,43 @@ module CacheStoreBehavior
end
end
+# https://rails.lighthouseapp.com/projects/8994/tickets/6225-memcachestore-cant-deal-with-umlauts-and-special-characters
+# The error is caused by charcter encodings that can't be compared with ASCII-8BIT regular expressions and by special
+# characters like the umlaut in UTF-8.
+module EncodedKeyCacheBehavior
+ if defined?(Encoding)
+ Encoding.list.each do |encoding|
+ define_method "test_#{encoding.name.underscore}_encoded_values" do
+ key = "foo".force_encoding(encoding)
+ assert_equal true, @cache.write(key, "1", :raw => true)
+ assert_equal "1", @cache.read(key)
+ assert_equal "1", @cache.fetch(key)
+ assert_equal true, @cache.delete(key)
+ assert_equal "2", @cache.fetch(key, :raw => true) { "2" }
+ assert_equal 3, @cache.increment(key)
+ assert_equal 2, @cache.decrement(key)
+ end
+ end
+
+ def test_common_utf8_values
+ key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
+ assert_equal true, @cache.write(key, "1", :raw => true)
+ assert_equal "1", @cache.read(key)
+ assert_equal "1", @cache.fetch(key)
+ assert_equal true, @cache.delete(key)
+ assert_equal "2", @cache.fetch(key, :raw => true) { "2" }
+ assert_equal 3, @cache.increment(key)
+ assert_equal 2, @cache.decrement(key)
+ end
+
+ def test_retains_encoding
+ key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
+ assert_equal true, @cache.write(key, "1", :raw => true)
+ assert_equal Encoding::UTF_8, key.encoding
+ end
+ end
+end
+
module CacheDeleteMatchedBehavior
def test_delete_matched
@cache.write("foo", "bar")
@@ -617,6 +654,7 @@ uses_memcached 'memcached backed store' do
include CacheStoreBehavior
include LocalCacheBehavior
include CacheIncrementDecrementBehavior
+ include EncodedKeyCacheBehavior
def test_raw_values
cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, :raw => true)
diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb
index d7ab3ce605..0e5407bc35 100644
--- a/activesupport/test/core_ext/array_ext_test.rb
+++ b/activesupport/test/core_ext/array_ext_test.rb
@@ -10,7 +10,7 @@ class ArrayExtAccessTests < Test::Unit::TestCase
def test_from
assert_equal %w( a b c d ), %w( a b c d ).from(0)
assert_equal %w( c d ), %w( a b c d ).from(2)
- assert_nil %w( a b c d ).from(10)
+ assert_equal %w(), %w( a b c d ).from(10)
end
def test_to
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
index 1670d9ee7d..95f18126d4 100644
--- a/activesupport/test/inflector_test.rb
+++ b/activesupport/test/inflector_test.rb
@@ -255,12 +255,21 @@ class InflectorTest < Test::Unit::TestCase
end
def test_clear_all
- cached_values = ActiveSupport::Inflector.inflections.plurals, ActiveSupport::Inflector.inflections.singulars, ActiveSupport::Inflector.inflections.uncountables, ActiveSupport::Inflector.inflections.humans
- ActiveSupport::Inflector.inflections.clear :all
- assert ActiveSupport::Inflector.inflections.plurals.empty?
- assert ActiveSupport::Inflector.inflections.singulars.empty?
- assert ActiveSupport::Inflector.inflections.uncountables.empty?
- assert ActiveSupport::Inflector.inflections.humans.empty?
+ cached_values = ActiveSupport::Inflector.inflections.plurals.dup, ActiveSupport::Inflector.inflections.singulars.dup, ActiveSupport::Inflector.inflections.uncountables.dup, ActiveSupport::Inflector.inflections.humans.dup
+ ActiveSupport::Inflector.inflections do |inflect|
+ # ensure any data is present
+ inflect.plural(/(quiz)$/i, '\1zes')
+ inflect.singular(/(database)s$/i, '\1')
+ inflect.uncountable('series')
+ inflect.human("col_rpted_bugs", "Reported bugs")
+
+ inflect.clear :all
+
+ assert inflect.plurals.empty?
+ assert inflect.singulars.empty?
+ assert inflect.uncountables.empty?
+ assert inflect.humans.empty?
+ end
ActiveSupport::Inflector.inflections.instance_variable_set :@plurals, cached_values[0]
ActiveSupport::Inflector.inflections.instance_variable_set :@singulars, cached_values[1]
ActiveSupport::Inflector.inflections.instance_variable_set :@uncountables, cached_values[2]
@@ -268,12 +277,21 @@ class InflectorTest < Test::Unit::TestCase
end
def test_clear_with_default
- cached_values = ActiveSupport::Inflector.inflections.plurals, ActiveSupport::Inflector.inflections.singulars, ActiveSupport::Inflector.inflections.uncountables, ActiveSupport::Inflector.inflections.humans
- ActiveSupport::Inflector.inflections.clear
- assert ActiveSupport::Inflector.inflections.plurals.empty?
- assert ActiveSupport::Inflector.inflections.singulars.empty?
- assert ActiveSupport::Inflector.inflections.uncountables.empty?
- assert ActiveSupport::Inflector.inflections.humans.empty?
+ cached_values = ActiveSupport::Inflector.inflections.plurals.dup, ActiveSupport::Inflector.inflections.singulars.dup, ActiveSupport::Inflector.inflections.uncountables.dup, ActiveSupport::Inflector.inflections.humans.dup
+ ActiveSupport::Inflector.inflections do |inflect|
+ # ensure any data is present
+ inflect.plural(/(quiz)$/i, '\1zes')
+ inflect.singular(/(database)s$/i, '\1')
+ inflect.uncountable('series')
+ inflect.human("col_rpted_bugs", "Reported bugs")
+
+ inflect.clear
+
+ assert inflect.plurals.empty?
+ assert inflect.singulars.empty?
+ assert inflect.uncountables.empty?
+ assert inflect.humans.empty?
+ end
ActiveSupport::Inflector.inflections.instance_variable_set :@plurals, cached_values[0]
ActiveSupport::Inflector.inflections.instance_variable_set :@singulars, cached_values[1]
ActiveSupport::Inflector.inflections.instance_variable_set :@uncountables, cached_values[2]
diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile
index 53460b8c36..d7069b31fc 100644
--- a/railties/guides/source/configuring.textile
+++ b/railties/guides/source/configuring.textile
@@ -229,6 +229,8 @@ h4. Configuring Active Record
* +config.active_record.lock_optimistically+ controls whether ActiveRecord will use optimistic locking. By default this is +true+.
+* +config.active_record.whitelist_attributes+ will create an empty whitelist of attributes available for mass-assignment security for all models in your app.
+
The MySQL adapter adds one additional configuration option:
* +ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans+ controls whether ActiveRecord will consider all +tinyint(1)+ columns in a MySQL database to be booleans. By default this is +true+.
diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile
index cbc4acfeca..95457578b4 100644
--- a/railties/guides/source/contributing_to_ruby_on_rails.textile
+++ b/railties/guides/source/contributing_to_ruby_on_rails.textile
@@ -2,7 +2,7 @@ h2. Contributing to Ruby on Rails
This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails. After reading it, you should be familiar with:
-* Using Lighthouse to report issues
+* Using GitHub to report issues
* Cloning master and running the test suite
* Helping to resolve existing issues
* Contributing to the Ruby on Rails documentation
@@ -14,29 +14,29 @@ endprologue.
h3. Reporting an Issue
-Ruby on Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) Lighthouse account in order to comment on issues or to upload patches.
+Ruby on Rails uses "GitHub Issue Tracking":https://github.com/rails/rails/issues to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) GitHub account in order to comment on issues or to upload patches.
NOTE: Bugs in the most recent released version of Ruby on Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide you'll find out how to get edge Rails for testing.
h4. Creating a Bug Report
-If you've found a problem in Ruby on Rails which is not a security risk do a search in Lighthouse in case it was already reported. If you find no ticket addressing it you can "add a new one":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new. (See the next section for reporting security issues.)
+If you've found a problem in Ruby on Rails which is not a security risk do a search in GitHub Issues in case it was already reported. If you find no issue addressing it you can "add a new one":https://github.com/rails/rails/issues/new. (See the next section for reporting security issues.)
-At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.
+At the minimum, your issue report needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.
You shouldn't assign the bug to a particular core developer unless you know for sure which developer will be handling that issue. The core team periodically reviews issues and assigns developers and milestones to them.
You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the "Choose some tags" textbox), rather than creating new tags.
-Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment.
+Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this issue report in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the issue report will automatically see any activity or that others will jump to fix it. Creating a issue like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment.
h4. Special Treatment for Security Issues
-WARNING: Please do not report security vulnerabilities on public Lighthouse tickets. The "Rails security policy page":http://rubyonrails.org/security details the procedure to follow for security issues.
+WARNING: Please do not report security vulnerabilities with public GitHub issue reports. The "Rails security policy page":http://rubyonrails.org/security details the procedure to follow for security issues.
h4. What About Feature Requests?
-Please don't put "feature request" tickets into Lighthouse. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wishlist item in Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
+Please don't put "feature request" items into GitHub Issues. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wishlist item in GitHub Issues with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
h3. Running the Test Suite
@@ -216,11 +216,11 @@ TIP: You may want to "put your git branch name in your shell prompt":http://qugs
h3. Helping to Resolve Existing Issues
-As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
+As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "Everyone's Issues":https://github.com/rails/rails/issues?sort=created&direction=desc&state=open&page=1 list in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
h4. Verifying Bug Reports
-For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing.
+For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the issue saying that you're seeing the same thing.
If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem.
@@ -230,26 +230,27 @@ Anything you can do to make bug reports more succinct or easier to reproduce is
h4. Testing Patches
-You can also help out by examining patches that have been submitted to Ruby on Rails via Lighthouse. To apply someone's changes you need to first create a dedicated branch:
+You can also help out by examining pull requests that have been submitted to Ruby on Rails via GitHub. To apply someone's changes you need to first create a dedicated branch:
<shell>
$ git checkout -b testing_branch
</shell>
-Then you can apply their patch:
+Then you can use their remote to update your codebase. For example, let's say the github user JohnSmith has forked and pushed to the master branch located at http://github.com/JohnSmith/rails.
<shell>
-$ git am their-patch-file.diff
+$ git remote add JohnSmith git://github.com/JohnSmith/rails.git
+$ git pull JohnSmith master
</shell>
-After applying a patch, test it out! Here are some things to think about:
+After applying their branch, test it out! Here are some things to think about:
-* Does the patch actually work?
+* Does the change actually work?
* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
* Does it have proper documentation coverage? Should documentation elsewhere be updated?
* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?
-Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:
+Once you're happy that the pull request contains a good change, comment on the GitHub issue indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:
<blockquote>
I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too.
@@ -261,7 +262,7 @@ h3. Contributing to the Rails Documentation
Ruby on Rails has two main sets of documentation: The guides help you to learn Ruby on Rails, and the API is a reference.
-You can create a ticket in Lighthouse to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":https://github.com/lifo/docrails/tree/master. docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation.
+You can create an issue in GitHub issues to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":https://github.com/lifo/docrails/tree/master. docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation.
When working with documentation, please take into account the "API Documentation Guidelines":api_documentation_guidelines.html and the "Ruby on Rails Guides Guidelines":ruby_on_rails_guides_guidelines.html.
@@ -314,10 +315,6 @@ You should not be the only person who looks at the code before you submit it. Yo
You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches.
-h4. Create a Lighthouse Ticket
-
-Now create a ticket for your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, as well as tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense. Write down your ticket number, for you will need it in the following step.
-
h4. Commit Your Changes
When you're happy with the code on your computer, you need to commit the changes to git:
@@ -346,33 +343,29 @@ $ git rebase master
No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.
-h4. Create a Patch
-
-Now you can create a patch file to share with other developers (and with the core team). Still in your branch, run
+h4. Fork
-<shell>
-$ git commit -a
-$ git format-patch master --stdout > my_new_patch.diff
-</shell>
+Navigate to the Rails "GitHub repository":https://github.com/rails/rails and press "Fork" in the upper right hand corner.
-Open the diff file in your text editor of choice to sanity check the results, and make sure that no unintended changes crept in.
-
-You can also perform an extra check by applying the patch to a different dedicated branch:
+Add the new remote to your local repository on your local machine:
<shell>
-$ git checkout -b testing_branch
-$ git apply --check my_new_patch.diff
+$ git remote add mine https://&lt;your user name&gt;@github.com/&lt;your user name&gt;/rails.git
</shell>
-Please make sure the patch does not introduce whitespace errors:
+Push to your remote:
<shell>
-$ git apply --whitespace=error-all my_new_patch.diff
+$ git push mine master
</shell>
-h4. Attach your Patch to the Lighthouse Ticket
+h4. Issue a Pull Request
-Now you need to update the ticket by attaching the patch file you just created.
+Navigate to the Rails repository you just pushed to (e.g. https://github.com/&lt;your user name&gt;/rails) and press "Pull Request" in the upper right hand corner.
+
+Ensure the changesets you introduced are included in the "Commits" tab and that the "Files Changed" incorporate all of your changes.
+
+Fill in some details about your potential patch including a meaningful title. When finished, press "Send pull request." Rails Core will be notified about your submission.
h4. Get Some Feedback
@@ -390,9 +383,9 @@ All contributions, either via master or docrails, get credit in "Rails Contribut
h3. Changelog
+* April 29, 2011: Reflect GitHub Issues and Pull Request workflow by "Dan Pickett":http://www.enlightsolutions.com
* April 14, 2001: Modified Contributing to the Rails Code section to add '[#ticket_number state:commited]' on patches commit messages by "Sebastian Martinez":http://wyeworks.com
* December 28, 2010: Complete revision by "Xavier Noria":credits.html#fxn
* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* August 1, 2009: Updates/amplifications by "Mike Gunderloy":credits.html#mgunderloy
* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy
-
diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile
index f4c1bde5b1..f87ffdb20d 100644
--- a/railties/guides/source/security.textile
+++ b/railties/guides/source/security.textile
@@ -418,10 +418,17 @@ To avoid this, Rails provides two class methods in your Active Record class to c
attr_protected :admin
</ruby>
++attr_protected+ also optionally takes a scope option using :as which allows you to define multiple mass-assignment groupings. If no scope is defined then attributes will be added to the default group.
+
+<ruby>
+attr_protected :last_login, :as => :admin
+</ruby>
+
A much better way, because it follows the whitelist-principle, is the +attr_accessible+ method. It is the exact opposite of +attr_protected+, because _(highlight)it takes a list of attributes that will be accessible_. All other attributes will be protected. This way you won't forget to protect attributes when adding new ones in the course of development. Here is an example:
<ruby>
attr_accessible :name
+attr_accessible :name, :is_admin, :as => :admin
</ruby>
If you want to set a protected attribute, you will to have to assign it individually:
@@ -434,13 +441,31 @@ params[:user] # => {:name => "ow3ned", :admin => true}
@user.admin # => true
</ruby>
-A more paranoid technique to protect your whole project would be to enforce that all models whitelist their accessible attributes. This can be easily achieved with a very simple initializer:
+When assigning attributes in Active Record using +new+, +attributes=+, or +update_attributes+ the :default scope will be used. To assign attributes using different scopes you should use +assign_attributes+ which accepts an optional :as options parameter. If no :as option is provided then the :default scope will be used. You can also bypass mass-assignment security by using the +:without_protection+ option. Here is an example:
+
+<ruby>
+@user = User.new
+
+@user.assign_attributes({ :name => 'Josh', :is_admin => true })
+@user.name # => Josh
+@user.is_admin # => false
+
+@user.assign_attributes({ :name => 'Josh', :is_admin => true }, :as => :admin)
+@user.name # => Josh
+@user.is_admin # => true
+
+@user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true)
+@user.name # => Josh
+@user.is_admin # => true
+</ruby>
+
+A more paranoid technique to protect your whole project would be to enforce that all models define their accessible attributes. This can be easily achieved with a very simple application config option of:
<ruby>
-ActiveRecord::Base.send(:attr_accessible, nil)
+config.active_record.whitelist_attributes = true
</ruby>
-This will create an empty whitelist of attributes available for mass assignment for all models in your app. As such, your models will need to explicitly whitelist accessible parameters by using an +attr_accessible+ declaration. This technique is best applied at the start of a new project. However, for an existing project with a thorough set of functional tests, it should be straightforward and relatively quick to insert this initializer, run your tests, and expose each attribute (via +attr_accessible+) as dictated by your failing tests.
+This will create an empty whitelist of attributes available for mass-assignment for all models in your app. As such, your models will need to explicitly whitelist or blacklist accessible parameters by using an +attr_accessible+ or +attr_protected+ declaration. This technique is best applied at the start of a new project. However, for an existing project with a thorough set of functional tests, it should be straightforward and relatively quick to use this application config option; run your tests, and expose each attribute (via +attr_accessible+ or +attr_protected+) as dictated by your failing tests.
h3. User Management
diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb
index bf865ce466..028c8814c4 100644
--- a/railties/lib/rails/application/finisher.rb
+++ b/railties/lib/rails/application/finisher.rb
@@ -41,6 +41,10 @@ module Rails
ActionDispatch::Reloader.prepare!
end
+ initializer :define_main_app_helper do |app|
+ app.routes.define_mounted_helper(:main_app)
+ end
+
initializer :eager_load! do
if config.cache_classes && !$rails_rake_task
ActiveSupport.run_load_hooks(:before_eager_load, self)
diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb
index 2b7faf9715..dfd3c654ff 100644
--- a/railties/lib/rails/commands/console.rb
+++ b/railties/lib/rails/commands/console.rb
@@ -51,6 +51,6 @@ module Rails
end
# Has to set the RAILS_ENV before config/application is required
-if ARGV.first && !ARGV.first.index("-") && env = ARGV.pop # has to pop the env ARGV so IRB doesn't freak
+if ARGV.first && !ARGV.first.index("-") && env = ARGV.shift # has to shift the env ARGV so IRB doesn't freak
ENV['RAILS_ENV'] = %w(production development test).detect {|e| e =~ /^#{env}/} || env
end
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index 87385814f7..6c1064c609 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -286,6 +286,27 @@ module Rails
#
# This code will use <tt>my_engine.user_path(@user)</tt> to generate the proper route.
#
+ # == Isolated engine's helpers
+ #
+ # Sometimes you may want to isolate engine, but use helpers that are defined for it.
+ # If you want to share just a few specific helpers you can add them to application's
+ # helpers in ApplicationController:
+ #
+ # class ApplicationController < ActionController::Base
+ # helper MyEngine::SharedEngineHelper
+ # end
+ #
+ # If you want to include all of the engine's helpers, you can use #helpers method on egine's
+ # instance:
+ #
+ # class ApplicationController < ActionController::Base
+ # helper MyEngine::Engine.helpers
+ # end
+ #
+ # It will include all of the helpers from engine's directory. Take into account that this does
+ # not include helpers defined in controllers with helper_method or other similar solutions,
+ # only helpers defined in helpers directory will be included.
+ #
# == Migrations & seed data
#
# Engines can have their own migrations. The default path for migrations is exactly the same
@@ -384,6 +405,24 @@ module Rails
@railties ||= self.class::Railties.new(config)
end
+ def helpers
+ @helpers ||= begin
+ helpers = Module.new
+
+ helpers_paths = if config.respond_to?(:helpers_paths)
+ config.helpers_paths
+ else
+ paths["app/helpers"].existent
+ end
+
+ all = ActionController::Base.all_helpers_from_path(helpers_paths)
+ ActionController::Base.modules_for_helpers(all).each do |mod|
+ helpers.send(:include, mod)
+ end
+ helpers
+ end
+ end
+
def app
@app ||= begin
config.middleware = config.middleware.merge_into(default_middleware_stack)
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index 481fa95068..520d2c6a3a 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -10,6 +10,8 @@ module Rails
module Generators
class AppBase < Base
DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
+ JDBC_DATABASES = %w( jdbcmysql jdbcsqlite3 jdbcpostgresql )
+ DATABASES.concat(JDBC_DATABASES)
JAVASCRIPTS = %w( jquery prototype )
attr_accessor :rails_template
@@ -133,14 +135,14 @@ module Rails
gem 'rails', :path => '#{Rails::Generators::RAILS_DEV_PATH}'
gem 'arel', :git => 'git://github.com/rails/arel.git'
gem 'rack', :git => 'git://github.com/rack/rack.git'
- gem 'sprockets', :git => "git://github.com/sstephenson/sprockets.git"
+ gem 'sprockets', :git => 'git://github.com/sstephenson/sprockets.git'
GEMFILE
elsif options.edge?
<<-GEMFILE.strip_heredoc
gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'arel', :git => 'git://github.com/rails/arel.git'
gem 'rack', :git => 'git://github.com/rack/rack.git'
- gem 'sprockets', :git => "git://github.com/sstephenson/sprockets.git"
+ gem 'sprockets', :git => 'git://github.com/sstephenson/sprockets.git'
GEMFILE
else
<<-GEMFILE.strip_heredoc
@@ -150,18 +152,21 @@ module Rails
# gem 'rails', :git => 'git://github.com/rails/rails.git'
# gem 'arel', :git => 'git://github.com/rails/arel.git'
# gem 'rack', :git => 'git://github.com/rack/rack.git'
- # gem 'sprockets', :git => "git://github.com/sstephenson/sprockets.git"
+ # gem 'sprockets', :git => 'git://github.com/sstephenson/sprockets.git'
GEMFILE
end
end
def gem_for_database
- # %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
+ # %w( mysql oracle postgresql sqlite3 frontbase ibm_db jdbcmysql jdbcsqlite3 jdbcpostgresql )
case options[:database]
when "oracle" then "ruby-oci8"
when "postgresql" then "pg"
when "frontbase" then "ruby-frontbase"
when "mysql" then "mysql2"
+ when "jdbcmysql" then "activerecord-jdbcmysql-adapter"
+ when "jdbcsqlite3" then "activerecord-jdbcsqlite3-adapter"
+ when "jdbcpostgresql" then "activerecord-jdbcpostgresql-adapter"
else options[:database]
end
end
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 141d9fd15c..8ad64e38ed 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -6,7 +6,7 @@ source 'http://rubygems.org'
# Asset template engines
<%= "gem 'json'\n" if RUBY_VERSION < "1.9.2" -%>
-gem 'sass', '~> 3.1.0.alpha'
+gem 'sass'
gem 'coffee-script'
gem 'uglifier'
diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb
index ff8e6e5f3e..46ccb7e078 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -39,6 +39,10 @@ module <%= app_const_base %>
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
+ # Please note that JavaScript expansions are *ignored altogether* if the asset
+ # pipeline is enabled (see config.assets.enabled below). Put your defaults in
+ # app/assets/javascripts/application.js in that case.
+ #
# JavaScript files you want as :defaults (application.js is always included).
<% if options[:skip_javascript] -%>
config.action_view.javascript_expansions[:defaults] = %w()
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml
new file mode 100644
index 0000000000..ca807c9f3f
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml
@@ -0,0 +1,30 @@
+# MySQL. Versions 4.1 and 5.0 are recommended.
+#
+# Install the MySQL driver:
+# gem install activerecord-jdbcmysql-adapter
+#
+# And be sure to use new-style password hashing:
+# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
+development:
+ adapter: jdbcmysql
+ database: <%= app_name %>_development
+ username: root
+ password:
+ host: localhost
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: jdbcmysql
+ database: <%= app_name %>_test
+ username: root
+ password:
+ host: localhost
+
+production:
+ adapter: jdbcmysql
+ database: <%= app_name %>_production
+ username: root
+ password:
+ host: localhost
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml
new file mode 100644
index 0000000000..a228aca5d2
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml
@@ -0,0 +1,48 @@
+# PostgreSQL. Versions 7.4 and 8.x are supported.
+#
+# Install the pg driver:
+# gem install pg
+# On Mac OS X with macports:
+# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
+# On Windows:
+# gem install pg
+# Choose the win32 build.
+# Install PostgreSQL and put its /bin directory on your path.
+development:
+ adapter: jdbcpostgresql
+ encoding: unicode
+ database: <%= app_name %>_development
+ username: <%= app_name %>
+ password:
+
+ # Connect on a TCP socket. Omitted by default since the client uses a
+ # domain socket that doesn't need configuration. Windows does not have
+ # domain sockets, so uncomment these lines.
+ #host: localhost
+ #port: 5432
+
+ # Schema search path. The server defaults to $user,public
+ #schema_search_path: myapp,sharedapp,public
+
+ # Minimum log levels, in increasing order:
+ # debug5, debug4, debug3, debug2, debug1,
+ # log, notice, warning, error, fatal, and panic
+ # The server defaults to notice.
+ #min_messages: warning
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: jdbcpostgresql
+ encoding: unicode
+ database: <%= app_name %>_test
+ username: <%= app_name %>
+ password:
+
+production:
+ adapter: jdbcpostgresql
+ encoding: unicode
+ database: <%= app_name %>_production
+ username: <%= app_name %>
+ password:
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml
new file mode 100644
index 0000000000..30776b3b4e
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml
@@ -0,0 +1,17 @@
+# SQLite version 3.x
+# gem 'activerecord-jdbcsqlite3-adapter'
+
+development:
+ adapter: jdbcsqlite3
+ database: db/development.sqlite3
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: jdbcsqlite3
+ database: db/test.sqlite3
+
+production:
+ adapter: jdbcsqlite3
+ database: db/production.sqlite3
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
index b00f10c545..9553f3bdde 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
@@ -11,14 +11,14 @@
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
- # Specifies the header that your server uses for sending files
- # (comment out if your front-end server doesn't support this)
- config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx
-
# Compress both stylesheets and JavaScripts
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :scss
+ # Specifies the header that your server uses for sending files
+ # (comment out if your front-end server doesn't support this)
+ config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx
+
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
diff --git a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
index 12921f47b6..126aadb88d 100644
--- a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
@@ -13,11 +13,13 @@ module Rails
directory "app"
template "#{app_templates_dir}/app/views/layouts/application.html.erb.tt",
"app/views/layouts/#{name}/application.html.erb"
+ empty_directory_with_gitkeep "app/assets/images"
elsif full?
empty_directory_with_gitkeep "app/models"
empty_directory_with_gitkeep "app/controllers"
empty_directory_with_gitkeep "app/views"
empty_directory_with_gitkeep "app/helpers"
+ empty_directory_with_gitkeep "app/assets/images"
end
end
@@ -199,6 +201,10 @@ task :default => :test
build(:javascripts)
end
+ def create_images_directory
+ build(:images)
+ end
+
def create_script_files
build(:script)
end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb b/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb
index dd4d2da4eb..824caecb24 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/integration/navigation_test.rb
@@ -5,9 +5,8 @@ class NavigationTest < ActionDispatch::IntegrationTest
fixtures :all
<% end -%>
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
+ # test "the truth" do
+ # assert true
+ # end
end
diff --git a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
index 11a73ebad7..0bc5fd8ca2 100644
--- a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
@@ -3,10 +3,9 @@ require 'test_helper'
<% module_namespacing do -%>
class <%= class_name %>ControllerTest < ActionController::TestCase
<% if actions.empty? -%>
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
+ # test "the truth" do
+ # assert true
+ # end
<% else -%>
<% for action in actions -%>
test "should get <%= action %>" do
diff --git a/railties/lib/rails/generators/test_unit/integration/templates/integration_test.rb b/railties/lib/rails/generators/test_unit/integration/templates/integration_test.rb
index de0823749c..e7a06e4a73 100644
--- a/railties/lib/rails/generators/test_unit/integration/templates/integration_test.rb
+++ b/railties/lib/rails/generators/test_unit/integration/templates/integration_test.rb
@@ -3,8 +3,7 @@ require 'test_helper'
class <%= class_name %>Test < ActionDispatch::IntegrationTest
fixtures :all
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
+ # test "the truth" do
+ # assert true
+ # end
end
diff --git a/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb
index b62c7fd279..c05102290c 100644
--- a/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/mailer/templates/functional_test.rb
@@ -13,10 +13,9 @@ class <%= class_name %>Test < ActionMailer::TestCase
<% end -%>
<% if actions.blank? -%>
- # replace this with your real tests
- test "the truth" do
- assert true
- end
+ # test "the truth" do
+ # assert true
+ # end
<% end -%>
end
<% end -%>
diff --git a/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb b/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb
index 6f79879838..c9bc7d5b90 100644
--- a/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb
+++ b/railties/lib/rails/generators/test_unit/model/templates/unit_test.rb
@@ -2,9 +2,8 @@ require 'test_helper'
<% module_namespacing do -%>
class <%= class_name %>Test < ActiveSupport::TestCase
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
+ # test "the truth" do
+ # assert true
+ # end
end
<% end -%>
diff --git a/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb b/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb
index cd116f5ce9..28aa23626a 100644
--- a/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb
+++ b/railties/lib/rails/generators/test_unit/observer/templates/unit_test.rb
@@ -2,9 +2,8 @@ require 'test_helper'
<% module_namespacing do -%>
class <%= class_name %>ObserverTest < ActiveSupport::TestCase
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
+ # test "the truth" do
+ # assert true
+ # end
end
<% end -%>
diff --git a/railties/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt b/railties/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt
index 3e0bc29d3a..0cbae1120e 100644
--- a/railties/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt
+++ b/railties/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt
@@ -1,8 +1,7 @@
require 'test_helper'
class <%= class_name %>Test < ActiveSupport::TestCase
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
+ # test "the truth" do
+ # assert true
+ # end
end
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index 62697b1bf9..ab3eb4c9e7 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -258,6 +258,18 @@ module ApplicationTests
assert_equal res, last_response.body # value should be unchanged
end
+ test "sets all Active Record models to whitelist all attributes by default" do
+ add_to_config <<-RUBY
+ config.active_record.whitelist_attributes = true
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ assert_equal ActiveModel::MassAssignmentSecurity::WhiteList,
+ ActiveRecord::Base.active_authorizers[:default].class
+ assert_equal [""], ActiveRecord::Base.active_authorizers[:default].to_a
+ end
+
test "registers interceptors with ActionMailer" do
add_to_config <<-RUBY
config.action_mailer.interceptors = MyMailInterceptor
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 58febfd9c7..1902484301 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -131,6 +131,24 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "Gemfile", /^gem\s+["']mysql2["']$/
end
+ def test_config_jdbcmysql_database
+ run_generator([destination_root, "-d", "jdbcmysql"])
+ assert_file "config/database.yml", /jdbcmysql/
+ assert_file "Gemfile", /^gem\s+["']activerecord-jdbcmysql-adapter["']$/
+ end
+
+ def test_config_jdbcsqlite3_database
+ run_generator([destination_root, "-d", "jdbcsqlite3"])
+ assert_file "config/database.yml", /jdbcsqlite3/
+ assert_file "Gemfile", /^gem\s+["']activerecord-jdbcsqlite3-adapter["']$/
+ end
+
+ def test_config_jdbcpostgresql_database
+ run_generator([destination_root, "-d", "jdbcpostgresql"])
+ assert_file "config/database.yml", /jdbcpostgresql/
+ assert_file "Gemfile", /^gem\s+["']activerecord-jdbcpostgresql-adapter["']$/
+ end
+
def test_generator_if_skip_active_record_is_given
run_generator [destination_root, "--skip-active-record"]
assert_no_file "config/database.yml"
diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb
index d20335ad95..fb956a8335 100644
--- a/railties/test/generators/plugin_new_generator_test.rb
+++ b/railties/test/generators/plugin_new_generator_test.rb
@@ -140,13 +140,14 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
run_generator [destination_root, "--full", "--skip_active_record"]
FileUtils.cd destination_root
`bundle install`
- assert_match(/2 tests, 2 assertions, 0 failures, 0 errors/, `bundle exec rake test`)
+ assert_match(/1 tests, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test`)
end
def test_creating_engine_in_full_mode
run_generator [destination_root, "--full"]
assert_file "app/assets/javascripts"
assert_file "app/assets/stylesheets"
+ assert_file "app/assets/images"
assert_file "app/models"
assert_file "app/controllers"
assert_file "app/views"
@@ -162,6 +163,9 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
def test_create_mountable_application_with_mountable_option
run_generator [destination_root, "--mountable"]
+ assert_file "app/assets/javascripts"
+ assert_file "app/assets/stylesheets"
+ assert_file "app/assets/images"
assert_file "config/routes.rb", /Bukkits::Engine.routes.draw do/
assert_file "lib/bukkits/engine.rb", /isolate_namespace Bukkits/
assert_file "test/dummy/config/routes.rb", /mount Bukkits::Engine => "\/bukkits"/
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 7605984684..0c588ba773 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -584,6 +584,51 @@ module RailtiesTest
assert_equal Bukkits::Engine.instance, Rails::Engine.find(engine_path)
end
+ test "gather isolated engine's helpers in Engine#helpers" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ app_file "app/helpers/some_helper.rb", <<-RUBY
+ module SomeHelper
+ def foo
+ 'foo'
+ end
+ end
+ RUBY
+
+ @plugin.write "app/helpers/bukkits/engine_helper.rb", <<-RUBY
+ module Bukkits
+ module EngineHelper
+ def bar
+ 'bar'
+ end
+ end
+ end
+ RUBY
+
+ @plugin.write "app/helpers/engine_helper.rb", <<-RUBY
+ module EngineHelper
+ def baz
+ 'baz'
+ end
+ end
+ RUBY
+
+ add_to_config("config.action_dispatch.show_exceptions = false")
+
+ boot_rails
+ require "#{rails_root}/config/environment"
+
+ methods = Bukkits::Engine.helpers.public_instance_methods.collect(&:to_s).sort
+ expected = ["bar", "baz"]
+ assert_equal expected, methods
+ end
+
private
def app
Rails.application