aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Gemfile6
-rw-r--r--actionmailer/CHANGELOG.md10
-rw-r--r--actionpack/CHANGELOG.md56
-rw-r--r--actionpack/lib/action_controller/metal/force_ssl.rb22
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb22
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb2
-rw-r--r--actionpack/lib/action_dispatch/routing/polymorphic_routes.rb8
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb10
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb7
-rw-r--r--actionpack/lib/action_view/helpers/url_helper.rb51
-rw-r--r--actionpack/lib/action_view/test_case.rb3
-rw-r--r--actionpack/test/abstract_unit.rb1
-rw-r--r--actionpack/test/activerecord/polymorphic_routes_test.rb28
-rw-r--r--actionpack/test/controller/force_ssl_test.rb31
-rw-r--r--actionpack/test/controller/integration_test.rb19
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb4
-rw-r--r--actionpack/test/dispatch/request/query_string_parsing_test.rb7
-rw-r--r--actionpack/test/template/test_case_test.rb19
-rw-r--r--actionpack/test/template/url_helper_test.rb27
-rw-r--r--activemodel/CHANGELOG.md15
-rw-r--r--activerecord/CHANGELOG.md29
-rw-r--r--activerecord/lib/active_record/associations/association_scope.rb19
-rw-r--r--activerecord/lib/active_record/attribute_methods/serialization.rb7
-rw-r--r--activerecord/lib/active_record/coders/yaml_column.rb8
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb1
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb8
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb14
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb14
-rw-r--r--activerecord/lib/active_record/core.rb2
-rw-r--r--activerecord/lib/active_record/explain.rb8
-rw-r--r--activerecord/lib/active_record/fixtures/file.rb44
-rw-r--r--activerecord/lib/active_record/locking/optimistic.rb2
-rw-r--r--activerecord/lib/active_record/null_relation.rb17
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb2
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb2
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb2
-rw-r--r--activerecord/lib/active_record/store.rb34
-rw-r--r--activerecord/test/cases/adapters/mysql2/connection_test.rb27
-rw-r--r--activerecord/test/cases/adapters/postgresql/connection_test.rb44
-rw-r--r--activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb36
-rw-r--r--activerecord/test/cases/base_test.rb9
-rw-r--r--activerecord/test/cases/helper.rb16
-rw-r--r--activerecord/test/cases/relation/where_test.rb19
-rw-r--r--activerecord/test/cases/relations_test.rb7
-rw-r--r--activerecord/test/cases/store_test.rb29
-rw-r--r--activerecord/test/fixtures/admin/users.yml3
-rw-r--r--activesupport/CHANGELOG.md14
-rw-r--r--activesupport/lib/active_support/callbacks.rb19
-rw-r--r--activesupport/lib/active_support/json/encoding.rb1
-rw-r--r--activesupport/lib/active_support/json/variable.rb9
-rw-r--r--activesupport/lib/active_support/testing/performance/ruby.rb5
-rw-r--r--activesupport/test/core_ext/file_test.rb6
-rw-r--r--activesupport/test/core_ext/kernel_test.rb5
-rw-r--r--activesupport/test/json/encoding_test.rb2
-rw-r--r--guides/source/active_record_querying.textile48
-rw-r--r--railties/lib/rails/code_statistics.rb11
-rw-r--r--railties/lib/rails/commands.rb10
-rw-r--r--railties/lib/rails/commands/console.rb48
-rw-r--r--railties/lib/rails/commands/dbconsole.rb137
-rw-r--r--railties/lib/rails/commands/server.rb5
-rw-r--r--railties/lib/rails/generators/app_base.rb2
-rw-r--r--railties/lib/rails/generators/rails/controller/templates/controller.rb2
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb2
-rw-r--r--railties/lib/rails/railtie.rb3
-rw-r--r--railties/lib/rails/tasks/documentation.rake2
-rw-r--r--railties/lib/rails/tasks/routes.rake2
-rw-r--r--railties/lib/rails/tasks/statistics.rake1
-rw-r--r--railties/test/commands/console_test.rb89
-rw-r--r--railties/test/commands/dbconsole_test.rb22
-rw-r--r--railties/test/commands/server_test.rb4
-rw-r--r--railties/test/generators/app_generator_test.rb2
71 files changed, 890 insertions, 312 deletions
diff --git a/Gemfile b/Gemfile
index ac835936ca..c727f73020 100644
--- a/Gemfile
+++ b/Gemfile
@@ -8,10 +8,11 @@ else
gem 'arel'
end
+gem 'minitest', '~> 3.0.0'
+gem 'mocha', '>= 0.11.2'
gem 'rack-test', github: "brynary/rack-test"
gem 'bcrypt-ruby', '~> 3.0.0'
gem 'jquery-rails'
-gem 'minitest', '~> 3.0.0'
if ENV['JOURNEY']
gem 'journey', path: ENV['JOURNEY']
@@ -29,9 +30,6 @@ end
# it being automatically loaded by sprockets
gem 'uglifier', '>= 1.0.3', require: false
-gem 'rake', '>= 0.8.7'
-gem 'mocha', '>= 0.11.2'
-
group :doc do
# The current sdoc cannot generate GitHub links due
# to a bug, but the PR that fixes it has been there
diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md
index a33d6e072b..e6021939ff 100644
--- a/actionmailer/CHANGELOG.md
+++ b/actionmailer/CHANGELOG.md
@@ -1,3 +1,13 @@
+## Rails 3.2.5 (Jun 1, 2012) ##
+
+* No changes.
+
+
+## Rails 3.2.4 (May 31, 2012) ##
+
+* No changes.
+
+
## Rails 3.2.3 (March 30, 2012) ##
* Upgrade mail version to 2.4.3 *ML*
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 2e7b3190fc..815a46a3ca 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,5 +1,29 @@
## Rails 4.0.0 (unreleased) ##
+* Allow to use mounted_helpers (helpers for accessing mounted engines) in ActionView::TestCase. *Piotr Sarnacki*
+
+* Include mounted_helpers (helpers for accessing mounted engines) in ActionDispatch::IntegrationTest by default. *Piotr Sarnacki*
+
+* Extracted redirect logic from `ActionController::ForceSSL::ClassMethods.force_ssl` into `ActionController::ForceSSL#force_ssl_redirect`
+
+ *Jeremy Friesen*
+
+* Make possible to use a block in button_to helper if button text is hard
+ to fit into the name parameter, e.g.:
+
+ <%= button_to [:make_happy, @user] do %>
+ Make happy <strong><%= @user.name %></strong>
+ <% end %>
+ # => "<form method="post" action="/users/1/make_happy" class="button_to">
+ # <div>
+ # <button type="submit">
+ # Make happy <strong>Name</strong>
+ # </button>
+ # </div>
+ # </form>"
+
+ *Sergey Nartimov*
+
* change a way of ordering helpers from several directories. Previously,
when loading helpers from multiple paths, all of the helpers files were
gathered into one array an then they were sorted. Helpers from different
@@ -217,6 +241,38 @@
HTML5 `mark` element. *Brian Cardarella*
+## Rails 3.2.5 (Jun 1, 2012) ##
+
+* No changes.
+
+
+## Rails 3.2.4 (May 31, 2012) ##
+
+* Deprecate old APIs for highlight, excerpt and word_wrap *Jeremy Walker*
+
+* Deprecate `:disable_with` in favor of `'data-disable-with'` option for `button_to`, `button_tag` and `submit_tag` helpers.
+
+ *Carlos Galdino + Rafael Mendonça França*
+
+* Deprecate `:mouseover` option for `image_tag` helper. *Rafael Mendonça França*
+
+* Deprecate `button_to_function` and `link_to_function` helpers. *Rafael Mendonça França*
+
+* Don't break Haml with textarea newline fix. GH #393, #4000, #5190, #5191
+
+* Fix options handling on labels. GH #2492, #5614
+
+* Added config.action_view.embed_authenticity_token_in_remote_forms to deal
+ with regression from 16ee611fa
+
+* Set rendered_format when doing render :inline. GH #5632
+
+* Fix the redirect when it receive blocks with arity of 1. Closes #5677
+
+* Strip [nil] from parameters hash. Thanks to Ben Murphy for
+ reporting this! CVE-2012-2660
+
+
## Rails 3.2.3 (March 30, 2012) ##
* Add `config.action_view.embed_authenticity_token_in_remote_forms` (defaults to true) which allows to set if authenticity token will be included by default in remote forms. If you change it to false, you can still force authenticity token by passing `:authenticity_token => true` in form options *Piotr Sarnacki*
diff --git a/actionpack/lib/action_controller/metal/force_ssl.rb b/actionpack/lib/action_controller/metal/force_ssl.rb
index ac12cbb625..77d799a38a 100644
--- a/actionpack/lib/action_controller/metal/force_ssl.rb
+++ b/actionpack/lib/action_controller/metal/force_ssl.rb
@@ -40,15 +40,23 @@ module ActionController
def force_ssl(options = {})
host = options.delete(:host)
before_filter(options) do
- unless request.ssl?
- redirect_options = {:protocol => 'https://', :status => :moved_permanently}
- redirect_options.merge!(:host => host) if host
- redirect_options.merge!(:params => request.query_parameters)
- flash.keep if respond_to?(:flash)
- redirect_to redirect_options
- end
+ force_ssl_redirect(host)
end
end
end
+
+ # Redirect the existing request to use the HTTPS protocol.
+ #
+ # ==== Parameters
+ # * <tt>host</tt> - Redirect to a different host name
+ def force_ssl_redirect(host = nil)
+ unless request.ssl?
+ redirect_options = {:protocol => 'https://', :status => :moved_permanently}
+ redirect_options.merge!(:host => host) if host
+ redirect_options.merge!(:params => request.query_parameters)
+ flash.keep if respond_to?(:flash)
+ redirect_to redirect_options
+ end
+ end
end
end
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index aa5ba3e8a5..6757a53bd1 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -263,6 +263,28 @@ module ActionDispatch
LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip
end
+ protected
+
+ # Remove nils from the params hash
+ def deep_munge(hash)
+ hash.each_value do |v|
+ case v
+ when Array
+ v.grep(Hash) { |x| deep_munge(x) }
+ when Hash
+ deep_munge(v)
+ end
+ end
+
+ keys = hash.keys.find_all { |k| hash[k] == [nil] }
+ keys.each { |k| hash[k] = nil }
+ hash
+ end
+
+ def parse_query(qs)
+ deep_munge(super)
+ end
+
private
def check_method(name)
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index e43e897783..25d099d83e 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1327,7 +1327,7 @@ module ActionDispatch
msg += @draw_paths.map { |_path| " * #{_path}" }.join("\n")
raise ArgumentError, msg
end
-
+
route_path = "#{path}/#{name}.rb"
instance_eval(File.read(route_path), route_path.to_s)
end
diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
index 8fde667108..86ce7a83b9 100644
--- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
+++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
@@ -95,7 +95,7 @@ module ActionDispatch
end
record = extract_record(record_or_hash_or_array)
- record = record.to_model if record.respond_to?(:to_model)
+ record = convert_to_model(record)
args = Array === record_or_hash_or_array ?
record_or_hash_or_array.dup :
@@ -122,6 +122,8 @@ module ActionDispatch
args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options
end
+ args.collect! { |a| convert_to_model(a) }
+
(proxy || self).send(named_route, *args)
end
@@ -152,6 +154,10 @@ module ActionDispatch
options[:action] ? "#{options[:action]}_" : ''
end
+ def convert_to_model(object)
+ object.respond_to?(:to_model) ? object.to_model : object
+ end
+
def routing_type(options)
options[:routing_type] || :url
end
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 7872f4007e..64b1d58ae9 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -252,15 +252,11 @@ module ActionDispatch
self.draw_paths = []
self.request_class = request_class
- @valid_conditions = {}
-
+ @valid_conditions = { :controller => true, :action => true }
request_class.public_instance_methods.each { |m|
- @valid_conditions[m.to_sym] = true
+ @valid_conditions[m] = true
}
- @valid_conditions[:controller] = true
- @valid_conditions[:action] = true
-
- self.valid_conditions.delete(:id)
+ @valid_conditions.delete(:id)
@append = []
@prepend = []
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 3fdc6688c2..50ca28395b 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -193,8 +193,11 @@ module ActionDispatch
# If the app is a Rails app, make url_helpers available on the session
# This makes app.url_for and app.foo_path available in the console
- if app.respond_to?(:routes) && app.routes.respond_to?(:url_helpers)
- singleton_class.class_eval { include app.routes.url_helpers }
+ if app.respond_to?(:routes)
+ singleton_class.class_eval do
+ include app.routes.url_helpers if app.routes.respond_to?(:url_helpers)
+ include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers)
+ end
end
reset!
diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb
index 7e69547dab..7f5b3c8a0f 100644
--- a/actionpack/lib/action_view/helpers/url_helper.rb
+++ b/actionpack/lib/action_view/helpers/url_helper.rb
@@ -233,25 +233,15 @@ module ActionView
#
# link_to("Destroy", "http://www.example.com", :method => :delete, :confirm => "Are you sure?")
# # => <a href='http://www.example.com' rel="nofollow" data-method="delete" data-confirm="Are you sure?">Destroy</a>
- def link_to(*args, &block)
- if block_given?
- options = args.first || {}
- html_options = args.second
- link_to(capture(&block), options, html_options)
- else
- name = args[0]
- options = args[1] || {}
- html_options = args[2]
-
- html_options = convert_options_to_data_attributes(options, html_options)
- url = url_for(options)
+ def link_to(name = nil, options = nil, html_options = nil, &block)
+ html_options, options = options, name if block_given?
+ options ||= {}
+ url = url_for(options)
- href = html_options['href']
- tag_options = tag_options(html_options)
+ html_options = convert_options_to_data_attributes(options, html_options)
+ html_options['href'] ||= url
- href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
- "<a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a>".html_safe
- end
+ content_tag(:a, name || url, html_options, &block)
end
# Generates a form containing a single button that submits to the URL created
@@ -294,6 +284,16 @@ module ActionView
# # <div><input value="New" type="submit" /></div>
# # </form>"
#
+ # <%= button_to [:make_happy, @user] do %>
+ # Make happy <strong><%= @user.name %></strong>
+ # <% end %>
+ # # => "<form method="post" action="/users/1/make_happy" class="button_to">
+ # # <div>
+ # # <button type="submit">
+ # # Make happy <strong><%= @user.name %></strong>
+ # # </button>
+ # # </div>
+ # # </form>"
#
# <%= button_to "New", :action => "new", :form_class => "new-thing" %>
# # => "<form method="post" action="/controller/new" class="new-thing">
@@ -331,7 +331,11 @@ module ActionView
# # </div>
# # </form>"
# #
- def button_to(name, options = {}, html_options = {})
+ def button_to(name = nil, options = nil, html_options = nil, &block)
+ html_options, options = options, name if block_given?
+ options ||= {}
+ html_options ||= {}
+
html_options = html_options.stringify_keys
convert_boolean_attributes!(html_options, %w(disabled))
@@ -350,9 +354,16 @@ module ActionView
request_token_tag = form_method == 'post' ? token_tag : ''
html_options = convert_options_to_data_attributes(options, html_options)
- html_options.merge!("type" => "submit", "value" => name || url)
+ html_options['type'] = 'submit'
+
+ button = if block_given?
+ content_tag('button', html_options, &block)
+ else
+ html_options['value'] = name || url
+ tag('input', html_options)
+ end
- inner_tags = method_tag.safe_concat tag('input', html_options).safe_concat request_token_tag
+ inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag)
content_tag('form', content_tag('div', inner_tags), form_options)
end
diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb
index fece499c94..53bde48e4d 100644
--- a/actionpack/lib/action_view/test_case.rb
+++ b/actionpack/lib/action_view/test_case.rb
@@ -229,7 +229,8 @@ module ActionView
def method_missing(selector, *args)
if @controller.respond_to?(:_routes) &&
- @controller._routes.named_routes.helpers.include?(selector)
+ ( @controller._routes.named_routes.helpers.include?(selector) ||
+ @controller._routes.mounted_helpers.method_defined?(selector) )
@controller.__send__(selector, *args)
else
super
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index ba06bcae51..37deb9c98a 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -277,6 +277,7 @@ module ActionController
include ActionController::Testing
# This stub emulates the Railtie including the URL helpers from a Rails application
include SharedTestRoutes.url_helpers
+ include SharedTestRoutes.mounted_helpers
self.view_paths = FIXTURE_LOAD_PATH
diff --git a/actionpack/test/activerecord/polymorphic_routes_test.rb b/actionpack/test/activerecord/polymorphic_routes_test.rb
index 90e7f4ae59..afb714484b 100644
--- a/actionpack/test/activerecord/polymorphic_routes_test.rb
+++ b/actionpack/test/activerecord/polymorphic_routes_test.rb
@@ -25,6 +25,24 @@ class Series < ActiveRecord::Base
self.table_name = 'projects'
end
+class ModelDelegator < ActiveRecord::Base
+ self.table_name = 'projects'
+
+ def to_model
+ ModelDelegate.new
+ end
+end
+
+class ModelDelegate
+ def self.model_name
+ ActiveModel::Name.new(self)
+ end
+
+ def to_param
+ 'overridden'
+ end
+end
+
module Blog
class Post < ActiveRecord::Base
self.table_name = 'projects'
@@ -50,6 +68,7 @@ class PolymorphicRoutesTest < ActionController::TestCase
@bid = Bid.new
@tax = Tax.new
@fax = Fax.new
+ @delegator = ModelDelegator.new
@series = Series.new
@blog_post = Blog::Post.new
@blog_blog = Blog::Blog.new
@@ -439,6 +458,13 @@ class PolymorphicRoutesTest < ActionController::TestCase
end
end
+ def test_routing_a_to_model_delegate
+ with_test_routes do
+ @delegator.save
+ assert_equal "http://example.com/model_delegates/overridden", polymorphic_url(@delegator)
+ end
+ end
+
def with_namespaced_routes(name)
with_routing do |set|
set.draw do
@@ -469,6 +495,7 @@ class PolymorphicRoutesTest < ActionController::TestCase
resource :bid
end
resources :series
+ resources :model_delegates
end
self.class.send(:include, @routes.url_helpers)
@@ -516,5 +543,4 @@ class PolymorphicRoutesTest < ActionController::TestCase
yield
end
end
-
end
diff --git a/actionpack/test/controller/force_ssl_test.rb b/actionpack/test/controller/force_ssl_test.rb
index 5b423c8151..6758668b7a 100644
--- a/actionpack/test/controller/force_ssl_test.rb
+++ b/actionpack/test/controller/force_ssl_test.rb
@@ -49,6 +49,15 @@ class ForceSSLFlash < ForceSSLController
end
end
+class RedirectToSSL < ForceSSLController
+ def banana
+ force_ssl_redirect || render(:text => 'monkey')
+ end
+ def cheeseburger
+ force_ssl_redirect('secure.cheeseburger.host') || render(:text => 'ihaz')
+ end
+end
+
class ForceSSLControllerLevelTest < ActionController::TestCase
tests ForceSSLControllerLevel
@@ -149,3 +158,25 @@ class ForceSSLFlashTest < ActionController::TestCase
assert_equal "hello", assigns["flashy"]
end
end
+
+class RedirectToSSLTest < ActionController::TestCase
+ tests RedirectToSSL
+ def test_banana_redirects_to_https_if_not_https
+ get :banana
+ assert_response 301
+ assert_equal "https://test.host/redirect_to_ssl/banana", redirect_to_url
+ end
+
+ def test_cheeseburgers_redirects_to_https_with_new_host_if_not_https
+ get :cheeseburger
+ assert_response 301
+ assert_equal "https://secure.cheeseburger.host/redirect_to_ssl/cheeseburger", redirect_to_url
+ end
+
+ def test_banana_does_not_redirect_if_already_https
+ request.env['HTTPS'] = 'on'
+ get :cheeseburger
+ assert_response 200
+ assert_equal 'ihaz', response.body
+ end
+end \ No newline at end of file
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index fb41dcb33a..f18bf33969 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -538,11 +538,26 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
@routes ||= ActionDispatch::Routing::RouteSet.new
end
+ class MountedApp
+ def self.routes
+ @routes ||= ActionDispatch::Routing::RouteSet.new
+ end
+
+ routes.draw do
+ get 'baz', :to => 'application_integration_test/test#index', :as => :baz
+ end
+
+ def self.call(*)
+ end
+ end
+
routes.draw do
get '', :to => 'application_integration_test/test#index', :as => :empty_string
get 'foo', :to => 'application_integration_test/test#index', :as => :foo
get 'bar', :to => 'application_integration_test/test#index', :as => :bar
+
+ mount MountedApp => '/mounted', :as => "mounted"
end
def app
@@ -555,6 +570,10 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
assert_equal '/bar', bar_path
end
+ test "includes mounted helpers" do
+ assert_equal '/mounted/baz', mounted.baz_path
+ end
+
test "route helpers after controller access" do
get '/'
assert_equal '/', empty_string_path
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index 066cd523be..0289f4070b 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -9,7 +9,7 @@ module RequestForgeryProtectionActions
end
def show_button
- render :inline => "<%= button_to('New', '/') {} %>"
+ render :inline => "<%= button_to('New', '/') %>"
end
def external_form
@@ -79,7 +79,7 @@ class FreeCookieController < RequestForgeryProtectionController
end
def show_button
- render :inline => "<%= button_to('New', '/') {} %>"
+ render :inline => "<%= button_to('New', '/') %>"
end
end
diff --git a/actionpack/test/dispatch/request/query_string_parsing_test.rb b/actionpack/test/dispatch/request/query_string_parsing_test.rb
index c3f009ab15..6ea66f9d32 100644
--- a/actionpack/test/dispatch/request/query_string_parsing_test.rb
+++ b/actionpack/test/dispatch/request/query_string_parsing_test.rb
@@ -81,7 +81,12 @@ class QueryStringParsingTest < ActionDispatch::IntegrationTest
end
test "query string without equal" do
- assert_parses({ "action" => nil }, "action")
+ assert_parses({"action" => nil}, "action")
+ assert_parses({"action" => {"foo" => nil}}, "action[foo]")
+ assert_parses({"action" => {"foo" => { "bar" => nil }}}, "action[foo][bar]")
+ assert_parses({"action" => {"foo" => { "bar" => nil }}}, "action[foo][bar][]")
+ assert_parses({"action" => {"foo" => nil}}, "action[foo][]")
+ assert_parses({"action"=>{"foo"=>[{"bar"=>nil}]}}, "action[foo][][bar]")
end
test "query string with empty key" do
diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb
index f2ed2ec609..c005f040eb 100644
--- a/actionpack/test/template/test_case_test.rb
+++ b/actionpack/test/template/test_case_test.rb
@@ -222,6 +222,25 @@ module ActionView
end
end
+ test "is able to use mounted routes" do
+ with_routing do |set|
+ app = Class.new do
+ def self.routes
+ @routes ||= ActionDispatch::Routing::RouteSet.new
+ end
+
+ routes.draw { get "bar", :to => lambda {} }
+
+ def self.call(*)
+ end
+ end
+
+ set.draw { mount app => "/foo", :as => "foo_app" }
+
+ assert_equal '/foo/bar', foo_app.bar_path
+ end
+ end
+
test "named routes can be used from helper included in view" do
with_routing do |set|
set.draw { resources :contents }
diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb
index fb5b35bac6..62608a727f 100644
--- a/actionpack/test/template/url_helper_test.rb
+++ b/actionpack/test/template/url_helper_test.rb
@@ -144,6 +144,13 @@ class UrlHelperTest < ActiveSupport::TestCase
)
end
+ def test_button_to_with_block
+ assert_dom_equal(
+ "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\"><div><button type=\"submit\"><span>Hello</span></button></div></form>",
+ button_to("http://www.example.com") { content_tag(:span, 'Hello') }
+ )
+ end
+
def test_link_tag_with_straight_url
assert_dom_equal "<a href=\"http://www.example.com\">Hello</a>", link_to("Hello", "http://www.example.com")
end
@@ -270,6 +277,16 @@ class UrlHelperTest < ActiveSupport::TestCase
)
end
+ def test_link_tag_with_block
+ assert_dom_equal '<a href="/"><span>Example site</span></a>',
+ link_to('/') { content_tag(:span, 'Example site') }
+ end
+
+ def test_link_tag_with_block_and_html_options
+ assert_dom_equal '<a class="special" href="/"><span>Example site</span></a>',
+ link_to('/', :class => "special") { content_tag(:span, 'Example site') }
+ end
+
def test_link_tag_using_block_in_erb
out = render_erb %{<%= link_to('/') do %>Example site<% end %>}
assert_equal '<a href="/">Example site</a>', out
@@ -282,6 +299,16 @@ class UrlHelperTest < ActiveSupport::TestCase
)
end
+ def test_link_tag_escapes_content
+ assert_dom_equal '<a href="/">Malicious &lt;script&gt;content&lt;/script&gt;</a>',
+ link_to("Malicious <script>content</script>", "/")
+ end
+
+ def test_link_tag_does_not_escape_html_safe_content
+ assert_dom_equal '<a href="/">Malicious <script>content</script></a>',
+ link_to("Malicious <script>content</script>".html_safe, "/")
+ end
+
def test_link_to_unless
assert_equal "Showing", link_to_unless(true, "Showing", url_hash)
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index eb34edb91b..4ddafddbe0 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -11,6 +11,21 @@
* Trim down Active Model API by removing `valid?` and `errors.full_messages` *José Valim*
+## Rails 3.2.5 (Jun 1, 2012) ##
+
+* No changes.
+
+
+## Rails 3.2.4 (May 31, 2012) ##
+
+* No changes.
+
+
+## Rails 3.2.3 (March 30, 2012) ##
+
+* No changes.
+
+
## Rails 3.2.2 (March 1, 2012) ##
* No changes.
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 4f4e087acd..b04c54ce7f 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -3,7 +3,7 @@
* Allow blocks for `count` with `ActiveRecord::Relation`, to work similar as
`Array#count`:
- Person.where("age > 26").count { |person| gender == 'female' }
+ Person.where("age > 26").count { |person| person.gender == 'female' }
*Chris Finne & Carlos Antonio da Silva*
@@ -344,6 +344,33 @@
* PostgreSQL hstore types are automatically deserialized from the database.
+## Rails 3.2.5 (Jun 1, 2012) ##
+
+* Restore behavior of Active Record 3.2.3 scopes.
+ A series of commits relating to preloading and scopes caused a regression.
+
+ *Andrew White*
+
+
+## Rails 3.2.4 (May 31, 2012) ##
+
+* Perf fix: Don't load the records when doing assoc.delete_all.
+ GH #6289. *Jon Leighton*
+
+* Association preloading shouldn't be affected by the current scoping.
+ This could cause infinite recursion and potentially other problems.
+ See GH #5667. *Jon Leighton*
+
+* Datetime attributes are forced to be changed. GH #3965
+
+* Fix attribute casting. GH #5549
+
+* Fix #5667. Preloading should ignore scoping.
+
+* Predicate builder should not recurse for determining where columns.
+ Thanks to Ben Murphy for reporting this! CVE-2012-2661
+
+
## Rails 3.2.3 (March 30, 2012) ##
* Added find_or_create_by_{attribute}! dynamic method. *Andrew White*
diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb
index 5a44d3a156..89a626693d 100644
--- a/activerecord/lib/active_record/associations/association_scope.rb
+++ b/activerecord/lib/active_record/associations/association_scope.rb
@@ -96,7 +96,7 @@ module ActiveRecord
conditions.each do |condition|
if options[:through] && condition.is_a?(Hash)
- condition = { table.name => condition }
+ condition = disambiguate_condition(table, condition)
end
scope = scope.where(interpolate(condition))
@@ -113,7 +113,7 @@ module ActiveRecord
conditions.each do |condition|
condition = interpolate(condition)
- condition = { (table.table_alias || table.name) => condition } unless i == 0
+ condition = disambiguate_condition(table, condition) unless i == 0
scope = scope.where(condition)
end
@@ -138,6 +138,21 @@ module ActiveRecord
end
end
+ def disambiguate_condition(table, condition)
+ if condition.is_a?(Hash)
+ Hash[
+ condition.map do |k, v|
+ if v.is_a?(Hash)
+ [k, v]
+ else
+ [table.table_alias || table.name, { k => v }]
+ end
+ end
+ ]
+ else
+ condition
+ end
+ end
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb
index 165785c8fb..706fbf0546 100644
--- a/activerecord/lib/active_record/attribute_methods/serialization.rb
+++ b/activerecord/lib/active_record/attribute_methods/serialization.rb
@@ -72,12 +72,13 @@ module ActiveRecord
self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
end
- def initialize_attributes(attributes) #:nodoc:
- super
+ def initialize_attributes(attributes, options = {}) #:nodoc:
+ serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized
+ super(attributes, options)
serialized_attributes.each do |key, coder|
if attributes.key?(key)
- attributes[key] = Attribute.new(coder, attributes[key], :serialized)
+ attributes[key] = Attribute.new(coder, attributes[key], serialized)
end
end
diff --git a/activerecord/lib/active_record/coders/yaml_column.rb b/activerecord/lib/active_record/coders/yaml_column.rb
index 66a0c83c41..f17e7158de 100644
--- a/activerecord/lib/active_record/coders/yaml_column.rb
+++ b/activerecord/lib/active_record/coders/yaml_column.rb
@@ -1,12 +1,10 @@
+require 'yaml'
+
module ActiveRecord
# :stopdoc:
module Coders
class YAMLColumn
- RESCUE_ERRORS = [ ArgumentError ]
-
- if defined?(Psych) && defined?(Psych::SyntaxError)
- RESCUE_ERRORS << Psych::SyntaxError
- end
+ RESCUE_ERRORS = [ ArgumentError, Psych::SyntaxError ]
attr_accessor :object_class
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 7b2961a04a..4c6d03a1d2 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -4,6 +4,7 @@ module ActiveRecord
# Converts an arel AST to SQL
def to_sql(arel, binds = [])
if arel.respond_to?(:ast)
+ binds = binds.dup
visitor.accept(arel.ast) do
quote(*binds.shift.reverse)
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
index 9794c5663e..692473abc5 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -313,10 +313,10 @@ module ActiveRecord
sql = "SHOW TABLES"
end
- select_all(sql).map { |table|
+ select_all(sql, 'SCHEMA').map { |table|
table.delete('Table_type')
sql = "SHOW CREATE TABLE #{quote_table_name(table.to_a.first.last)}"
- exec_without_stmt(sql).first['Create Table'] + ";\n\n"
+ exec_without_stmt(sql, 'SCHEMA').first['Create Table'] + ";\n\n"
}.join
end
@@ -508,7 +508,7 @@ module ActiveRecord
# SHOW VARIABLES LIKE 'name'
def show_variable(name)
- variables = select_all("SHOW VARIABLES LIKE '#{name}'")
+ variables = select_all("SHOW VARIABLES LIKE '#{name}'", 'SCHEMA')
variables.first['Value'] unless variables.empty?
end
@@ -630,7 +630,7 @@ module ActiveRecord
raise ActiveRecordError, "No such column: #{table_name}.#{column_name}"
end
- current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'")["Type"]
+ current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'", 'SCHEMA')["Type"]
rename_column_sql = "CHANGE #{quote_column_name(column_name)} #{quote_column_name(new_column_name)} #{current_type}"
add_column_options!(rename_column_sql, options)
rename_column_sql
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index 7dcea375e1..03c318f5f7 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -457,7 +457,8 @@ module ActiveRecord
# Is this connection alive and ready for queries?
def active?
- @connection.status == PGconn::CONNECTION_OK
+ @connection.query 'SELECT 1'
+ true
rescue PGError
false
end
@@ -523,7 +524,7 @@ module ActiveRecord
# Returns the configured supported identifier length supported by PostgreSQL
def table_alias_length
- @table_alias_length ||= query('SHOW max_identifier_length')[0][0].to_i
+ @table_alias_length ||= query('SHOW max_identifier_length', 'SCHEMA')[0][0].to_i
end
# QUOTING ==================================================
@@ -985,7 +986,7 @@ module ActiveRecord
# Returns an array of indexes for the given table.
def indexes(table_name, name = nil)
- result = query(<<-SQL, name)
+ result = query(<<-SQL, 'SCHEMA')
SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid
FROM pg_class t
INNER JOIN pg_index d ON t.oid = d.indrelid
@@ -997,7 +998,6 @@ module ActiveRecord
ORDER BY i.relname
SQL
-
result.map do |row|
index_name = row[0]
unique = row[1] == 't'
@@ -1036,7 +1036,7 @@ module ActiveRecord
# Returns the current database name.
def current_database
- query('select current_database()')[0][0]
+ query('select current_database()', 'SCHEMA')[0][0]
end
# Returns the current schema name.
@@ -1046,7 +1046,7 @@ module ActiveRecord
# Returns the current database encoding format.
def encoding
- query(<<-end_sql)[0][0]
+ query(<<-end_sql, 'SCHEMA')[0][0]
SELECT pg_encoding_to_char(pg_database.encoding) FROM pg_database
WHERE pg_database.datname LIKE '#{current_database}'
end_sql
@@ -1054,7 +1054,7 @@ module ActiveRecord
# Returns an array of schema names.
def schema_names
- query(<<-SQL).flatten
+ query(<<-SQL, 'SCHEMA').flatten
SELECT nspname
FROM pg_namespace
WHERE nspname !~ '^pg_.*'
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index d4ffa82b17..a0c7e559ce 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -208,7 +208,6 @@ module ActiveRecord
true
end
-
# QUOTING ==================================================
def quote(value, column = nil)
@@ -220,7 +219,6 @@ module ActiveRecord
end
end
-
def quote_string(s) #:nodoc:
@connection.class.quote(s)
end
@@ -359,7 +357,7 @@ module ActiveRecord
# SCHEMA STATEMENTS ========================================
- def tables(name = 'SCHEMA', table_name = nil) #:nodoc:
+ def tables(name = nil, table_name = nil) #:nodoc:
sql = <<-SQL
SELECT name
FROM sqlite_master
@@ -367,13 +365,13 @@ module ActiveRecord
SQL
sql << " AND name = #{quote_table_name(table_name)}" if table_name
- exec_query(sql, name).map do |row|
+ exec_query(sql, 'SCHEMA').map do |row|
row['name']
end
end
- def table_exists?(name)
- name && tables('SCHEMA', name).any?
+ def table_exists?(table_name)
+ table_name && tables(nil, table_name).any?
end
# Returns an array of +SQLite3Column+ objects for the table specified by +table_name+.
@@ -394,12 +392,12 @@ module ActiveRecord
# Returns an array of indexes for the given table.
def indexes(table_name, name = nil) #:nodoc:
- exec_query("PRAGMA index_list(#{quote_table_name(table_name)})", name).map do |row|
+ exec_query("PRAGMA index_list(#{quote_table_name(table_name)})", 'SCHEMA').map do |row|
IndexDefinition.new(
table_name,
row['name'],
row['unique'] != 0,
- exec_query("PRAGMA index_info('#{row['name']}')").map { |col|
+ exec_query("PRAGMA index_info('#{row['name']}')", "Columns for index #{row['name']} on #{table_name}").map { |col|
col['name']
})
end
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index 80c6f20b1a..1fa6c701bb 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -241,7 +241,7 @@ module ActiveRecord
##
def initialize_dup(other) # :nodoc:
cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
- self.class.initialize_attributes(cloned_attributes)
+ self.class.initialize_attributes(cloned_attributes, :serialized => false)
cloned_attributes.delete(self.class.primary_key)
diff --git a/activerecord/lib/active_record/explain.rb b/activerecord/lib/active_record/explain.rb
index 313fdb3487..b0eda8ef34 100644
--- a/activerecord/lib/active_record/explain.rb
+++ b/activerecord/lib/active_record/explain.rb
@@ -52,7 +52,7 @@ module ActiveRecord
# Makes the adapter execute EXPLAIN for the tuples of queries and bindings.
# Returns a formatted string ready to be logged.
def exec_explain(queries) # :nodoc:
- queries && queries.map do |sql, bind|
+ str = queries && queries.map do |sql, bind|
[].tap do |msg|
msg << "EXPLAIN for: #{sql}"
unless bind.empty?
@@ -62,6 +62,12 @@ module ActiveRecord
msg << connection.explain(sql, bind)
end.join("\n")
end.join("\n")
+
+ # Overriding inspect to be more human readable, specially in the console.
+ def str.inspect
+ self
+ end
+ str
end
# Silences automatic EXPLAIN logging for the duration of the block.
diff --git a/activerecord/lib/active_record/fixtures/file.rb b/activerecord/lib/active_record/fixtures/file.rb
index 6547791144..a9cabf5a7b 100644
--- a/activerecord/lib/active_record/fixtures/file.rb
+++ b/activerecord/lib/active_record/fixtures/file.rb
@@ -24,37 +24,33 @@ module ActiveRecord
rows.each(&block)
end
- RESCUE_ERRORS = [ ArgumentError ] # :nodoc:
+ RESCUE_ERRORS = [ ArgumentError, Psych::SyntaxError ] # :nodoc:
private
- if defined?(Psych) && defined?(Psych::SyntaxError)
- RESCUE_ERRORS << Psych::SyntaxError
- end
-
- def rows
- return @rows if @rows
+ def rows
+ return @rows if @rows
+
+ begin
+ data = YAML.load(render(IO.read(@file)))
+ rescue *RESCUE_ERRORS => error
+ raise Fixture::FormatError, "a YAML error occurred parsing #{@file}. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Please have a look at http://www.yaml.org/faq.html\nThe exact error was:\n #{error.class}: #{error}", error.backtrace
+ end
+ @rows = data ? validate(data).to_a : []
+ end
- begin
- data = YAML.load(render(IO.read(@file)))
- rescue *RESCUE_ERRORS => error
- raise Fixture::FormatError, "a YAML error occurred parsing #{@file}. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Please have a look at http://www.yaml.org/faq.html\nThe exact error was:\n #{error.class}: #{error}", error.backtrace
+ def render(content)
+ ERB.new(content).result
end
- @rows = data ? validate(data).to_a : []
- end
- def render(content)
- ERB.new(content).result
- end
+ # Validate our unmarshalled data.
+ def validate(data)
+ unless Hash === data || YAML::Omap === data
+ raise Fixture::FormatError, 'fixture is not a hash'
+ end
- # Validate our unmarshalled data.
- def validate(data)
- unless Hash === data || YAML::Omap === data
- raise Fixture::FormatError, 'fixture is not a hash'
+ raise Fixture::FormatError unless data.all? { |name, row| Hash === row }
+ data
end
-
- raise Fixture::FormatError unless data.all? { |name, row| Hash === row }
- data
- end
end
end
end
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index a3412582fa..05e052b953 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -168,7 +168,7 @@ module ActiveRecord
# start the lock version at zero. Note we can't use
# <tt>locking_enabled?</tt> at this point as
# <tt>@attributes</tt> may not have been initialized yet.
- def initialize_attributes(attributes) #:nodoc:
+ def initialize_attributes(attributes, options = {}) #:nodoc:
if attributes.key?(locking_column) && lock_optimistically
attributes[locking_column] ||= 0
end
diff --git a/activerecord/lib/active_record/null_relation.rb b/activerecord/lib/active_record/null_relation.rb
index c2d3eeb8ce..aca8291d75 100644
--- a/activerecord/lib/active_record/null_relation.rb
+++ b/activerecord/lib/active_record/null_relation.rb
@@ -2,24 +2,24 @@
module ActiveRecord
# = Active Record Null Relation
- class NullRelation < Relation
+ module NullRelation
def exec_queries
@records = []
end
- def pluck(column_name)
+ def pluck(_column_name)
[]
end
- def delete_all(conditions = nil)
+ def delete_all(_conditions = nil)
0
end
- def update_all(updates, conditions = nil, options = {})
+ def update_all(_updates, _conditions = nil, _options = {})
0
end
- def delete(id_or_array)
+ def delete(_id_or_array)
0
end
@@ -51,13 +51,12 @@ module ActiveRecord
0
end
- def calculate(operation, column_name, options = {})
+ def calculate(_operation, _column_name, _options = {})
nil
end
- def exists?(id = false)
+ def exists?(_id = false)
false
end
-
end
-end \ No newline at end of file
+end
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index ad49c80e4f..54c93332bb 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -17,7 +17,7 @@ module ActiveRecord
# Person.count(:age, distinct: true)
# # => counts the number of different age values
#
- # Person.where("age > 26").count { |person| gender == 'female' }
+ # Person.where("age > 26").count { |person| person.gender == 'female' }
# # => queries people where "age > 26" then count the loaded results filtering by gender
def count(column_name = nil, options = {})
if block_given?
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
index 6a0cdd5917..cb8f903474 100644
--- a/activerecord/lib/active_record/relation/predicate_builder.rb
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -6,7 +6,7 @@ module ActiveRecord
if value.is_a?(Hash)
table = Arel::Table.new(column, engine)
- build_from_hash(engine, value, table)
+ value.map { |k,v| build(table[k.to_sym], v) }
else
column = column.to_s
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index 19fe8155d9..a89d0f3ebf 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -279,7 +279,7 @@ module ActiveRecord
# end
#
def none
- NullRelation.new(@klass, @table)
+ scoped.extending(NullRelation)
end
def readonly(value = true)
diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb
index fdd82b489a..d70e02e379 100644
--- a/activerecord/lib/active_record/store.rb
+++ b/activerecord/lib/active_record/store.rb
@@ -38,7 +38,7 @@ module ActiveRecord
module ClassMethods
def store(store_attribute, options = {})
- serialize store_attribute, options.fetch(:coder, ActiveSupport::HashWithIndifferentAccess)
+ serialize store_attribute, IndifferentCoder.new(options[:coder])
store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
end
@@ -47,7 +47,7 @@ module ActiveRecord
define_method("#{key}=") do |value|
initialize_store_attribute(store_attribute)
send(store_attribute)[key] = value
- send("#{store_attribute}_will_change!")
+ send :"#{store_attribute}_will_change!"
end
define_method(key) do
@@ -71,5 +71,35 @@ module ActiveRecord
send :"#{store_attribute}=", ActiveSupport::HashWithIndifferentAccess.new
end
end
+
+ class IndifferentCoder
+ def initialize(coder_or_class_name)
+ @coder =
+ if coder_or_class_name.respond_to?(:load) && coder_or_class_name.respond_to?(:dump)
+ coder_or_class_name
+ else
+ ActiveRecord::Coders::YAMLColumn.new(coder_or_class_name || Object)
+ end
+ end
+
+ def dump(obj)
+ @coder.dump self.class.as_indifferent_hash(obj)
+ end
+
+ def load(yaml)
+ self.class.as_indifferent_hash @coder.load(yaml)
+ end
+
+ def self.as_indifferent_hash(obj)
+ case obj
+ when ActiveSupport::HashWithIndifferentAccess
+ obj
+ when Hash
+ obj.with_indifferent_access
+ else
+ HashWithIndifferentAccess.new
+ end
+ end
+ end
end
end
diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb
index 684c7f5929..276c499276 100644
--- a/activerecord/test/cases/adapters/mysql2/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb
@@ -4,6 +4,13 @@ class MysqlConnectionTest < ActiveRecord::TestCase
def setup
super
@connection = ActiveRecord::Model.connection
+ @connection.extend(LogIntercepter)
+ @connection.intercepted = true
+ end
+
+ def teardown
+ @connection.intercepted = false
+ @connection.logged = []
end
def test_no_automatic_reconnection_after_timeout
@@ -45,6 +52,26 @@ class MysqlConnectionTest < ActiveRecord::TestCase
end
end
+ def test_logs_name_structure_dump
+ @connection.structure_dump
+ assert_equal "SCHEMA", @connection.logged[0][1]
+ assert_equal "SCHEMA", @connection.logged[2][1]
+ end
+
+ def test_logs_name_show_variable
+ @connection.show_variable 'foo'
+ assert_equal "SCHEMA", @connection.logged[0][1]
+ end
+
+ def test_logs_name_rename_column_sql
+ @connection.execute "CREATE TABLE `bar_baz` (`foo` varchar(255))"
+ @connection.logged = []
+ @connection.send(:rename_column_sql, 'bar_baz', 'foo', 'foo2')
+ assert_equal "SCHEMA", @connection.logged[0][1]
+ ensure
+ @connection.execute "DROP TABLE `bar_baz`"
+ end
+
private
def run_without_connection
diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb
index 4baec749ff..adb2cef010 100644
--- a/activerecord/test/cases/adapters/postgresql/connection_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb
@@ -8,6 +8,13 @@ module ActiveRecord
def setup
super
@connection = ActiveRecord::Base.connection
+ @connection.extend(LogIntercepter)
+ @connection.intercepted = true
+ end
+
+ def teardown
+ @connection.intercepted = false
+ @connection.logged = []
end
def test_encoding
@@ -25,5 +32,42 @@ module ActiveRecord
expect = NonExistentTable.connection.query('show geqo').first.first
assert_equal 'off', expect
end
+
+ def test_tables_logs_name
+ @connection.tables('hello')
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_indexes_logs_name
+ @connection.indexes('items', 'hello')
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_table_exists_logs_name
+ @connection.table_exists?('items')
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_table_alias_length_logs_name
+ @connection.instance_variable_set("@table_alias_length", nil)
+ @connection.table_alias_length
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_current_database_logs_name
+ @connection.current_database
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_encoding_logs_name
+ @connection.encoding
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
+ def test_schema_names_logs_name
+ @connection.schema_names
+ assert_equal 'SCHEMA', @connection.logged[0][1]
+ end
+
end
end
diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
index 8a7f44d0a3..5e947799cc 100644
--- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
@@ -20,6 +20,14 @@ module ActiveRecord
number integer
)
eosql
+
+ @conn.extend(LogIntercepter)
+ @conn.intercepted = true
+ end
+
+ def teardown
+ @conn.intercepted = false
+ @conn.logged = []
end
def test_column_types
@@ -232,13 +240,23 @@ module ActiveRecord
end
def test_tables_logs_name
- name = "hello"
- assert_logged [[name, []]] do
- @conn.tables(name)
+ assert_logged [['SCHEMA', []]] do
+ @conn.tables('hello')
assert_not_nil @conn.logged.first.shift
end
end
+ def test_indexes_logs_name
+ assert_logged [["PRAGMA index_list(\"items\")", 'SCHEMA', []]] do
+ @conn.indexes('items', 'hello')
+ end
+ end
+
+ def test_table_exists_logs_name
+ assert @conn.table_exists?('items')
+ assert_equal 'SCHEMA', @conn.logged[0][1]
+ end
+
def test_columns
columns = @conn.columns('items').sort_by { |x| x.name }
assert_equal 2, columns.length
@@ -274,7 +292,6 @@ module ActiveRecord
end
def test_indexes_logs
- intercept_logs_on @conn
assert_difference('@conn.logged.length') do
@conn.indexes('items')
end
@@ -326,21 +343,10 @@ module ActiveRecord
private
def assert_logged logs
- intercept_logs_on @conn
yield
assert_equal logs, @conn.logged
end
- def intercept_logs_on ctx
- @conn.extend(Module.new {
- attr_accessor :logged
- def log sql, name, binds = []
- @logged << [sql, name, binds]
- yield
- end
- })
- @conn.logged = []
- end
end
end
end
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index 619fb881fa..f95230ff50 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -1309,6 +1309,15 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal({ :foo => :bar }, t.content_before_type_cast)
end
+ def test_serialized_attribute_calling_dup_method
+ klass = Class.new(ActiveRecord::Base)
+ klass.table_name = "topics"
+ klass.serialize :content, JSON
+
+ t = klass.new(:content => { :foo => :bar }).dup
+ assert_equal({ :foo => :bar }, t.content_before_type_cast)
+ end
+
def test_serialized_attribute_declared_in_subclass
hash = { 'important1' => 'value1', 'important2' => 'value2' }
important_topic = ImportantTopic.create("important" => hash)
diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb
index 37fa13f771..afff020561 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -121,3 +121,19 @@ class << Time
@now = nil
end
end
+
+module LogIntercepter
+ attr_accessor :logged, :intercepted
+ def self.extended(base)
+ base.logged = []
+ end
+ def log(sql, name, binds = [], &block)
+ if @intercepted
+ @logged << [sql, name, binds]
+ yield
+ else
+ super(sql, name,binds, &block)
+ end
+ end
+end
+
diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb
new file mode 100644
index 0000000000..90c690e266
--- /dev/null
+++ b/activerecord/test/cases/relation/where_test.rb
@@ -0,0 +1,19 @@
+require "cases/helper"
+require 'models/post'
+
+module ActiveRecord
+ class WhereTest < ActiveRecord::TestCase
+ fixtures :posts
+
+ def test_where_error
+ assert_raises(ActiveRecord::StatementInvalid) do
+ Post.where(:id => { 'posts.author_id' => 10 }).first
+ end
+ end
+
+ def test_where_with_table_name
+ post = Post.first
+ assert_equal post, Post.where(:posts => { 'id' => post.id }).first
+ end
+ end
+end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 2dc8f0053b..90367df5ee 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -226,7 +226,6 @@ class RelationTest < ActiveRecord::TestCase
assert_no_queries do
assert_equal [], Developer.none
assert_equal [], Developer.scoped.none
- assert Developer.none.is_a?(ActiveRecord::NullRelation)
end
end
@@ -236,6 +235,12 @@ class RelationTest < ActiveRecord::TestCase
end
end
+ def test_none_chainable_to_existing_scope_extension_method
+ assert_no_queries do
+ assert_equal 1, Topic.anonymous_extension.none.one
+ end
+ end
+
def test_none_chained_to_methods_firing_queries_straight_to_db
assert_no_queries do
assert_equal [], Developer.none.pluck(:id) # => uses select_all
diff --git a/activerecord/test/cases/store_test.rb b/activerecord/test/cases/store_test.rb
index 3a5d84df9f..79476ed2a4 100644
--- a/activerecord/test/cases/store_test.rb
+++ b/activerecord/test/cases/store_test.rb
@@ -3,8 +3,10 @@ require 'models/admin'
require 'models/admin/user'
class StoreTest < ActiveRecord::TestCase
+ fixtures :'admin/users'
+
setup do
- @john = Admin::User.create(:name => 'John Doe', :color => 'black', :remember_login => true, :height => 'tall', :is_a_good_guy => true)
+ @john = Admin::User.create!(:name => 'John Doe', :color => 'black', :remember_login => true, :height => 'tall', :is_a_good_guy => true)
end
test "reading store attributes through accessors" do
@@ -52,18 +54,19 @@ class StoreTest < ActiveRecord::TestCase
end
test "convert store attributes from Hash to HashWithIndifferentAccess saving the data and access attributes indifferently" do
- @john.json_data = { :height => 'tall', 'weight' => 'heavy' }
- assert_equal true, @john.json_data.instance_of?(Hash)
- assert_equal 'tall', @john.json_data[:height]
- assert_equal nil, @john.json_data['height']
- assert_equal nil, @john.json_data[:weight]
- assert_equal 'heavy', @john.json_data['weight']
- @john.height = 'low'
- assert_equal true, @john.json_data.instance_of?(HashWithIndifferentAccess)
- assert_equal 'low', @john.json_data[:height]
- assert_equal 'low', @john.json_data['height']
- assert_equal 'heavy', @john.json_data[:weight]
- assert_equal 'heavy', @john.json_data['weight']
+ user = Admin::User.find_by_name('Jamis')
+ assert_equal 'symbol', user.settings[:symbol]
+ assert_equal 'symbol', user.settings['symbol']
+ assert_equal 'string', user.settings[:string]
+ assert_equal 'string', user.settings['string']
+ assert_equal true, user.settings.instance_of?(ActiveSupport::HashWithIndifferentAccess)
+
+ user.height = 'low'
+ assert_equal 'symbol', user.settings[:symbol]
+ assert_equal 'symbol', user.settings['symbol']
+ assert_equal 'string', user.settings[:string]
+ assert_equal 'string', user.settings['string']
+ assert_equal true, user.settings.instance_of?(ActiveSupport::HashWithIndifferentAccess)
end
test "convert store attributes from any format other than Hash or HashWithIndifferent access losing the data" do
diff --git a/activerecord/test/fixtures/admin/users.yml b/activerecord/test/fixtures/admin/users.yml
index 6f11f2509e..e2884beda5 100644
--- a/activerecord/test/fixtures/admin/users.yml
+++ b/activerecord/test/fixtures/admin/users.yml
@@ -5,3 +5,6 @@ david:
jamis:
name: Jamis
account: signals37
+ settings:
+ :symbol: symbol
+ string: string
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index a818ef0c5d..af9e8c27c7 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,7 +1,7 @@
## Rails 4.0.0 (unreleased) ##
-* ActionView::Helpers::NumberHelper methods have been moved to ActiveSupport::NumberHelper and are now available via
- Numeric#to_s. Numeric#to_s now accepts the formatting options :phone, :currency, :percentage, :delimited,
+* ActionView::Helpers::NumberHelper methods have been moved to ActiveSupport::NumberHelper and are now available via
+ Numeric#to_s. Numeric#to_s now accepts the formatting options :phone, :currency, :percentage, :delimited,
:rounded, :human, and :human_size. *Andrew Mutz*
* Add `Hash#transform_keys`, `Hash#transform_keys!`, `Hash#deep_transform_keys`, and `Hash#deep_transform_keys!`. *Mark McSpadden*
@@ -57,8 +57,16 @@
* Adds `encode_big_decimal_as_string` option to force JSON serialization of BigDecimals as numeric instead
of wrapping them in strings for safety.
+* Remove deprecated ActiveSupport::JSON::Variable. *Erich Menge*
-## Rails 3.2.4 (unreleased) ##
+
+## Rails 3.2.5 (Jun 1, 2012) ##
+
+* ActiveSupport::JSON::Variable is deprecated. Define your own #as_json and #encode_json methods
+ for custom JSON string literals. *Erich Menge*
+
+
+## Rails 3.2.4 (May 31, 2012) ##
* Added #beginning_of_hour and #end_of_hour to Time and DateTime core
extensions. *Mark J. Titorenko*
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index a9253c186d..0aa3efbb63 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -328,17 +328,26 @@ module ActiveSupport
# if it was not yet defined.
# This generated method plays caching role.
def __define_callbacks(kind, object) #:nodoc:
- chain = object.send("_#{kind}_callbacks")
- name = "_run_callbacks_#{chain.object_id.abs}"
+ name = __callback_runner_name(kind)
unless object.respond_to?(name, true)
+ str = object.send("_#{kind}_callbacks").compile
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
- def #{name}() #{chain.compile} end
+ def #{name}() #{str} end
protected :#{name}
RUBY_EVAL
end
name
end
+ def __reset_runner(symbol)
+ name = __callback_runner_name(symbol)
+ undef_method(name) if method_defined?(name)
+ end
+
+ def __callback_runner_name(kind)
+ "_run__#{self.name.hash.abs}__#{kind}__callbacks"
+ end
+
# This is used internally to append, prepend and skip callbacks to the
# CallbackChain.
#
@@ -350,6 +359,7 @@ module ActiveSupport
([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse.each do |target|
chain = target.send("_#{name}_callbacks")
yield target, chain.dup, type, filters, options
+ target.__reset_runner(name)
end
end
@@ -437,9 +447,12 @@ module ActiveSupport
chain = target.send("_#{symbol}_callbacks").dup
callbacks.each { |c| chain.delete(c) }
target.send("_#{symbol}_callbacks=", chain)
+ target.__reset_runner(symbol)
end
self.send("_#{symbol}_callbacks=", callbacks.dup.clear)
+
+ __reset_runner(symbol)
end
# Define sets of events in the object lifecycle that support callbacks.
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
index 59709a19f1..c319e94bc6 100644
--- a/activesupport/lib/active_support/json/encoding.rb
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -1,6 +1,5 @@
require 'active_support/core_ext/object/to_json'
require 'active_support/core_ext/module/delegation'
-require 'active_support/json/variable'
require 'bigdecimal'
require 'active_support/core_ext/big_decimal/conversions' # for #to_s
diff --git a/activesupport/lib/active_support/json/variable.rb b/activesupport/lib/active_support/json/variable.rb
deleted file mode 100644
index 5685ed18b7..0000000000
--- a/activesupport/lib/active_support/json/variable.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-module ActiveSupport
- module JSON
- # A string that returns itself as its JSON-encoded form.
- class Variable < String
- def as_json(options = nil) self end #:nodoc:
- def encode_json(encoder) self end #:nodoc:
- end
- end
-end
diff --git a/activesupport/lib/active_support/testing/performance/ruby.rb b/activesupport/lib/active_support/testing/performance/ruby.rb
index 1104fc0a03..12aef0d7fe 100644
--- a/activesupport/lib/active_support/testing/performance/ruby.rb
+++ b/activesupport/lib/active_support/testing/performance/ruby.rb
@@ -18,6 +18,7 @@ module ActiveSupport
end).freeze
protected
+ remove_method :run_gc
def run_gc
GC.start
end
@@ -28,6 +29,7 @@ module ActiveSupport
@supported = @metric.measure_mode rescue false
end
+ remove_method :run
def run
return unless @supported
@@ -39,6 +41,7 @@ module ActiveSupport
@total = @data.threads.sum(0) { |thread| thread.methods.max.total_time }
end
+ remove_method :record
def record
return unless @supported
@@ -78,6 +81,7 @@ module ActiveSupport
self.class::Mode
end
+ remove_method :profile
def profile
RubyProf.resume
yield
@@ -86,6 +90,7 @@ module ActiveSupport
end
protected
+ remove_method :with_gc_stats
def with_gc_stats
GC::Profiler.enable
GC.start
diff --git a/activesupport/test/core_ext/file_test.rb b/activesupport/test/core_ext/file_test.rb
index 50c9c57aa6..128e956a8c 100644
--- a/activesupport/test/core_ext/file_test.rb
+++ b/activesupport/test/core_ext/file_test.rb
@@ -30,7 +30,7 @@ class AtomicWriteTest < ActiveSupport::TestCase
assert File.exist?(file_name)
end
assert File.exist?(file_name)
- assert_equal 0100755, file_mode
+ assert_equal 0100755 & ~File.umask, file_mode
assert_equal contents, File.read(file_name)
File.atomic_write(file_name, Dir.pwd) do |file|
@@ -38,7 +38,7 @@ class AtomicWriteTest < ActiveSupport::TestCase
assert File.exist?(file_name)
end
assert File.exist?(file_name)
- assert_equal 0100755, file_mode
+ assert_equal 0100755 & ~File.umask, file_mode
assert_equal contents, File.read(file_name)
ensure
File.unlink(file_name) rescue nil
@@ -51,7 +51,7 @@ class AtomicWriteTest < ActiveSupport::TestCase
assert !File.exist?(file_name)
end
assert File.exist?(file_name)
- assert_equal 0100666 ^ File.umask, file_mode
+ assert_equal 0100666 & ~File.umask, file_mode
assert_equal contents, File.read(file_name)
ensure
File.unlink(file_name) rescue nil
diff --git a/activesupport/test/core_ext/kernel_test.rb b/activesupport/test/core_ext/kernel_test.rb
index e90b9d454f..99e4506be7 100644
--- a/activesupport/test/core_ext/kernel_test.rb
+++ b/activesupport/test/core_ext/kernel_test.rb
@@ -96,15 +96,16 @@ class KernelDebuggerTest < ActiveSupport::TestCase
end
def test_debugger_not_available_message_to_rails_logger
+ Object.send(:remove_const, :Rails) if Object.const_defined?(:Rails)
rails = Class.new do
def self.logger
@logger ||= MockStdErr.new
end
end
- Object.const_set("Rails", rails)
+ Object.const_set(:Rails, rails)
debugger
assert_match(/Debugger requested/, rails.logger.output.first)
ensure
- Object.send(:remove_const, "Rails")
+ Object.send(:remove_const, :Rails)
end
end
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index 212ee262a3..a947635f4a 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -54,8 +54,6 @@ class TestJSONEncoding < ActiveSupport::TestCase
HashlikeTests = [[ Hashlike.new, %({\"a\":1}) ]]
CustomTests = [[ Custom.new, '"custom"' ]]
- VariableTests = [[ ActiveSupport::JSON::Variable.new('foo'), 'foo'],
- [ ActiveSupport::JSON::Variable.new('alert("foo")'), 'alert("foo")']]
RegexpTests = [[ /^a/, '"(?-mix:^a)"' ], [/^\w{1,2}[a-z]+/ix, '"(?ix-m:^\\\\w{1,2}[a-z]+)"']]
DateTests = [[ Date.new(2005,2,1), %("2005/02/01") ]]
diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile
index 294ef25b33..4b14671efc 100644
--- a/guides/source/active_record_querying.textile
+++ b/guides/source/active_record_querying.textile
@@ -259,6 +259,54 @@ SELECT * FROM clients WHERE (clients.id IN (1,10))
WARNING: <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
+h5. take
+
+<tt>Model.take(limit)</tt> retrieves the first number of records specified by +limit+ without any explicit ordering:
+
+<ruby>
+Client.take(2)
+# => [#<Client id: 1, first_name: "Lifo">,
+ #<Client id: 2, first_name: "Raf">]
+</ruby>
+
+The SQL equivalent of the above is:
+
+<sql>
+SELECT * FROM clients LIMIT 2
+</sql>
+
+h5. first
+
+<tt>Model.first(limit)</tt> finds the first number of records specified by +limit+ ordered by primary key:
+
+<ruby>
+Client.first(2)
+# => [#<Client id: 1, first_name: "Lifo">,
+ #<Client id: 2, first_name: "Raf">]
+</ruby>
+
+The SQL equivalent of the above is:
+
+<sql>
+SELECT * FROM clients LIMIT 2
+</sql>
+
+h5. last
+
+<tt>Model.last(limit)</tt> finds the number of records specified by +limit+ ordered by primary key in descending order:
+
+<ruby>
+Client.last(2)
+# => [#<Client id: 10, first_name: "Ryan">,
+ #<Client id: 9, first_name: "John">]
+</ruby>
+
+The SQL equivalent of the above is:
+
+<sql>
+SELECT * FROM clients ORDER By id DESC LIMIT 2
+</sql>
+
h4. Retrieving Multiple Objects in Batches
We often need to iterate over a large set of records, as when we send a newsletter to a large set of users, or when we export data.
diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb
index bcac0751d6..1aed2796c1 100644
--- a/railties/lib/rails/code_statistics.rb
+++ b/railties/lib/rails/code_statistics.rb
@@ -26,7 +26,7 @@ class CodeStatistics #:nodoc:
Hash[@pairs.map{|pair| [pair.first, calculate_directory_statistics(pair.last)]}]
end
- def calculate_directory_statistics(directory, pattern = /.*\.rb$/)
+ def calculate_directory_statistics(directory, pattern = /.*\.(rb|js|coffee)$/)
stats = { "lines" => 0, "codelines" => 0, "classes" => 0, "methods" => 0 }
Dir.foreach(directory) do |file_name|
@@ -39,6 +39,13 @@ class CodeStatistics #:nodoc:
comment_started = false
+ case file_name
+ when /.*\.js$/
+ comment_pattern = /^\s*\/\//
+ else
+ comment_pattern = /^\s*#/
+ end
+
File.open(directory + "/" + file_name) do |f|
while line = f.gets
stats["lines"] += 1
@@ -55,7 +62,7 @@ class CodeStatistics #:nodoc:
end
stats["classes"] += 1 if line =~ /^\s*class\s+[_A-Z]/
stats["methods"] += 1 if line =~ /^\s*def\s+[_a-z]/
- stats["codelines"] += 1 unless line =~ /^\s*$/ || line =~ /^\s*#/
+ stats["codelines"] += 1 unless line =~ /^\s*$/ || line =~ comment_pattern
end
end
end
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
index 7f473c237c..8816387d34 100644
--- a/railties/lib/rails/commands.rb
+++ b/railties/lib/rails/commands.rb
@@ -36,9 +36,17 @@ when 'benchmarker', 'profiler'
when 'console'
require 'rails/commands/console'
+ options = Rails::Console.parse_arguments(ARGV)
+
+ # RAILS_ENV needs to be set before config/application is required
+ ENV['RAILS_ENV'] = options[:environment] if options[:environment]
+
+ # shift ARGV so IRB doesn't freak
+ ARGV.shift if ARGV.first && ARGV.first[0] != '-'
+
require APP_PATH
Rails.application.require_environment!
- Rails::Console.start(Rails.application)
+ Rails::Console.start(Rails.application, options)
when 'server'
# Change to the application's path if there is no config.ru file in current dir.
diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb
index b95df3e545..92cee6b638 100644
--- a/railties/lib/rails/commands/console.rb
+++ b/railties/lib/rails/commands/console.rb
@@ -4,21 +4,12 @@ require 'irb/completion'
module Rails
class Console
- attr_reader :options, :app, :console, :arguments
-
- def self.start(*args)
- new(*args).start
- end
-
- def initialize(app, arguments = ARGV)
- @app = app
- @arguments = arguments
- app.load_console
- @console = app.config.console || IRB
- end
+ class << self
+ def start(*args)
+ new(*args).start
+ end
- def options
- @options ||= begin
+ def parse_arguments(arguments)
options = {}
OptionParser.new do |opt|
@@ -31,20 +22,38 @@ module Rails
opt.parse!(arguments)
end
+ if arguments.first && arguments.first[0] != '-'
+ env = arguments.first
+ options[:environment] = %w(production development test).detect {|e| e =~ /^#{env}/} || env
+ end
+
options
end
end
+ attr_reader :options, :app, :console
+
+ def initialize(app, options={})
+ @app = app
+ @options = options
+ app.load_console
+ @console = app.config.console || IRB
+ end
+
def sandbox?
options[:sandbox]
end
+ def environment
+ options[:environment] ||= ENV['RAILS_ENV'] || 'development'
+ end
+
def environment?
- options[:environment]
+ environment
end
def set_environment!
- Rails.env = options[:environment]
+ Rails.env = environment
end
def debugger?
@@ -53,9 +62,7 @@ module Rails
def start
app.sandbox = sandbox?
-
require_debugger if debugger?
-
set_environment! if environment?
if sandbox?
@@ -82,8 +89,3 @@ module Rails
end
end
end
-
-# Has to set the RAILS_ENV before config/application is required
-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/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index cc7caffc3d..cc0552184a 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -5,66 +5,19 @@ require 'rbconfig'
module Rails
class DBConsole
- attr_reader :arguments, :config
-
+ attr_reader :config, :arguments
+
def self.start
- new(config).start
+ new.start
end
- def self.config
- config = begin
- YAML.load(ERB.new(IO.read("config/database.yml")).result)
- rescue SyntaxError, StandardError
- require APP_PATH
- Rails.application.config.database_configuration
- end
-
- unless config[env]
- abort "No database is configured for the environment '#{env}'"
- end
-
- config[env]
- end
-
- def self.env
- if Rails.respond_to?(:env)
- Rails.env
- else
- ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
- end
- end
-
- def initialize(config, arguments = ARGV)
- @config, @arguments = config, arguments
+ def initialize(arguments = ARGV)
+ @arguments = arguments
end
def start
- include_password = false
- options = {}
- OptionParser.new do |opt|
- opt.banner = "Usage: rails dbconsole [environment] [options]"
- opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v|
- include_password = true
- end
-
- opt.on("--mode [MODE]", ['html', 'list', 'line', 'column'],
- "Automatically put the sqlite3 database in the specified mode (html, list, line, column).") do |mode|
- options['mode'] = mode
- end
-
- opt.on("--header") do |h|
- options['header'] = h
- end
-
- opt.on("-h", "--help", "Show this help message.") do
- puts opt
- exit
- end
-
- opt.parse!(arguments)
- abort opt.to_s unless (0..1).include?(arguments.size)
- end
-
+ options = parse_arguments(arguments)
+ ENV['RAILS_ENV'] = options[:environment] || environment
case config["adapter"]
when /^mysql/
@@ -76,7 +29,7 @@ module Rails
'encoding' => '--default-character-set'
}.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact
- if config['password'] && include_password
+ if config['password'] && options['include_password']
args << "--password=#{config['password']}"
elsif config['password'] && !config['password'].to_s.empty?
args << "-p"
@@ -90,7 +43,7 @@ module Rails
ENV['PGUSER'] = config["username"] if config["username"]
ENV['PGHOST'] = config["host"] if config["host"]
ENV['PGPORT'] = config["port"].to_s if config["port"]
- ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && include_password
+ ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && options['include_password']
find_cmd_and_exec('psql', config["database"])
when "sqlite"
@@ -110,7 +63,7 @@ module Rails
if config['username']
logon = config['username']
- logon << "/#{config['password']}" if config['password'] && include_password
+ logon << "/#{config['password']}" if config['password'] && options['include_password']
logon << "@#{config['database']}" if config['database']
end
@@ -121,8 +74,73 @@ module Rails
end
end
+ def config
+ @config ||= begin
+ cfg = begin
+ cfg = YAML.load(ERB.new(IO.read("config/database.yml")).result)
+ rescue SyntaxError, StandardError
+ require APP_PATH
+ Rails.application.config.database_configuration
+ end
+
+ unless cfg[environment]
+ abort "No database is configured for the environment '#{environment}'"
+ end
+
+ cfg[environment]
+ end
+ end
+
+ def environment
+ if Rails.respond_to?(:env)
+ Rails.env
+ else
+ ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
+ end
+ end
+
protected
+ def parse_arguments(arguments)
+ options = {}
+
+ OptionParser.new do |opt|
+ opt.banner = "Usage: rails dbconsole [environment] [options]"
+ opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v|
+ options['include_password'] = true
+ end
+
+ opt.on("--mode [MODE]", ['html', 'list', 'line', 'column'],
+ "Automatically put the sqlite3 database in the specified mode (html, list, line, column).") do |mode|
+ options['mode'] = mode
+ end
+
+ opt.on("--header") do |h|
+ options['header'] = h
+ end
+
+ opt.on("-h", "--help", "Show this help message.") do
+ puts opt
+ exit
+ end
+
+ opt.on("-e", "--environment=name", String,
+ "Specifies the environment to run this console under (test/development/production).",
+ "Default: development"
+ ) { |v| options[:environment] = v.strip }
+
+ opt.parse!(arguments)
+ abort opt.to_s unless (0..1).include?(arguments.size)
+ end
+
+ if arguments.first && arguments.first[0] != '-'
+ env = arguments.first
+ options[:environment] = %w(production development test).detect {|e| e =~ /^#{env}/} || env
+ end
+
+ options
+ end
+
def find_cmd_and_exec(commands, *args)
commands = Array(commands)
@@ -145,8 +163,3 @@ module Rails
end
end
end
-
-# Has to set the RAILS_ENV before config/application is required
-if ARGV.first && !ARGV.first.index("-") && env = ARGV.first
- ENV['RAILS_ENV'] = %w(production development test).detect {|e| e =~ /^#{env}/} || env
-end
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index e68d2e05c5..9ef64da3ef 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -32,11 +32,6 @@ module Rails
opt_parser.parse! args
- # Handle's environment like RAILS_ENV=production passed in directly
- if index = args.index {|arg| arg.include?("RAILS_ENV")}
- options[:environment] ||= args.delete_at(index).split('=').last
- end
-
options[:server] = args.shift
options
end
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index 2c1742c6be..5838c9fc38 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -230,7 +230,7 @@ module Rails
if defined?(JRUBY_VERSION)
"gem 'therubyrhino'\n"
else
- "# gem 'therubyracer', platform: :ruby\n"
+ "# gem 'therubyracer', platforms: :ruby\n"
end
end
diff --git a/railties/lib/rails/generators/rails/controller/templates/controller.rb b/railties/lib/rails/generators/rails/controller/templates/controller.rb
index ece6bbba3b..4053113b4b 100644
--- a/railties/lib/rails/generators/rails/controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/controller/templates/controller.rb
@@ -1,7 +1,7 @@
<% if namespaced? -%>
require_dependency "<%= namespaced_file_path %>/application_controller"
-<% end -%>
+<% end -%>
<% module_namespacing do -%>
class <%= class_name %>Controller < ApplicationController
<% actions.each do |action| -%>
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
index 0294bde582..b3e74f9b02 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
@@ -1,7 +1,7 @@
<% if namespaced? -%>
require_dependency "<%= namespaced_file_path %>/application_controller"
-<% end -%>
+<% end -%>
<% module_namespacing do -%>
class <%= controller_class_name %>Controller < ApplicationController
# GET <%= route_url %>
diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb
index c3cc65ab31..a06be59759 100644
--- a/railties/lib/rails/railtie.rb
+++ b/railties/lib/rails/railtie.rb
@@ -190,7 +190,8 @@ module Rails
end
def load_tasks(app=self)
- extend Rake::DSL if defined? Rake::DSL
+ require 'rake'
+ extend Rake::DSL
self.class.rake_tasks.each { |block| self.instance_exec(app, &block) }
# load also tasks from all superclasses
diff --git a/railties/lib/rails/tasks/documentation.rake b/railties/lib/rails/tasks/documentation.rake
index 4ec49eee76..2851ca4189 100644
--- a/railties/lib/rails/tasks/documentation.rake
+++ b/railties/lib/rails/tasks/documentation.rake
@@ -2,7 +2,7 @@ require 'rdoc/task'
# Monkey-patch to remove redoc'ing and clobber descriptions to cut down on rake -T noise
class RDocTaskWithoutDescriptions < RDoc::Task
- include ::Rake::DSL if defined?(::Rake::DSL)
+ include ::Rake::DSL
def define
task rdoc_task_name
diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake
index 7dc54144da..5778b22f18 100644
--- a/railties/lib/rails/tasks/routes.rake
+++ b/railties/lib/rails/tasks/routes.rake
@@ -1,8 +1,6 @@
desc 'Print out all defined routes in match order, with names. Target specific controller with CONTROLLER=x.'
task :routes => :environment do
- Rails.application.reload_routes!
all_routes = Rails.application.routes.routes
-
require 'rails/application/route_inspector'
inspector = Rails::Application::RouteInspector.new
puts inspector.format(all_routes, ENV['CONTROLLER']).join "\n"
diff --git a/railties/lib/rails/tasks/statistics.rake b/railties/lib/rails/tasks/statistics.rake
index f684e71267..67a6d2d2ac 100644
--- a/railties/lib/rails/tasks/statistics.rake
+++ b/railties/lib/rails/tasks/statistics.rake
@@ -3,6 +3,7 @@ STATS_DIRECTORIES = [
%w(Helpers app/helpers),
%w(Models app/models),
%w(Mailers app/mailers),
+ %w(Javascripts app/assets/javascripts),
%w(Libraries lib/),
%w(APIs app/apis),
%w(Integration\ tests test/integration),
diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb
index 78648a16b3..91ede1cb68 100644
--- a/railties/test/commands/console_test.rb
+++ b/railties/test/commands/console_test.rb
@@ -3,47 +3,44 @@ require 'rails/commands/console'
class Rails::ConsoleTest < ActiveSupport::TestCase
class FakeConsole
+ def self.start; end
end
def setup
end
def test_sandbox_option
- console = Rails::Console.new(app, ["--sandbox"])
+ console = Rails::Console.new(app, parse_arguments(["--sandbox"]))
assert console.sandbox?
end
def test_short_version_of_sandbox_option
- console = Rails::Console.new(app, ["-s"])
+ console = Rails::Console.new(app, parse_arguments(["-s"]))
assert console.sandbox?
end
def test_debugger_option
- console = Rails::Console.new(app, ["--debugger"])
+ console = Rails::Console.new(app, parse_arguments(["--debugger"]))
assert console.debugger?
end
def test_no_options
- console = Rails::Console.new(app, [])
+ console = Rails::Console.new(app, parse_arguments([]))
assert !console.debugger?
assert !console.sandbox?
end
def test_start
- app.expects(:sandbox=).with(nil)
FakeConsole.expects(:start)
-
start
-
assert_match(/Loading \w+ environment \(Rails/, output)
end
def test_start_with_debugger
- app.expects(:sandbox=).with(nil)
+ rails_console = Rails::Console.new(app, parse_arguments(["--debugger"]))
rails_console.expects(:require_debugger).returns(nil)
- FakeConsole.expects(:start)
- start ["--debugger"]
+ silence_stream(STDOUT) { rails_console.start }
end
def test_start_with_sandbox
@@ -56,42 +53,63 @@ class Rails::ConsoleTest < ActiveSupport::TestCase
end
def test_console_with_environment
- app.expects(:sandbox=).with(nil)
- FakeConsole.expects(:start)
-
start ["-e production"]
+ assert_match(/\sproduction\s/, output)
+ end
+
+ def test_console_defaults_to_IRB
+ config = mock("config", :console => nil)
+ app = mock("app", :config => config)
+ app.expects(:load_console).returns(nil)
- assert_match(/production/, output)
+ assert_equal IRB, Rails::Console.new(app).console
end
- def test_console_with_rails_environment
- app.expects(:sandbox=).with(nil)
- FakeConsole.expects(:start)
+ def test_default_environment_with_no_rails_env
+ with_rails_env nil do
+ start
+ assert_match /\sdevelopment\s/, output
+ end
+ end
- start ["RAILS_ENV=production"]
+ def test_default_environment_with_rails_env
+ with_rails_env 'special-production' do
+ start
+ assert_match /\sspecial-production\s/, output
+ end
+ end
+
+ def test_e_option
+ start ['-e', 'special-production']
+ assert_match /\sspecial-production\s/, output
+ end
- assert_match(/production/, output)
+ def test_environment_option
+ start ['--environment=special-production']
+ assert_match /\sspecial-production\s/, output
end
+ def test_rails_env_is_production_when_first_argument_is_p
+ start ['p']
+ assert_match /\sproduction\s/, output
+ end
- def test_console_defaults_to_IRB
- config = mock("config", :console => nil)
- app = mock("app", :config => config)
- app.expects(:load_console).returns(nil)
+ def test_rails_env_is_test_when_first_argument_is_t
+ start ['t']
+ assert_match /\stest\s/, output
+ end
- assert_equal IRB, Rails::Console.new(app).console
+ def test_rails_env_is_development_when_argument_is_d
+ start ['d']
+ assert_match /\sdevelopment\s/, output
end
private
attr_reader :output
- def rails_console
- @rails_console ||= Rails::Console.new(app)
- end
-
def start(argv = [])
- rails_console.stubs(:arguments => argv)
+ rails_console = Rails::Console.new(app, parse_arguments(argv))
@output = output = capture(:stdout) { rails_console.start }
end
@@ -99,8 +117,21 @@ class Rails::ConsoleTest < ActiveSupport::TestCase
@app ||= begin
config = mock("config", :console => FakeConsole)
app = mock("app", :config => config)
+ app.stubs(:sandbox=).returns(nil)
app.expects(:load_console)
app
end
end
+
+ def parse_arguments(args)
+ Rails::Console.parse_arguments(args)
+ end
+
+ def with_rails_env(env)
+ original_rails_env = ENV['RAILS_ENV']
+ ENV['RAILS_ENV'] = env
+ yield
+ ensure
+ ENV['RAILS_ENV'] = original_rails_env
+ end
end
diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb
index 562b83713b..d45bdaabf5 100644
--- a/railties/test/commands/dbconsole_test.rb
+++ b/railties/test/commands/dbconsole_test.rb
@@ -10,35 +10,37 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
Rails::DBConsole.const_set(:APP_PATH, "erb")
app_config({})
- capture_abort { Rails::DBConsole.config }
+ capture_abort { Rails::DBConsole.new.config }
assert aborted
assert_match(/No database is configured for the environment '\w+'/, output)
app_config(test: "with_init")
- assert_equal Rails::DBConsole.config, "with_init"
+ assert_equal Rails::DBConsole.new.config, "with_init"
app_db_file("test:\n without_init")
- assert_equal Rails::DBConsole.config, "without_init"
+ assert_equal Rails::DBConsole.new.config, "without_init"
app_db_file("test:\n <%= Rails.something_app_specific %>")
- assert_equal Rails::DBConsole.config, "with_init"
+ assert_equal Rails::DBConsole.new.config, "with_init"
app_db_file("test:\n\ninvalid")
- assert_equal Rails::DBConsole.config, "with_init"
+ assert_equal Rails::DBConsole.new.config, "with_init"
end
def test_env
- assert_equal Rails::DBConsole.env, "test"
+ assert_equal Rails::DBConsole.new.environment, "test"
+
+ ENV['RAILS_ENV'] = nil
+ ENV['RACK_ENV'] = nil
Rails.stubs(:respond_to?).with(:env).returns(false)
- assert_equal Rails::DBConsole.env, "test"
+ assert_equal Rails::DBConsole.new.environment, "development"
- ENV['RAILS_ENV'] = nil
ENV['RACK_ENV'] = "rack_env"
- assert_equal Rails::DBConsole.env, "rack_env"
+ assert_equal Rails::DBConsole.new.environment, "rack_env"
ENV['RAILS_ENV'] = "rails_env"
- assert_equal Rails::DBConsole.env, "rails_env"
+ assert_equal Rails::DBConsole.new.environment, "rails_env"
ensure
ENV['RAILS_ENV'] = "test"
end
diff --git a/railties/test/commands/server_test.rb b/railties/test/commands/server_test.rb
index 8039aec873..4a3ea82e3d 100644
--- a/railties/test/commands/server_test.rb
+++ b/railties/test/commands/server_test.rb
@@ -4,14 +4,14 @@ require 'rails/commands/server'
class Rails::ServerTest < ActiveSupport::TestCase
def test_environment_with_server_option
- args = ["thin", "RAILS_ENV=production"]
+ args = ["thin", "-e", "production"]
options = Rails::Server::Options.new.parse!(args)
assert_equal 'production', options[:environment]
assert_equal 'thin', options[:server]
end
def test_environment_without_server_option
- args = ["RAILS_ENV=production"]
+ args = ["-e", "production"]
options = Rails::Server::Options.new.parse!(args)
assert_equal 'production', options[:environment]
assert_nil options[:server]
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 26e912fd9e..5534476a6d 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -246,7 +246,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
if defined?(JRUBY_VERSION)
assert_gem "therubyrhino"
else
- assert_file "Gemfile", /# gem\s+["']therubyracer["']+, platform: :ruby$/
+ assert_file "Gemfile", /# gem\s+["']therubyracer["']+, platforms: :ruby$/
end
end