diff options
131 files changed, 3101 insertions, 2200 deletions
diff --git a/actionmailer/CHANGELOG b/actionmailer/CHANGELOG index bdae0d4d3d..fc02ae8ffc 100644 --- a/actionmailer/CHANGELOG +++ b/actionmailer/CHANGELOG @@ -1,3 +1,8 @@ +* Add layout functionality to mailers [Pratik] + + Mailer layouts behaves just like controller layouts, except layout names need to + have '_mailer' postfix for them to be automatically picked up. + *2.1.0 (May 31st, 2008)* * Fixed that a return-path header would be ignored #7572 [joost] diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 72c94529b5..96e514e0db 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -246,7 +246,10 @@ module ActionMailer #:nodoc: # +implicit_parts_order+. class Base include AdvAttrAccessor, PartContainer - include ActionController::UrlWriter if Object.const_defined?(:ActionController) + if Object.const_defined?(:ActionController) + include ActionController::UrlWriter + include ActionController::Layout + end private_class_method :new #:nodoc: @@ -362,6 +365,7 @@ module ActionMailer #:nodoc: # The mail object instance referenced by this mailer. attr_reader :mail + attr_reader :template_name, :default_template_name, :action_name class << self attr_writer :mailer_name @@ -374,11 +378,16 @@ module ActionMailer #:nodoc: alias_method :controller_name, :mailer_name alias_method :controller_path, :mailer_name - def method_missing(method_symbol, *parameters)#:nodoc: - case method_symbol.id2name - when /^create_([_a-z]\w*)/ then new($1, *parameters).mail - when /^deliver_([_a-z]\w*)/ then new($1, *parameters).deliver! - when "new" then nil + def respond_to?(method_symbol, include_private = false) #:nodoc: + matches_dynamic_method?(method_symbol) || super + end + + def method_missing(method_symbol, *parameters) #:nodoc: + match = matches_dynamic_method?(method_symbol) + case match[1] + when 'create' then new(match[2], *parameters).mail + when 'deliver' then new(match[2], *parameters).deliver! + when 'new' then nil else super end end @@ -424,6 +433,12 @@ module ActionMailer #:nodoc: def template_root=(root) self.view_paths = ActionView::Base.process_view_paths(root) end + + private + def matches_dynamic_method?(method_name) #:nodoc: + method_name = method_name.to_s + /(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name) + end end # Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer @@ -519,6 +534,7 @@ module ActionMailer #:nodoc: @content_type ||= @@default_content_type.dup @implicit_parts_order ||= @@default_implicit_parts_order.dup @template ||= method_name + @default_template_name = @action_name = @template @mailer_name ||= self.class.name.underscore @parts ||= [] @headers ||= {} @@ -535,7 +551,22 @@ module ActionMailer #:nodoc: if opts[:file] && (opts[:file] !~ /\// && !opts[:file].respond_to?(:render)) opts[:file] = "#{mailer_name}/#{opts[:file]}" end - initialize_template_class(body).render(opts) + + begin + old_template, @template = @template, initialize_template_class(body) + layout = respond_to?(:pick_layout, true) ? pick_layout(opts) : false + @template.render(opts.merge(:layout => layout)) + ensure + @template = old_template + end + end + + def default_template_format + :html + end + + def candidate_for_layout?(options) + !@template.send(:_exempt_from_layout?, default_template_name) end def template_root diff --git a/actionmailer/lib/action_mailer/helpers.rb b/actionmailer/lib/action_mailer/helpers.rb index 9c5fcc6afb..5f6dcd77cd 100644 --- a/actionmailer/lib/action_mailer/helpers.rb +++ b/actionmailer/lib/action_mailer/helpers.rb @@ -72,7 +72,7 @@ module ActionMailer methods.flatten.each do |method| master_helper_module.module_eval <<-end_eval def #{method}(*args, &block) - controller.send!(%(#{method}), *args, &block) + controller.__send__(%(#{method}), *args, &block) end end_eval end @@ -92,7 +92,7 @@ module ActionMailer inherited_without_helper(child) begin child.master_helper_module = Module.new - child.master_helper_module.send! :include, master_helper_module + child.master_helper_module.__send__(:include, master_helper_module) child.helper child.name.to_s.underscore rescue MissingSourceFile => e raise unless e.is_missing?("helpers/#{child.name.to_s.underscore}_helper") diff --git a/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb b/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb new file mode 100644 index 0000000000..54950788f7 --- /dev/null +++ b/actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb @@ -0,0 +1 @@ +Inside
\ No newline at end of file diff --git a/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb b/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb new file mode 100644 index 0000000000..0533a3b2fe --- /dev/null +++ b/actionmailer/test/fixtures/explicit_layout_mailer/logout.html.erb @@ -0,0 +1 @@ +You logged out
\ No newline at end of file diff --git a/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb b/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb new file mode 100644 index 0000000000..4789e888c6 --- /dev/null +++ b/actionmailer/test/fixtures/explicit_layout_mailer/signup.html.erb @@ -0,0 +1 @@ +We do not spam
\ No newline at end of file diff --git a/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb b/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb new file mode 100644 index 0000000000..932271450c --- /dev/null +++ b/actionmailer/test/fixtures/layouts/auto_layout_mailer.html.erb @@ -0,0 +1 @@ +Hello from layout <%= yield %>
\ No newline at end of file diff --git a/actionmailer/test/fixtures/layouts/spam.html.erb b/actionmailer/test/fixtures/layouts/spam.html.erb new file mode 100644 index 0000000000..619d6b16b4 --- /dev/null +++ b/actionmailer/test/fixtures/layouts/spam.html.erb @@ -0,0 +1 @@ +Spammer layout <%= yield %>
\ No newline at end of file diff --git a/actionmailer/test/mail_layout_test.rb b/actionmailer/test/mail_layout_test.rb new file mode 100644 index 0000000000..ffba9a16bd --- /dev/null +++ b/actionmailer/test/mail_layout_test.rb @@ -0,0 +1,78 @@ +require 'abstract_unit' + +class AutoLayoutMailer < ActionMailer::Base + def hello(recipient) + recipients recipient + subject "You have a mail" + from "tester@example.com" + end + + def spam(recipient) + recipients recipient + subject "You have a mail" + from "tester@example.com" + body render(:inline => "Hello, <%= @world %>", :layout => 'spam', :body => { :world => "Earth" }) + end + + def nolayout(recipient) + recipients recipient + subject "You have a mail" + from "tester@example.com" + body render(:inline => "Hello, <%= @world %>", :layout => false, :body => { :world => "Earth" }) + end +end + +class ExplicitLayoutMailer < ActionMailer::Base + layout 'spam', :except => [:logout] + + def signup(recipient) + recipients recipient + subject "You have a mail" + from "tester@example.com" + end + + def logout(recipient) + recipients recipient + subject "You have a mail" + from "tester@example.com" + end +end + +class LayoutMailerTest < Test::Unit::TestCase + def setup + set_delivery_method :test + ActionMailer::Base.perform_deliveries = true + ActionMailer::Base.deliveries = [] + + @recipient = 'test@localhost' + end + + def teardown + restore_delivery_method + end + + def test_should_pickup_default_layout + mail = AutoLayoutMailer.create_hello(@recipient) + assert_equal "Hello from layout Inside", mail.body.strip + end + + def test_should_pickup_layout_given_to_render + mail = AutoLayoutMailer.create_spam(@recipient) + assert_equal "Spammer layout Hello, Earth", mail.body.strip + end + + def test_should_respect_layout_false + mail = AutoLayoutMailer.create_nolayout(@recipient) + assert_equal "Hello, Earth", mail.body.strip + end + + def test_explicit_class_layout + mail = ExplicitLayoutMailer.create_signup(@recipient) + assert_equal "Spammer layout We do not spam", mail.body.strip + end + + def test_explicit_layout_exceptions + mail = ExplicitLayoutMailer.create_logout(@recipient) + assert_equal "You logged out", mail.body.strip + end +end diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb index 882b07d675..f57c6f3fb8 100644 --- a/actionmailer/test/mail_service_test.rb +++ b/actionmailer/test/mail_service_test.rb @@ -968,3 +968,55 @@ class MethodNamingTest < Test::Unit::TestCase end end end + +class RespondToTest < Test::Unit::TestCase + class RespondToMailer < ActionMailer::Base; end + + def setup + set_delivery_method :test + end + + def teardown + restore_delivery_method + end + + def test_should_respond_to_new + assert RespondToMailer.respond_to?(:new) + end + + def test_should_respond_to_create_with_template_suffix + assert RespondToMailer.respond_to?(:create_any_old_template) + end + + def test_should_respond_to_deliver_with_template_suffix + assert RespondToMailer.respond_to?(:deliver_any_old_template) + end + + def test_should_not_respond_to_new_with_template_suffix + assert !RespondToMailer.respond_to?(:new_any_old_template) + end + + def test_should_not_respond_to_create_with_template_suffix_unless_it_is_separated_by_an_underscore + assert !RespondToMailer.respond_to?(:createany_old_template) + end + + def test_should_not_respond_to_deliver_with_template_suffix_unless_it_is_separated_by_an_underscore + assert !RespondToMailer.respond_to?(:deliverany_old_template) + end + + def test_should_not_respond_to_create_with_template_suffix_if_it_begins_with_a_uppercase_letter + assert !RespondToMailer.respond_to?(:create_Any_old_template) + end + + def test_should_not_respond_to_deliver_with_template_suffix_if_it_begins_with_a_uppercase_letter + assert !RespondToMailer.respond_to?(:deliver_Any_old_template) + end + + def test_should_not_respond_to_create_with_template_suffix_if_it_begins_with_a_digit + assert !RespondToMailer.respond_to?(:create_1_template) + end + + def test_should_not_respond_to_deliver_with_template_suffix_if_it_begins_with_a_digit + assert !RespondToMailer.respond_to?(:deliver_1_template) + end +end diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index f6942b43f1..88af60ed62 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,29 @@ *Edge* +* Add support for shallow nesting of routes. #838 [S. Brent Faulkner] + + Example : + + map.resources :users, :shallow => true do |user| + user.resources :posts + end + + - GET /users/1/posts (maps to PostsController#index action as usual) + named route "user_posts" is added as usual. + + - GET /posts/2 (maps to PostsController#show action as if it were not nested) + Additionally, named route "post" is added too. + +* Added button_to_remote helper. #3641 [Donald Piret, Tarmo Tänav] + +* Deprecate render_component. Please use render_component plugin from http://github.com/rails/render_component/tree/master [Pratik] + +* Routes may be restricted to lists of HTTP methods instead of a single method or :any. #407 [Brennan Dunn, Gaius Centus Novus] + map.resource :posts, :collection => { :search => [:get, :post] } + map.session 'session', :requirements => { :method => [:get, :post, :delete] } + +* Deprecated implicit local assignments when rendering partials [Josh Peek] + * Introduce current_cycle helper method to return the current value without bumping the cycle. #417 [Ken Collins] * Allow polymorphic_url helper to take url options. #880 [Tarmo Tänav] diff --git a/actionpack/lib/action_controller/assertions/selector_assertions.rb b/actionpack/lib/action_controller/assertions/selector_assertions.rb index 9114894b1d..bcbb570e4b 100644 --- a/actionpack/lib/action_controller/assertions/selector_assertions.rb +++ b/actionpack/lib/action_controller/assertions/selector_assertions.rb @@ -396,54 +396,31 @@ module ActionController # # The same, but shorter. # assert_select "ol>li", 4 def assert_select_rjs(*args, &block) - rjs_type = nil - arg = args.shift + rjs_type = args.first.is_a?(Symbol) ? args.shift : nil + id = args.first.is_a?(String) ? args.shift : nil # If the first argument is a symbol, it's the type of RJS statement we're looking # for (update, replace, insertion, etc). Otherwise, we're looking for just about # any RJS statement. - if arg.is_a?(Symbol) - rjs_type = arg - + if rjs_type if rjs_type == :insert - arg = args.shift - position = arg - insertion = "insert_#{arg}".to_sym - raise ArgumentError, "Unknown RJS insertion type #{arg}" unless RJS_STATEMENTS[insertion] + position = args.shift + insertion = "insert_#{position}".to_sym + raise ArgumentError, "Unknown RJS insertion type #{position}" unless RJS_STATEMENTS[insertion] statement = "(#{RJS_STATEMENTS[insertion]})" else raise ArgumentError, "Unknown RJS statement type #{rjs_type}" unless RJS_STATEMENTS[rjs_type] statement = "(#{RJS_STATEMENTS[rjs_type]})" end - arg = args.shift else statement = "#{RJS_STATEMENTS[:any]}" end - position ||= Regexp.new(RJS_INSERTIONS.join('|')) # Next argument we're looking for is the element identifier. If missing, we pick - # any element. - if arg.is_a?(String) - id = Regexp.quote(arg) - arg = args.shift - else - id = "[^\"]*" - end - - pattern = - case rjs_type - when :chained_replace, :chained_replace_html - Regexp.new("\\$\\(\"#{id}\"\\)#{statement}\\(#{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE) - when :remove, :show, :hide, :toggle - Regexp.new("#{statement}\\(\"#{id}\"\\)") - when :replace, :replace_html - Regexp.new("#{statement}\\(\"#{id}\", #{RJS_PATTERN_HTML}\\)") - when :insert, :insert_html - Regexp.new("Element.insert\\(\\\"#{id}\\\", \\{ #{position}: #{RJS_PATTERN_HTML} \\}\\);") - else - Regexp.union(Regexp.new("#{statement}\\(\"#{id}\", #{RJS_PATTERN_HTML}\\)"), - Regexp.new("Element.insert\\(\\\"#{id}\\\", \\{ #{position}: #{RJS_PATTERN_HTML} \\}\\);")) - end + # any element, otherwise we replace it in the statement. + pattern = Regexp.new( + id ? statement.gsub(RJS_ANY_ID, "\"#{id}\"") : statement + ) # Duplicate the body since the next step involves destroying it. matches = nil @@ -472,7 +449,13 @@ module ActionController matches else # RJS statement not found. - flunk args.shift || "No RJS statement that replaces or inserts HTML content." + case rjs_type + when :remove, :show, :hide, :toggle + flunk_message = "No RJS statement that #{rjs_type.to_s}s '#{id}' was rendered." + else + flunk_message = "No RJS statement that replaces or inserts HTML content." + end + flunk args.shift || flunk_message end end @@ -582,26 +565,23 @@ module ActionController protected unless const_defined?(:RJS_STATEMENTS) - RJS_STATEMENTS = { - :replace => /Element\.replace/, - :replace_html => /Element\.update/, - :chained_replace => /\.replace/, - :chained_replace_html => /\.update/, - :remove => /Element\.remove/, - :show => /Element\.show/, - :hide => /Element\.hide/, - :toggle => /Element\.toggle/ + RJS_PATTERN_HTML = "\"((\\\\\"|[^\"])*)\"" + RJS_ANY_ID = "\"([^\"])*\"" + RJS_STATEMENTS = { + :chained_replace => "\\$\\(#{RJS_ANY_ID}\\)\\.replace\\(#{RJS_PATTERN_HTML}\\)", + :chained_replace_html => "\\$\\(#{RJS_ANY_ID}\\)\\.update\\(#{RJS_PATTERN_HTML}\\)", + :replace_html => "Element\\.update\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)", + :replace => "Element\\.replace\\(#{RJS_ANY_ID}, #{RJS_PATTERN_HTML}\\)" } - RJS_STATEMENTS[:any] = Regexp.new("(#{RJS_STATEMENTS.values.join('|')})") - RJS_PATTERN_HTML = /"((\\"|[^"])*)"/ - RJS_INSERTIONS = [:top, :bottom, :before, :after] + [:remove, :show, :hide, :toggle].each do |action| + RJS_STATEMENTS[action] = "Element\\.#{action}\\(#{RJS_ANY_ID}\\)" + end + RJS_INSERTIONS = ["top", "bottom", "before", "after"] RJS_INSERTIONS.each do |insertion| - RJS_STATEMENTS["insert_#{insertion}".to_sym] = /Element.insert\(\"([^\"]*)\", \{ #{insertion.to_s.downcase}: #{RJS_PATTERN_HTML} \}\);/ + RJS_STATEMENTS["insert_#{insertion}".to_sym] = "Element.insert\\(#{RJS_ANY_ID}, \\{ #{insertion}: #{RJS_PATTERN_HTML} \\}\\)" end - RJS_STATEMENTS[:insert_html] = Regexp.new(RJS_INSERTIONS.collect do |insertion| - /Element.insert\(\"([^\"]*)\", \{ #{insertion.to_s.downcase}: #{RJS_PATTERN_HTML} \}\);/ - end.join('|')) - RJS_PATTERN_EVERYTHING = Regexp.new("#{RJS_STATEMENTS[:any]}\\(\"([^\"]*)\", #{RJS_PATTERN_HTML}\\)", Regexp::MULTILINE) + RJS_STATEMENTS[:insert_html] = "Element.insert\\(#{RJS_ANY_ID}, \\{ (#{RJS_INSERTIONS.join('|')}): #{RJS_PATTERN_HTML} \\}\\)" + RJS_STATEMENTS[:any] = Regexp.new("(#{RJS_STATEMENTS.values.join('|')})") RJS_PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/ end @@ -615,8 +595,8 @@ module ActionController root = HTML::Node.new(nil) while true - next if body.sub!(RJS_PATTERN_EVERYTHING) do |match| - html = unescape_rjs($3) + next if body.sub!(RJS_STATEMENTS[:any]) do |match| + html = unescape_rjs(match) matches = HTML::Document.new(html).root.children.select { |n| n.tag? } root.children.concat matches "" diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 55e1d48949..670a049497 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -260,10 +260,11 @@ module ActionController #:nodoc: include StatusCodes + cattr_reader :protected_instance_variables # Controller specific instance variables which will not be accessible inside views. - @@protected_view_variables = %w(@assigns @performed_redirect @performed_render @variables_added @request_origin @url @parent_controller - @action_name @before_filter_chain_aborted @action_cache_path @_session @_cookies @_headers @_params - @_flash @_response) + @@protected_instance_variables = %w(@assigns @performed_redirect @performed_render @variables_added @request_origin @url @parent_controller + @action_name @before_filter_chain_aborted @action_cache_path @_session @_cookies @_headers @_params + @_flash @_response) # Prepends all the URL-generating helpers from AssetHelper. This makes it possible to easily move javascripts, stylesheets, # and images to a dedicated asset server away from the main web server. Example: @@ -393,16 +394,9 @@ module ActionController #:nodoc: # directive. Values should always be specified as strings. attr_internal :headers - # Holds the hash of variables that are passed on to the template class to be made available to the view. This hash - # is generated by taking a snapshot of all the instance variables in the current scope just before a template is rendered. - attr_accessor :assigns - # Returns the name of the action this controller is processing. attr_accessor :action_name - # Templates that are exempt from layouts - @@exempt_from_layout = Set.new([/\.rjs$/]) - class << self # Factory for the standard create, process loop where the controller is discarded after processing. def process(request, response) #:nodoc: @@ -520,13 +514,7 @@ module ActionController #:nodoc: protected :filter_parameters end - # Don't render layouts for templates with the given extensions. - def exempt_from_layout(*extensions) - regexps = extensions.collect do |extension| - extension.is_a?(Regexp) ? extension : /\.#{Regexp.escape(extension.to_s)}$/ - end - @@exempt_from_layout.merge regexps - end + delegate :exempt_from_layout, :to => 'ActionView::Base' end public @@ -538,7 +526,6 @@ module ActionController #:nodoc: assign_shortcuts(request, response) initialize_current_url assign_names - forget_variables_added_to_assigns log_processing @@ -548,12 +535,16 @@ module ActionController #:nodoc: @@guard.synchronize { send(method, *arguments) } end - response.prepare! unless component_request? - response + send_response ensure process_cleanup end + def send_response + response.prepare! unless component_request? + response + end + # Returns a URL that has been rewritten according to the options hash and the defined Routes. # (For doing a complete redirect, use redirect_to). # @@ -859,7 +850,7 @@ module ActionController #:nodoc: raise DoubleRenderError, "Can only render or redirect once per action" if performed? if options.nil? - return render_for_file(default_template_name, nil, true) + return render(:file => default_template_name, :layout => true) elsif !extra_options.is_a?(Hash) raise RenderError, "You called render with invalid options : #{options.inspect}, #{extra_options.inspect}" else @@ -870,6 +861,9 @@ module ActionController #:nodoc: end end + response.layout = layout = pick_layout(options) + logger.info("Rendering template within #{layout}") if logger && layout + if content_type = options[:content_type] response.content_type = content_type.to_s end @@ -879,26 +873,21 @@ module ActionController #:nodoc: end if options.has_key?(:text) - render_for_text(options[:text], options[:status]) + text = layout ? @template.render(options.merge(:text => options[:text], :layout => layout)) : options[:text] + render_for_text(text, options[:status]) else if file = options[:file] - render_for_file(file, options[:status], nil, options[:locals] || {}) + render_for_file(file, options[:status], layout, options[:locals] || {}) elsif template = options[:template] - render_for_file(template, options[:status], true, options[:locals] || {}) + render_for_file(template, options[:status], layout, options[:locals] || {}) elsif inline = options[:inline] - add_variables_to_assigns - render_for_text(@template.render(options), options[:status]) + render_for_text(@template.render(options.merge(:layout => layout)), options[:status]) elsif action_name = options[:action] - template = default_template_name(action_name.to_s) - if options[:layout] && !template_exempt_from_layout?(template) - render_with_a_layout(:file => template, :status => options[:status], :layout => true) - else - render_with_no_layout(:file => template, :status => options[:status]) - end + render_for_file(default_template_name(action_name.to_s), options[:status], layout) elsif xml = options[:xml] response.content_type ||= Mime::XML @@ -912,12 +901,14 @@ module ActionController #:nodoc: elsif options[:partial] options[:partial] = default_template_name if options[:partial] == true - add_variables_to_assigns - render_for_text(@template.render(options), options[:status]) + if layout + render_for_text(@template.render(:text => @template.render(options), :layout => layout), options[:status]) + else + render_for_text(@template.render(options), options[:status]) + end elsif options[:update] - add_variables_to_assigns - @template.send! :evaluate_assigns + @template.send(:_evaluate_assigns_and_ivars) generator = ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.new(@template, &block) response.content_type = Mime::JS @@ -927,7 +918,7 @@ module ActionController #:nodoc: render_for_text(nil, options[:status]) else - render_for_file(default_template_name, options[:status], true) + render_for_file(default_template_name, options[:status], layout) end end end @@ -938,7 +929,6 @@ module ActionController #:nodoc: render(options, &block) ensure erase_render_results - forget_variables_added_to_assigns reset_variables_added_to_assigns end @@ -1123,10 +1113,9 @@ module ActionController #:nodoc: private - def render_for_file(template_path, status = nil, use_full_path = nil, locals = {}) #:nodoc: - add_variables_to_assigns + def render_for_file(template_path, status = nil, layout = nil, locals = {}) #:nodoc: logger.info("Rendering #{template_path}" + (status ? " (#{status})" : '')) if logger - render_for_text(@template.render(:file => template_path, :locals => locals), status) + render_for_text @template.render(:file => template_path, :locals => locals, :layout => layout), status end def render_for_text(text = nil, status = nil, append_response = false) #:nodoc: @@ -1161,7 +1150,6 @@ module ActionController #:nodoc: @_session = @_response.session @template = @_response.template - @assigns = @_response.template.assigns @_headers = @_response.headers end @@ -1225,27 +1213,10 @@ module ActionController #:nodoc: hidden_actions end - def add_variables_to_assigns - unless @variables_added - add_instance_variables_to_assigns - @variables_added = true - end - end - - def forget_variables_added_to_assigns - @variables_added = nil - end - def reset_variables_added_to_assigns @template.instance_variable_set("@assigns_added", nil) end - def add_instance_variables_to_assigns - (instance_variable_names - @@protected_view_variables).each do |var| - @assigns[var[1..-1]] = instance_variable_get(var) - end - end - def request_origin # this *needs* to be cached! # otherwise you'd get different results if calling it more than once @@ -1261,12 +1232,7 @@ module ActionController #:nodoc: end def template_exists?(template_name = default_template_name) - @template.file_exists?(template_name) - end - - def template_exempt_from_layout?(template_name = default_template_name) - template_name = @template.pick_template(template_name).to_s if @template - @@exempt_from_layout.any? { |ext| template_name =~ ext } + @template.send(:_pick_template, template_name) ? true : false rescue ActionView::MissingTemplate false end diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb index b27ec486c0..7c803a9830 100644 --- a/actionpack/lib/action_controller/caching/actions.rb +++ b/actionpack/lib/action_controller/caching/actions.rb @@ -90,7 +90,7 @@ module ActionController #:nodoc: set_content_type!(controller, cache_path.extension) options = { :text => cache } options.merge!(:layout => true) if cache_layout? - controller.send!(:render, options) + controller.__send__(:render, options) false else controller.action_cache_path = cache_path @@ -121,7 +121,7 @@ module ActionController #:nodoc: end def content_for_layout(controller) - controller.response.layout && controller.response.template.instance_variable_get('@content_for_layout') + controller.response.layout && controller.response.template.instance_variable_get('@cached_content_for_layout') end end diff --git a/actionpack/lib/action_controller/caching/sweeping.rb b/actionpack/lib/action_controller/caching/sweeping.rb index 61559e9ec7..c7992d7769 100644 --- a/actionpack/lib/action_controller/caching/sweeping.rb +++ b/actionpack/lib/action_controller/caching/sweeping.rb @@ -83,13 +83,13 @@ module ActionController #:nodoc: controller_callback_method_name = "#{timing}_#{controller.controller_name.underscore}" action_callback_method_name = "#{controller_callback_method_name}_#{controller.action_name}" - send!(controller_callback_method_name) if respond_to?(controller_callback_method_name, true) - send!(action_callback_method_name) if respond_to?(action_callback_method_name, true) + __send__(controller_callback_method_name) if respond_to?(controller_callback_method_name, true) + __send__(action_callback_method_name) if respond_to?(action_callback_method_name, true) end def method_missing(method, *arguments) return if @controller.nil? - @controller.send!(method, *arguments) + @controller.__send__(method, *arguments) end end end diff --git a/actionpack/lib/action_controller/cgi_process.rb b/actionpack/lib/action_controller/cgi_process.rb index 0ca27b30db..d381af1b84 100644 --- a/actionpack/lib/action_controller/cgi_process.rb +++ b/actionpack/lib/action_controller/cgi_process.rb @@ -48,7 +48,7 @@ module ActionController #:nodoc: def initialize(cgi, session_options = {}) @cgi = cgi @session_options = session_options - @env = @cgi.send!(:env_table) + @env = @cgi.__send__(:env_table) super() end @@ -107,7 +107,7 @@ module ActionController #:nodoc: end def method_missing(method_id, *arguments) - @cgi.send!(method_id, *arguments) rescue super + @cgi.__send__(method_id, *arguments) rescue super end private @@ -164,7 +164,7 @@ end_msg begin output.write(@cgi.header(@headers)) - if @cgi.send!(:env_table)['REQUEST_METHOD'] == 'HEAD' + if @cgi.__send__(:env_table)['REQUEST_METHOD'] == 'HEAD' return elsif @body.respond_to?(:call) # Flush the output now in case the @body Proc uses diff --git a/actionpack/lib/action_controller/components.rb b/actionpack/lib/action_controller/components.rb index 8275bd380a..f446b91e7e 100644 --- a/actionpack/lib/action_controller/components.rb +++ b/actionpack/lib/action_controller/components.rb @@ -38,6 +38,7 @@ module ActionController #:nodoc: def self.included(base) #:nodoc: base.class_eval do include InstanceMethods + include ActiveSupport::Deprecation extend ClassMethods helper HelperMethods @@ -64,7 +65,7 @@ module ActionController #:nodoc: module HelperMethods def render_component(options) - @controller.send!(:render_component_as_string, options) + @controller.__send__(:render_component_as_string, options) end end @@ -82,6 +83,7 @@ module ActionController #:nodoc: render_for_text(component_response(options, true).body, response.headers["Status"]) end end + deprecate :render_component => "Please install render_component plugin from http://github.com/rails/render_component/tree/master" # Returns the component response as a string def render_component_as_string(options) #:doc: @@ -95,6 +97,7 @@ module ActionController #:nodoc: end end end + deprecate :render_component_as_string => "Please install render_component plugin from http://github.com/rails/render_component/tree/master" def flash_with_components(refresh = false) #:nodoc: if !defined?(@_flash) || refresh diff --git a/actionpack/lib/action_controller/filters.rb b/actionpack/lib/action_controller/filters.rb index 1d7236f18a..9022b8b279 100644 --- a/actionpack/lib/action_controller/filters.rb +++ b/actionpack/lib/action_controller/filters.rb @@ -199,8 +199,8 @@ module ActionController #:nodoc: Proc.new do |controller, action| method.before(controller) - if controller.send!(:performed?) - controller.send!(:halt_filter_chain, method, :rendered_or_redirected) + if controller.__send__(:performed?) + controller.__send__(:halt_filter_chain, method, :rendered_or_redirected) else begin action.call @@ -223,8 +223,8 @@ module ActionController #:nodoc: def call(controller, &block) super - if controller.send!(:performed?) - controller.send!(:halt_filter_chain, method, :rendered_or_redirected) + if controller.__send__(:performed?) + controller.__send__(:halt_filter_chain, method, :rendered_or_redirected) end end end diff --git a/actionpack/lib/action_controller/helpers.rb b/actionpack/lib/action_controller/helpers.rb index ce5e8be54c..9cffa07b26 100644 --- a/actionpack/lib/action_controller/helpers.rb +++ b/actionpack/lib/action_controller/helpers.rb @@ -204,8 +204,8 @@ module ActionController #:nodoc: begin child.master_helper_module = Module.new - child.master_helper_module.send! :include, master_helper_module - child.send! :default_helper_module! + child.master_helper_module.__send__ :include, master_helper_module + child.__send__ :default_helper_module! rescue MissingSourceFile => e raise unless e.is_missing?("helpers/#{child.controller_path}_helper") end diff --git a/actionpack/lib/action_controller/http_authentication.rb b/actionpack/lib/action_controller/http_authentication.rb index 31db012ef2..2ed810db7d 100644 --- a/actionpack/lib/action_controller/http_authentication.rb +++ b/actionpack/lib/action_controller/http_authentication.rb @@ -117,7 +117,7 @@ module ActionController def authentication_request(controller, realm) controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}") - controller.send! :render, :text => "HTTP Basic: Access denied.\n", :status => :unauthorized + controller.__send__ :render, :text => "HTTP Basic: Access denied.\n", :status => :unauthorized end end end diff --git a/actionpack/lib/action_controller/integration.rb b/actionpack/lib/action_controller/integration.rb index 198a22e8dc..a98c1af7f9 100644 --- a/actionpack/lib/action_controller/integration.rb +++ b/actionpack/lib/action_controller/integration.rb @@ -444,7 +444,7 @@ EOF reset! unless @integration_session # reset the html_document variable, but only for new get/post calls @html_document = nil unless %w(cookies assigns).include?(method) - returning @integration_session.send!(method, *args) do + returning @integration_session.__send__(method, *args) do copy_session_variables! end end @@ -469,12 +469,12 @@ EOF self.class.fixture_table_names.each do |table_name| name = table_name.tr(".", "_") next unless respond_to?(name) - extras.send!(:define_method, name) { |*args| delegate.send(name, *args) } + extras.__send__(:define_method, name) { |*args| delegate.send(name, *args) } end end # delegate add_assertion to the test case - extras.send!(:define_method, :add_assertion) { test_result.add_assertion } + extras.__send__(:define_method, :add_assertion) { test_result.add_assertion } session.extend(extras) session.delegate = self session.test_result = @_result @@ -488,7 +488,7 @@ EOF def copy_session_variables! #:nodoc: return unless @integration_session %w(controller response request).each do |var| - instance_variable_set("@#{var}", @integration_session.send!(var)) + instance_variable_set("@#{var}", @integration_session.__send__(var)) end end diff --git a/actionpack/lib/action_controller/layout.rb b/actionpack/lib/action_controller/layout.rb index 8b6febe254..3631ce86af 100644 --- a/actionpack/lib/action_controller/layout.rb +++ b/actionpack/lib/action_controller/layout.rb @@ -3,11 +3,6 @@ module ActionController #:nodoc: def self.included(base) base.extend(ClassMethods) base.class_eval do - # NOTE: Can't use alias_method_chain here because +render_without_layout+ is already - # defined as a publicly exposed method - alias_method :render_with_no_layout, :render - alias_method :render, :render_with_a_layout - class << self alias_method_chain :inherited, :layout end @@ -169,17 +164,17 @@ module ActionController #:nodoc: # performance and have access to them as any normal template would. def layout(template_name, conditions = {}, auto = false) add_layout_conditions(conditions) - write_inheritable_attribute "layout", template_name - write_inheritable_attribute "auto_layout", auto + write_inheritable_attribute(:layout, template_name) + write_inheritable_attribute(:auto_layout, auto) end def layout_conditions #:nodoc: - @layout_conditions ||= read_inheritable_attribute("layout_conditions") + @layout_conditions ||= read_inheritable_attribute(:layout_conditions) end def default_layout(format) #:nodoc: - layout = read_inheritable_attribute("layout") - return layout unless read_inheritable_attribute("auto_layout") + layout = read_inheritable_attribute(:layout) + return layout unless read_inheritable_attribute(:auto_layout) @default_layout ||= {} @default_layout[format] ||= default_layout_with_format(format, layout) @default_layout[format] @@ -199,7 +194,7 @@ module ActionController #:nodoc: end def add_layout_conditions(conditions) - write_inheritable_hash "layout_conditions", normalize_conditions(conditions) + write_inheritable_hash(:layout_conditions, normalize_conditions(conditions)) end def normalize_conditions(conditions) @@ -221,10 +216,10 @@ module ActionController #:nodoc: # object). If the layout was defined without a directory, layouts is assumed. So <tt>layout "weblog/standard"</tt> will return # weblog/standard, but <tt>layout "standard"</tt> will return layouts/standard. def active_layout(passed_layout = nil) - layout = passed_layout || self.class.default_layout(response.template.template_format) + layout = passed_layout || self.class.default_layout(default_template_format) active_layout = case layout when String then layout - when Symbol then send!(layout) + when Symbol then __send__(layout) when Proc then layout.call(self) end @@ -240,51 +235,24 @@ module ActionController #:nodoc: end end - protected - def render_with_a_layout(options = nil, extra_options = {}, &block) #:nodoc: - template_with_options = options.is_a?(Hash) - - if (layout = pick_layout(template_with_options, options)) && apply_layout?(template_with_options, options) - options = options.merge :layout => false if template_with_options - logger.info("Rendering template within #{layout}") if logger - - content_for_layout = render_with_no_layout(options, extra_options, &block) - erase_render_results - add_variables_to_assigns - @template.instance_variable_set("@content_for_layout", content_for_layout) - response.layout = layout - status = template_with_options ? options[:status] : nil - render_for_text(@template.render(layout), status) - else - render_with_no_layout(options, extra_options, &block) - end - end - - private - def apply_layout?(template_with_options, options) - return false if options == :update - template_with_options ? candidate_for_layout?(options) : !template_exempt_from_layout? - end - def candidate_for_layout?(options) - (options.has_key?(:layout) && options[:layout] != false) || - options.values_at(:text, :xml, :json, :file, :inline, :partial, :nothing).compact.empty? && - !template_exempt_from_layout?(options[:template] || default_template_name(options[:action])) + options.values_at(:text, :xml, :json, :file, :inline, :partial, :nothing, :update).compact.empty? && + !@template.__send__(:_exempt_from_layout?, options[:template] || default_template_name(options[:action])) end - def pick_layout(template_with_options, options) - if template_with_options - case layout = options[:layout] - when FalseClass - nil - when NilClass, TrueClass - active_layout if action_has_layout? - else - active_layout(layout) + def pick_layout(options) + if options.has_key?(:layout) + case layout = options.delete(:layout) + when FalseClass + nil + when NilClass, TrueClass + active_layout if action_has_layout? && !@template.__send__(:_exempt_from_layout?, default_template_name) + else + active_layout(layout) end else - active_layout if action_has_layout? + active_layout if action_has_layout? && candidate_for_layout?(options) end end @@ -304,7 +272,13 @@ module ActionController #:nodoc: end def layout_directory?(layout_name) - @template.file_exists?("#{File.join('layouts', layout_name)}.#{@template.template_format}") + @template.__send__(:_pick_template, "#{File.join('layouts', layout_name)}.#{@template.template_format}") ? true : false + rescue ActionView::MissingTemplate + false + end + + def default_template_format + response.template.template_format end end end diff --git a/actionpack/lib/action_controller/polymorphic_routes.rb b/actionpack/lib/action_controller/polymorphic_routes.rb index 30564c7bb3..cc228c4230 100644 --- a/actionpack/lib/action_controller/polymorphic_routes.rb +++ b/actionpack/lib/action_controller/polymorphic_routes.rb @@ -108,7 +108,7 @@ module ActionController args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options end - send!(named_route, *args) + __send__(named_route, *args) end # Returns the path component of a URL for the given record. It uses @@ -149,7 +149,7 @@ module ActionController if parent.is_a?(Symbol) || parent.is_a?(String) string << "#{parent}_" else - string << "#{RecordIdentifier.send!("singular_class_name", parent)}_" + string << "#{RecordIdentifier.__send__("singular_class_name", parent)}_" end end end @@ -157,7 +157,7 @@ module ActionController if record.is_a?(Symbol) || record.is_a?(String) route << "#{record}_" else - route << "#{RecordIdentifier.send!("#{inflection}_class_name", record)}_" + route << "#{RecordIdentifier.__send__("#{inflection}_class_name", record)}_" end action_prefix(options) + namespace + route + routing_type(options).to_s diff --git a/actionpack/lib/action_controller/rescue.rb b/actionpack/lib/action_controller/rescue.rb index b12d50c773..83c4218af4 100644 --- a/actionpack/lib/action_controller/rescue.rb +++ b/actionpack/lib/action_controller/rescue.rb @@ -177,11 +177,8 @@ module ActionController #:nodoc: # Render detailed diagnostics for unhandled exceptions rescued from # a controller action. def rescue_action_locally(exception) - add_variables_to_assigns @template.instance_variable_set("@exception", exception) @template.instance_variable_set("@rescues_path", File.dirname(rescues_path("stub"))) - @template.send!(:assign_variables_from_controller) - @template.instance_variable_set("@contents", @template.render(:file => template_path_for_local_rescue(exception))) response.content_type = Mime::HTML diff --git a/actionpack/lib/action_controller/resources.rb b/actionpack/lib/action_controller/resources.rb index becf6b0b63..872b0dab3d 100644 --- a/actionpack/lib/action_controller/resources.rb +++ b/actionpack/lib/action_controller/resources.rb @@ -85,16 +85,24 @@ module ActionController @new_path ||= "#{path}/#{new_action}" end + def shallow_path_prefix + @shallow_path_prefix ||= "#{path_prefix unless @options[:shallow]}" + end + def member_path - @member_path ||= "#{path}/:id" + @member_path ||= "#{shallow_path_prefix}/#{path_segment}/:id" end def nesting_path_prefix - @nesting_path_prefix ||= "#{path}/:#{singular}_id" + @nesting_path_prefix ||= "#{shallow_path_prefix}/#{path_segment}/:#{singular}_id" + end + + def shallow_name_prefix + @shallow_name_prefix ||= "#{name_prefix unless @options[:shallow]}" end def nesting_name_prefix - "#{name_prefix}#{singular}_" + "#{shallow_name_prefix}#{singular}_" end def action_separator @@ -141,6 +149,8 @@ module ActionController super end + alias_method :shallow_path_prefix, :path_prefix + alias_method :shallow_name_prefix, :name_prefix alias_method :member_path, :path alias_method :nesting_path_prefix, :path end @@ -238,8 +248,9 @@ module ActionController # # The +resources+ method accepts the following options to customize the resulting routes: # * <tt>:collection</tt> - Add named routes for other actions that operate on the collection. - # Takes a hash of <tt>#{action} => #{method}</tt>, where method is <tt>:get</tt>/<tt>:post</tt>/<tt>:put</tt>/<tt>:delete</tt> - # or <tt>:any</tt> if the method does not matter. These routes map to a URL like /messages/rss, with a route of +rss_messages_url+. + # Takes a hash of <tt>#{action} => #{method}</tt>, where method is <tt>:get</tt>/<tt>:post</tt>/<tt>:put</tt>/<tt>:delete</tt>, + # an array of any of the previous, or <tt>:any</tt> if the method does not matter. + # These routes map to a URL like /messages/rss, with a route of +rss_messages_url+. # * <tt>:member</tt> - Same as <tt>:collection</tt>, but for actions that operate on a specific member. # * <tt>:new</tt> - Same as <tt>:collection</tt>, but for actions that operate on the new \resource action. # * <tt>:controller</tt> - Specify the controller name for the routes. @@ -317,7 +328,32 @@ module ActionController # comments_url(@article) # comment_url(@article, @comment) # - # If <tt>map.resources</tt> is called with multiple \resources, they all get the same options applied. + # * <tt>:shallow</tt> - If true, paths for nested resources which reference a specific member + # (ie. those with an :id parameter) will not use the parent path prefix or name prefix. + # + # The <tt>:shallow</tt> option is inherited by any nested resource(s). + # + # For example, 'users', 'posts' and 'comments' all use shallow paths with the following nested resources: + # + # map.resources :users, :shallow => true do |user| + # user.resources :posts do |post| + # post.resources :comments + # end + # end + # # --> GET /users/1/posts (maps to the PostsController#index action as usual) + # # also adds the usual named route called "user_posts" + # # --> GET /posts/2 (maps to the PostsController#show action as if it were not nested) + # # also adds the named route called "post" + # # --> GET /posts/2/comments (maps to the CommentsController#index action) + # # also adds the named route called "post_comments" + # # --> GET /comments/2 (maps to the CommentsController#show action as if it were not nested) + # # also adds the named route called "comment" + # + # You may also use <tt>:shallow</tt> in combination with the +has_one+ and +has_many+ shorthand notations like: + # + # map.resources :users, :has_many => { :posts => :comments }, :shallow => true + # + # If <tt>map.resources</tt> is called with multiple resources, they all get the same options applied. # # Examples: # @@ -442,7 +478,7 @@ module ActionController map_associations(resource, options) if block_given? - with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], &block) + with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], &block) end end end @@ -459,29 +495,45 @@ module ActionController map_associations(resource, options) if block_given? - with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], &block) + with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], &block) end end end def map_associations(resource, options) + map_has_many_associations(resource, options.delete(:has_many), options) if options[:has_many] + path_prefix = "#{options.delete(:path_prefix)}#{resource.nesting_path_prefix}" name_prefix = "#{options.delete(:name_prefix)}#{resource.nesting_name_prefix}" - Array(options[:has_many]).each do |association| - resources(association, :path_prefix => path_prefix, :name_prefix => name_prefix, :namespace => options[:namespace]) + Array(options[:has_one]).each do |association| + resource(association, :path_prefix => path_prefix, :name_prefix => name_prefix, :namespace => options[:namespace], :shallow => options[:shallow]) end + end - Array(options[:has_one]).each do |association| - resource(association, :path_prefix => path_prefix, :name_prefix => name_prefix, :namespace => options[:namespace]) + def map_has_many_associations(resource, associations, options) + case associations + when Hash + associations.each do |association,has_many| + map_has_many_associations(resource, association, options.merge(:has_many => has_many)) + end + when Array + associations.each do |association| + map_has_many_associations(resource, association, options) + end + when Symbol, String + resources(associations, :path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], :has_many => options[:has_many]) + else end end def map_collection_actions(map, resource) resource.collection_methods.each do |method, actions| actions.each do |action| - action_options = action_options_for(action, resource, method) - map_named_routes(map, "#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{action}", action_options) + [method].flatten.each do |m| + action_options = action_options_for(action, resource, m) + map_named_routes(map, "#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{action}", action_options) + end end end end @@ -521,17 +573,19 @@ module ActionController def map_member_actions(map, resource) resource.member_methods.each do |method, actions| actions.each do |action| - action_options = action_options_for(action, resource, method) + [method].flatten.each do |m| + action_options = action_options_for(action, resource, m) - action_path = resource.options[:path_names][action] if resource.options[:path_names].is_a?(Hash) - action_path ||= Base.resources_path_names[action] || action + action_path = resource.options[:path_names][action] if resource.options[:path_names].is_a?(Hash) + action_path ||= Base.resources_path_names[action] || action - map_named_routes(map, "#{action}_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{action_path}", action_options) + map_named_routes(map, "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{action_path}", action_options) + end end end show_action_options = action_options_for("show", resource) - map_named_routes(map, "#{resource.name_prefix}#{resource.singular}", resource.member_path, show_action_options) + map_named_routes(map, "#{resource.shallow_name_prefix}#{resource.singular}", resource.member_path, show_action_options) update_action_options = action_options_for("update", resource) map_unnamed_routes(map, resource.member_path, update_action_options) @@ -574,4 +628,4 @@ end class ActionController::Routing::RouteSet::Mapper include ActionController::Resources -end
\ No newline at end of file +end diff --git a/actionpack/lib/action_controller/response.rb b/actionpack/lib/action_controller/response.rb index 5dac4128bb..54a99996ef 100644 --- a/actionpack/lib/action_controller/response.rb +++ b/actionpack/lib/action_controller/response.rb @@ -129,8 +129,8 @@ module ActionController # :nodoc: def prepare! assign_default_content_type_and_charset! - set_content_length! handle_conditional_get! + set_content_length! convert_content_type! end diff --git a/actionpack/lib/action_controller/routing/builder.rb b/actionpack/lib/action_controller/routing/builder.rb index 03427e41de..5704d9d01a 100644 --- a/actionpack/lib/action_controller/routing/builder.rb +++ b/actionpack/lib/action_controller/routing/builder.rb @@ -187,12 +187,14 @@ module ActionController private def validate_route_conditions(conditions) if method = conditions[:method] - if method == :head - raise ArgumentError, "HTTP method HEAD is invalid in route conditions. Rails processes HEAD requests the same as GETs, returning just the response headers" - end + [method].flatten.each do |m| + if m == :head + raise ArgumentError, "HTTP method HEAD is invalid in route conditions. Rails processes HEAD requests the same as GETs, returning just the response headers" + end - unless HTTP_METHODS.include?(method.to_sym) - raise ArgumentError, "Invalid HTTP method specified in route conditions: #{conditions.inspect}" + unless HTTP_METHODS.include?(m.to_sym) + raise ArgumentError, "Invalid HTTP method specified in route conditions: #{conditions.inspect}" + end end end end diff --git a/actionpack/lib/action_controller/routing/optimisations.rb b/actionpack/lib/action_controller/routing/optimisations.rb index 0fe836606c..894d4109e4 100644 --- a/actionpack/lib/action_controller/routing/optimisations.rb +++ b/actionpack/lib/action_controller/routing/optimisations.rb @@ -103,9 +103,10 @@ module ActionController end # This case uses almost the same code as positional arguments, - # but add an args.last.to_query on the end + # but add a question mark and args.last.to_query on the end, + # unless the last arg is empty def generation_code - super.insert(-2, '?#{args.last.to_query}') + super.insert(-2, '#{\'?\' + args.last.to_query unless args.last.empty?}') end # To avoid generating "http://localhost/?host=foo.example.com" we diff --git a/actionpack/lib/action_controller/routing/route.rb b/actionpack/lib/action_controller/routing/route.rb index 2106ac09e0..3b2cb28545 100644 --- a/actionpack/lib/action_controller/routing/route.rb +++ b/actionpack/lib/action_controller/routing/route.rb @@ -201,7 +201,7 @@ module ActionController # recognition, not generation. def recognition_conditions result = ["(match = #{Regexp.new(recognition_pattern).inspect}.match(path))"] - result << "conditions[:method] === env[:method]" if conditions[:method] + result << "[conditions[:method]].flatten.include?(env[:method])" if conditions[:method] result end diff --git a/actionpack/lib/action_controller/routing/route_set.rb b/actionpack/lib/action_controller/routing/route_set.rb index 8dfc22f94f..9d48f289db 100644 --- a/actionpack/lib/action_controller/routing/route_set.rb +++ b/actionpack/lib/action_controller/routing/route_set.rb @@ -115,7 +115,7 @@ module ActionController def install(destinations = [ActionController::Base, ActionView::Base], regenerate = false) reset! if regenerate Array(destinations).each do |dest| - dest.send! :include, @module + dest.__send__(:include, @module) end end @@ -353,7 +353,7 @@ module ActionController if generate_all # Used by caching to expire all paths for a resource return routes.collect do |route| - route.send!(method, options, merged, expire_on) + route.__send__(method, options, merged, expire_on) end.compact end @@ -361,7 +361,7 @@ module ActionController routes = routes_by_controller[controller][action][options.keys.sort_by { |x| x.object_id }] routes.each do |route| - results = route.send!(method, options, merged, expire_on) + results = route.__send__(method, options, merged, expire_on) return results if results && (!results.is_a?(Array) || results.first) end end diff --git a/actionpack/lib/action_controller/routing/segments.rb b/actionpack/lib/action_controller/routing/segments.rb index 9d4b740a44..e5f174ae2c 100644 --- a/actionpack/lib/action_controller/routing/segments.rb +++ b/actionpack/lib/action_controller/routing/segments.rb @@ -160,7 +160,7 @@ module ActionController s << "\n#{expiry_statement}" end - def interpolation_chunk(value_code = "#{local_name}") + def interpolation_chunk(value_code = local_name) "\#{URI.escape(#{value_code}.to_s, ActionController::Routing::Segment::UNSAFE_PCHAR)}" end @@ -231,7 +231,7 @@ module ActionController end # Don't URI.escape the controller name since it may contain slashes. - def interpolation_chunk(value_code = "#{local_name}") + def interpolation_chunk(value_code = local_name) "\#{#{value_code}.to_s}" end @@ -251,7 +251,7 @@ module ActionController end class PathSegment < DynamicSegment #:nodoc: - def interpolation_chunk(value_code = "#{local_name}") + def interpolation_chunk(value_code = local_name) "\#{#{value_code}}" end diff --git a/actionpack/lib/action_controller/session_management.rb b/actionpack/lib/action_controller/session_management.rb index 80a3ddd2c5..f5a1155a46 100644 --- a/actionpack/lib/action_controller/session_management.rb +++ b/actionpack/lib/action_controller/session_management.rb @@ -86,14 +86,14 @@ module ActionController #:nodoc: raise ArgumentError, "only one of either :only or :except are allowed" end - write_inheritable_array("session_options", [options]) + write_inheritable_array(:session_options, [options]) end # So we can declare session options in the Rails initializer. alias_method :session=, :session def cached_session_options #:nodoc: - @session_options ||= read_inheritable_attribute("session_options") || [] + @session_options ||= read_inheritable_attribute(:session_options) || [] end def session_options_for(request, action) #:nodoc: diff --git a/actionpack/lib/action_controller/test_process.rb b/actionpack/lib/action_controller/test_process.rb index a11fa7cd10..cde1f2052b 100644 --- a/actionpack/lib/action_controller/test_process.rb +++ b/actionpack/lib/action_controller/test_process.rb @@ -3,6 +3,8 @@ require 'action_controller/test_case' module ActionController #:nodoc: class Base + attr_reader :assigns + # Process a test request called with a TestRequest object. def self.process_test(request) new.process_test(request) @@ -14,7 +16,12 @@ module ActionController #:nodoc: def process_with_test(*args) returning process_without_test(*args) do - add_variables_to_assigns + @assigns = {} + (instance_variable_names - @@protected_instance_variables).each do |var| + value = instance_variable_get(var) + @assigns[var[1..-1]] = value + response.template.assigns[var[1..-1]] = value if response + end end end @@ -211,7 +218,7 @@ module ActionController #:nodoc: # Returns the template of the file which was used to # render this response (or nil) def rendered_template - template._first_render + template.send(:_first_render) end # A shortcut to the flash. Returns an empty hash if no session flash exists. @@ -350,7 +357,7 @@ module ActionController #:nodoc: alias local_path path def method_missing(method_name, *args, &block) #:nodoc: - @tempfile.send!(method_name, *args, &block) + @tempfile.__send__(method_name, *args, &block) end end @@ -396,7 +403,7 @@ module ActionController #:nodoc: def xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil) @request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' @request.env['HTTP_ACCEPT'] = 'text/javascript, text/html, application/xml, text/xml, */*' - returning send!(request_method, action, parameters, session, flash) do + returning __send__(request_method, action, parameters, session, flash) do @request.env.delete 'HTTP_X_REQUESTED_WITH' @request.env.delete 'HTTP_ACCEPT' end @@ -429,7 +436,7 @@ module ActionController #:nodoc: def build_request_uri(action, parameters) unless @request.env['REQUEST_URI'] - options = @controller.send!(:rewrite_options, parameters) + options = @controller.__send__(:rewrite_options, parameters) options.update(:only_path => true, :action => action) url = ActionController::UrlRewriter.new(@request, parameters) diff --git a/actionpack/lib/action_controller/verification.rb b/actionpack/lib/action_controller/verification.rb index 35b12a7f13..7bf09ba6ea 100644 --- a/actionpack/lib/action_controller/verification.rb +++ b/actionpack/lib/action_controller/verification.rb @@ -80,7 +80,7 @@ module ActionController #:nodoc: # array (may also be a single value). def verify(options={}) before_filter :only => options[:only], :except => options[:except] do |c| - c.send! :verify_action, options + c.__send__ :verify_action, options end end end @@ -116,7 +116,7 @@ module ActionController #:nodoc: end def apply_redirect_to(redirect_to_option) # :nodoc: - (redirect_to_option.is_a?(Symbol) && redirect_to_option != :back) ? self.send!(redirect_to_option) : redirect_to_option + (redirect_to_option.is_a?(Symbol) && redirect_to_option != :back) ? self.__send__(redirect_to_option) : redirect_to_option end def apply_remaining_actions(options) # :nodoc: diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index c65048bfa0..6c4da9067d 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -162,7 +162,6 @@ module ActionView #:nodoc: attr_accessor :base_path, :assigns, :template_extension attr_accessor :controller - attr_accessor :_first_render, :_last_render attr_writer :template_format @@ -185,6 +184,17 @@ module ActionView #:nodoc: "deprecated and has no effect. Please remove it from your config files.", caller) end + # Templates that are exempt from layouts + @@exempt_from_layout = Set.new([/\.rjs$/]) + + # Don't render layouts for templates with the given extensions. + def self.exempt_from_layout(*extensions) + regexps = extensions.collect do |extension| + extension.is_a?(Regexp) ? extension : /\.#{Regexp.escape(extension.to_s)}$/ + end + @@exempt_from_layout.merge(regexps) + end + # Specify whether RJS responses should be wrapped in a try/catch block # that alert()s the caught exception (and then re-raises it). @@debug_rjs = false @@ -246,33 +256,20 @@ module ActionView #:nodoc: update_page(&block) elsif options.is_a?(Hash) options = options.reverse_merge(:locals => {}) - - if partial_layout = options.delete(:layout) - if block_given? - begin - @_proc_for_layout = block - concat(render(options.merge(:partial => partial_layout))) - ensure - @_proc_for_layout = nil - end - else - begin - original_content_for_layout, @content_for_layout = @content_for_layout, render(options) - render(options.merge(:partial => partial_layout)) - ensure - @content_for_layout = original_content_for_layout - end - end + if options[:layout] + _render_with_layout(options, local_assigns, &block) elsif options[:file] if options[:use_full_path] ActiveSupport::Deprecation.warn("use_full_path option has been deprecated and has no affect.", caller) end - pick_template(options[:file]).render_template(self, options[:locals]) + _pick_template(options[:file]).render_template(self, options[:locals]) elsif options[:partial] render_partial(options) elsif options[:inline] InlineTemplate.new(options[:inline], options[:type]).render(self, options[:locals]) + elsif options[:text] + options[:text] end end end @@ -290,74 +287,95 @@ module ActionView #:nodoc: end end - def file_exists?(template_path) - pick_template(template_path) ? true : false - rescue MissingTemplate - false - end + private + attr_accessor :_first_render, :_last_render - # Gets the extension for an existing template with the given template_path. - # Returns the format with the extension if that template exists. - # - # pick_template('users/show') - # # => 'users/show.html.erb' - # - # pick_template('users/legacy') - # # => 'users/legacy.rhtml' - # - def pick_template(template_path) - return template_path if template_path.respond_to?(:render) - - path = template_path.sub(/^\//, '') - if m = path.match(/(.*)\.(\w+)$/) - template_file_name, template_file_extension = m[1], m[2] - else - template_file_name = path - end + # Evaluate the local assigns and pushes them to the view. + def _evaluate_assigns_and_ivars #:nodoc: + unless @assigns_added + @assigns.each { |key, value| instance_variable_set("@#{key}", value) } - # OPTIMIZE: Checks to lookup template in view path - if template = self.view_paths["#{template_file_name}.#{template_format}"] - template - elsif template = self.view_paths[template_file_name] - template - elsif _first_render && template = self.view_paths["#{template_file_name}.#{_first_render.format_and_extension}"] - template - elsif template_format == :js && template = self.view_paths["#{template_file_name}.html"] - @template_format = :html - template - else - template = Template.new(template_path, view_paths) - - if self.class.warn_cache_misses && logger - logger.debug "[PERFORMANCE] Rendering a template that was " + - "not found in view path. Templates outside the view path are " + - "not cached and result in expensive disk operations. Move this " + - "file into #{view_paths.join(':')} or add the folder to your " + - "view path list" + if @controller + variables = @controller.instance_variables + variables -= @controller.protected_instance_variables if @controller.respond_to?(:protected_instance_variables) + variables.each {|name| instance_variable_set(name, @controller.instance_variable_get(name)) } + end + + @assigns_added = true end + end - template + def _set_controller_content_type(content_type) #:nodoc: + if controller.respond_to?(:response) + controller.response.content_type ||= content_type + end end - end - memoize :pick_template - private - # Evaluate the local assigns and pushes them to the view. - def evaluate_assigns - unless @assigns_added - assign_variables_from_controller - @assigns_added = true + def _pick_template(template_path) + return template_path if template_path.respond_to?(:render) + + path = template_path.sub(/^\//, '') + if m = path.match(/(.*)\.(\w+)$/) + template_file_name, template_file_extension = m[1], m[2] + else + template_file_name = path + end + + # OPTIMIZE: Checks to lookup template in view path + if template = self.view_paths["#{template_file_name}.#{template_format}"] + template + elsif template = self.view_paths[template_file_name] + template + elsif _first_render && template = self.view_paths["#{template_file_name}.#{_first_render.format_and_extension}"] + template + elsif template_format == :js && template = self.view_paths["#{template_file_name}.html"] + @template_format = :html + template + else + template = Template.new(template_path, view_paths) + + if self.class.warn_cache_misses && logger + logger.debug "[PERFORMANCE] Rendering a template that was " + + "not found in view path. Templates outside the view path are " + + "not cached and result in expensive disk operations. Move this " + + "file into #{view_paths.join(':')} or add the folder to your " + + "view path list" + end + + template end end + memoize :_pick_template - # Assigns instance variables from the controller to the view. - def assign_variables_from_controller - @assigns.each { |key, value| instance_variable_set("@#{key}", value) } + def _exempt_from_layout?(template_path) #:nodoc: + template = _pick_template(template_path).to_s + @@exempt_from_layout.any? { |ext| template =~ ext } + rescue ActionView::MissingTemplate + return false end - def set_controller_content_type(content_type) - if controller.respond_to?(:response) - controller.response.content_type ||= content_type + def _render_with_layout(options, local_assigns, &block) #:nodoc: + partial_layout = options.delete(:layout) + + if block_given? + begin + @_proc_for_layout = block + concat(render(options.merge(:partial => partial_layout))) + ensure + @_proc_for_layout = nil + end + else + begin + original_content_for_layout, @content_for_layout = @content_for_layout, render(options) + if (options[:inline] || options[:file] || options[:text]) + @cached_content_for_layout = @content_for_layout + render(:file => partial_layout, :locals => local_assigns) + else + render(options.merge(:partial => partial_layout)) + end + ensure + @content_for_layout = original_content_for_layout + end end end end diff --git a/actionpack/lib/action_view/helpers/active_record_helper.rb b/actionpack/lib/action_view/helpers/active_record_helper.rb index c339e10701..8b56d241ae 100644 --- a/actionpack/lib/action_view/helpers/active_record_helper.rb +++ b/actionpack/lib/action_view/helpers/active_record_helper.rb @@ -246,7 +246,7 @@ module ActionView alias_method :tag_without_error_wrapping, :tag def tag(name, options) - if object.respond_to?("errors") && object.errors.respond_to?("on") + if object.respond_to?(:errors) && object.errors.respond_to?(:on) error_wrapping(tag_without_error_wrapping(name, options), object.errors.on(@method_name)) else tag_without_error_wrapping(name, options) @@ -255,7 +255,7 @@ module ActionView alias_method :content_tag_without_error_wrapping, :content_tag def content_tag(name, value, options) - if object.respond_to?("errors") && object.errors.respond_to?("on") + if object.respond_to?(:errors) && object.errors.respond_to?(:on) error_wrapping(content_tag_without_error_wrapping(name, value, options), object.errors.on(@method_name)) else content_tag_without_error_wrapping(name, value, options) @@ -264,7 +264,7 @@ module ActionView alias_method :to_date_select_tag_without_error_wrapping, :to_date_select_tag def to_date_select_tag(options = {}, html_options = {}) - if object.respond_to?("errors") && object.errors.respond_to?("on") + if object.respond_to?(:errors) && object.errors.respond_to?(:on) error_wrapping(to_date_select_tag_without_error_wrapping(options, html_options), object.errors.on(@method_name)) else to_date_select_tag_without_error_wrapping(options, html_options) @@ -273,7 +273,7 @@ module ActionView alias_method :to_datetime_select_tag_without_error_wrapping, :to_datetime_select_tag def to_datetime_select_tag(options = {}, html_options = {}) - if object.respond_to?("errors") && object.errors.respond_to?("on") + if object.respond_to?(:errors) && object.errors.respond_to?(:on) error_wrapping(to_datetime_select_tag_without_error_wrapping(options, html_options), object.errors.on(@method_name)) else to_datetime_select_tag_without_error_wrapping(options, html_options) @@ -282,7 +282,7 @@ module ActionView alias_method :to_time_select_tag_without_error_wrapping, :to_time_select_tag def to_time_select_tag(options = {}, html_options = {}) - if object.respond_to?("errors") && object.errors.respond_to?("on") + if object.respond_to?(:errors) && object.errors.respond_to?(:on) error_wrapping(to_time_select_tag_without_error_wrapping(options, html_options), object.errors.on(@method_name)) else to_time_select_tag_without_error_wrapping(options, html_options) @@ -298,7 +298,7 @@ module ActionView end def column_type - object.send("column_for_attribute", @method_name).type + object.send(:column_for_attribute, @method_name).type end end end diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb index 623ed1e8df..ed33f082b9 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb @@ -104,7 +104,7 @@ module ActionView ASSETS_DIR = defined?(Rails.public_path) ? Rails.public_path : "public" JAVASCRIPTS_DIR = "#{ASSETS_DIR}/javascripts" STYLESHEETS_DIR = "#{ASSETS_DIR}/stylesheets" - JAVASCRIPT_DEFAULT_SOURCES = ['prototype', 'effects', 'dragdrop', 'controls'].map(&:to_s).freeze unless const_defined?(:JAVASCRIPT_DEFAULT_SOURCES) + JAVASCRIPT_DEFAULT_SOURCES = ['prototype', 'effects', 'dragdrop', 'controls'].freeze unless const_defined?(:JAVASCRIPT_DEFAULT_SOURCES) # Returns a link tag that browsers and news readers can use to auto-detect # an RSS or ATOM feed. The +type+ can either be <tt>:rss</tt> (default) or diff --git a/actionpack/lib/action_view/helpers/prototype_helper.rb b/actionpack/lib/action_view/helpers/prototype_helper.rb index e452b04b31..ff41a6d417 100644 --- a/actionpack/lib/action_view/helpers/prototype_helper.rb +++ b/actionpack/lib/action_view/helpers/prototype_helper.rb @@ -255,6 +255,14 @@ module ActionView link_to_function(name, remote_function(options), html_options || options.delete(:html)) end + # Creates a button with an onclick event which calls a remote action + # via XMLHttpRequest + # The options for specifying the target with :url + # and defining callbacks is the same as link_to_remote. + def button_to_remote(name, options = {}, html_options = {}) + button_to_function(name, remote_function(options), html_options) + end + # Periodically calls the specified url (<tt>options[:url]</tt>) every # <tt>options[:frequency]</tt> seconds (default is 10). Usually used to # update a specified div (<tt>options[:update]</tt>) with the results @@ -1052,7 +1060,7 @@ module ActionView js_options['asynchronous'] = options[:type] != :synchronous js_options['method'] = method_option_to_s(options[:method]) if options[:method] - js_options['insertion'] = options[:position].to_s.downcase if options[:position] + js_options['insertion'] = "'#{options[:position].to_s.downcase}'" if options[:position] js_options['evalScripts'] = options[:script].nil? || options[:script] if options[:form] diff --git a/actionpack/lib/action_view/helpers/record_tag_helper.rb b/actionpack/lib/action_view/helpers/record_tag_helper.rb index 9bb235175e..0cdb70e217 100644 --- a/actionpack/lib/action_view/helpers/record_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/record_tag_helper.rb @@ -49,9 +49,9 @@ module ActionView # def content_tag_for(tag_name, record, *args, &block) prefix = args.first.is_a?(Hash) ? nil : args.shift - options = args.first.is_a?(Hash) ? args.shift : {} - concat content_tag(tag_name, capture(&block), - options.merge({ :class => "#{dom_class(record)} #{options[:class]}".strip, :id => dom_id(record, prefix) })) + options = args.extract_options! + options.merge!({ :class => "#{dom_class(record)} #{options[:class]}".strip, :id => dom_id(record, prefix) }) + content_tag(tag_name, options, &block) end end end diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index ff6e588f62..ab1fdc80bc 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -298,7 +298,7 @@ module ActionView "" else textilized = RedCloth.new(text, [ :hard_breaks ]) - textilized.hard_breaks = true if textilized.respond_to?("hard_breaks=") + textilized.hard_breaks = true if textilized.respond_to?(:hard_breaks=) textilized.to_html end end diff --git a/actionpack/lib/action_view/partials.rb b/actionpack/lib/action_view/partials.rb index 443c49b870..373bb92dc4 100644 --- a/actionpack/lib/action_view/partials.rb +++ b/actionpack/lib/action_view/partials.rb @@ -196,7 +196,7 @@ module ActionView path = "_#{partial_path}" end - pick_template(path) + _pick_template(path) end memoize :_pick_partial_template end diff --git a/actionpack/lib/action_view/renderable.rb b/actionpack/lib/action_view/renderable.rb index fa45edd436..d960335220 100644 --- a/actionpack/lib/action_view/renderable.rb +++ b/actionpack/lib/action_view/renderable.rb @@ -26,11 +26,11 @@ module ActionView def render(view, local_assigns = {}) compile(local_assigns) - view._first_render ||= self - view._last_render = self + view.send(:_first_render=, self) unless view.send(:_first_render) + view.send(:_last_render=, self) - view.send(:evaluate_assigns) - view.send(:set_controller_content_type, mime_type) if respond_to?(:mime_type) + view.send(:_evaluate_assigns_and_ivars) + view.send(:_set_controller_content_type, mime_type) if respond_to?(:mime_type) view.send(method_name(local_assigns), local_assigns) do |*names| if proc = view.instance_variable_get("@_proc_for_layout") diff --git a/actionpack/lib/action_view/renderable_partial.rb b/actionpack/lib/action_view/renderable_partial.rb index 5203e57ead..123a9aebbc 100644 --- a/actionpack/lib/action_view/renderable_partial.rb +++ b/actionpack/lib/action_view/renderable_partial.rb @@ -27,8 +27,14 @@ module ActionView def render_partial(view, object = nil, local_assigns = {}, as = nil) object ||= local_assigns[:object] || - local_assigns[variable_name] || - view.controller.instance_variable_get("@#{variable_name}") if view.respond_to?(:controller) + local_assigns[variable_name] + + if view.respond_to?(:controller) + object ||= ActiveSupport::Deprecation::DeprecatedObjectProxy.new( + view.controller.instance_variable_get("@#{variable_name}"), + "@#{variable_name} will no longer be implicitly assigned to #{variable_name}" + ) + end # Ensure correct object is reassigned to other accessors local_assigns[:object] = local_assigns[variable_name] = object diff --git a/actionpack/lib/action_view/template_handlers/builder.rb b/actionpack/lib/action_view/template_handlers/builder.rb index 7d24a5c423..788dc93326 100644 --- a/actionpack/lib/action_view/template_handlers/builder.rb +++ b/actionpack/lib/action_view/template_handlers/builder.rb @@ -6,7 +6,7 @@ module ActionView include Compilable def compile(template) - "set_controller_content_type(Mime::XML);" + + "_set_controller_content_type(Mime::XML);" + "xml = ::Builder::XmlMarkup.new(:indent => 2);" + "self.output_buffer = xml.target!;" + template.source + diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index adbb37fd09..c69f9455b2 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -54,7 +54,7 @@ module ActionView private def method_missing(selector, *args) controller = TestController.new - return controller.send!(selector, *args) if ActionController::Routing::Routes.named_routes.helpers.include?(selector) + return controller.__send__(selector, *args) if ActionController::Routing::Routes.named_routes.helpers.include?(selector) super end end diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb index 1531e7c21a..08cbcbf302 100644 --- a/actionpack/test/controller/assert_select_test.rb +++ b/actionpack/test/controller/assert_select_test.rb @@ -433,6 +433,17 @@ class AssertSelectTest < Test::Unit::TestCase assert_select_rjs :remove, "test1" end + def test_assert_select_rjs_for_remove_offers_useful_error_when_assertion_fails + render_rjs do |page| + page.remove "test_with_typo" + end + + assert_select_rjs :remove, "test1" + + rescue Test::Unit::AssertionFailedError + assert_equal "No RJS statement that removes 'test1' was rendered.", $!.message + end + def test_assert_select_rjs_for_remove_ignores_block render_rjs do |page| page.remove "test1" @@ -454,6 +465,17 @@ class AssertSelectTest < Test::Unit::TestCase assert_select_rjs :show, "test1" end + def test_assert_select_rjs_for_show_offers_useful_error_when_assertion_fails + render_rjs do |page| + page.show "test_with_typo" + end + + assert_select_rjs :show, "test1" + + rescue Test::Unit::AssertionFailedError + assert_equal "No RJS statement that shows 'test1' was rendered.", $!.message + end + def test_assert_select_rjs_for_show_ignores_block render_rjs do |page| page.show "test1" @@ -475,6 +497,17 @@ class AssertSelectTest < Test::Unit::TestCase assert_select_rjs :hide, "test1" end + def test_assert_select_rjs_for_hide_offers_useful_error_when_assertion_fails + render_rjs do |page| + page.hide "test_with_typo" + end + + assert_select_rjs :hide, "test1" + + rescue Test::Unit::AssertionFailedError + assert_equal "No RJS statement that hides 'test1' was rendered.", $!.message + end + def test_assert_select_rjs_for_hide_ignores_block render_rjs do |page| page.hide "test1" @@ -496,6 +529,17 @@ class AssertSelectTest < Test::Unit::TestCase assert_select_rjs :toggle, "test1" end + def test_assert_select_rjs_for_toggle_offers_useful_error_when_assertion_fails + render_rjs do |page| + page.toggle "test_with_typo" + end + + assert_select_rjs :toggle, "test1" + + rescue Test::Unit::AssertionFailedError + assert_equal "No RJS statement that toggles 'test1' was rendered.", $!.message + end + def test_assert_select_rjs_for_toggle_ignores_block render_rjs do |page| page.toggle "test1" @@ -555,6 +599,11 @@ class AssertSelectTest < Test::Unit::TestCase end end + def test_assert_select_rjs_raise_errors + assert_raises(ArgumentError) { assert_select_rjs(:destroy) } + assert_raises(ArgumentError) { assert_select_rjs(:insert, :left) } + end + # Simple selection from a single result. def test_nested_assert_select_rjs_with_single_result render_rjs do |page| diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb index d49cc2a9aa..738c016c6e 100644 --- a/actionpack/test/controller/base_test.rb +++ b/actionpack/test/controller/base_test.rb @@ -84,11 +84,11 @@ class ControllerInstanceTests < Test::Unit::TestCase def test_action_methods @empty_controllers.each do |c| hide_mocha_methods_from_controller(c) - assert_equal Set.new, c.send!(:action_methods), "#{c.controller_path} should be empty!" + assert_equal Set.new, c.__send__(:action_methods), "#{c.controller_path} should be empty!" end @non_empty_controllers.each do |c| hide_mocha_methods_from_controller(c) - assert_equal Set.new(%w(public_action)), c.send!(:action_methods), "#{c.controller_path} should not be empty!" + assert_equal Set.new(%w(public_action)), c.__send__(:action_methods), "#{c.controller_path} should not be empty!" end end @@ -100,7 +100,7 @@ class ControllerInstanceTests < Test::Unit::TestCase :expects, :mocha, :mocha_inspect, :reset_mocha, :stubba_object, :stubba_method, :stubs, :verify, :__metaclass__, :__is_a__, :to_matcher, ] - controller.class.send!(:hide_action, *mocha_methods) + controller.class.__send__(:hide_action, *mocha_methods) end end @@ -140,7 +140,7 @@ class PerformActionTest < Test::Unit::TestCase def test_method_missing_is_not_an_action_name use_controller MethodMissingController - assert ! @controller.send!(:action_methods).include?('method_missing') + assert ! @controller.__send__(:action_methods).include?('method_missing') get :method_missing assert_response :success diff --git a/actionpack/test/controller/components_test.rb b/actionpack/test/controller/components_test.rb index 71e8a18071..4d36fc411d 100644 --- a/actionpack/test/controller/components_test.rb +++ b/actionpack/test/controller/components_test.rb @@ -77,49 +77,64 @@ class ComponentsTest < Test::Unit::TestCase end def test_calling_from_controller - get :calling_from_controller - assert_equal "Lady of the House, speaking", @response.body + assert_deprecated do + get :calling_from_controller + assert_equal "Lady of the House, speaking", @response.body + end end def test_calling_from_controller_with_params - get :calling_from_controller_with_params - assert_equal "David of the House, speaking", @response.body + assert_deprecated do + get :calling_from_controller_with_params + assert_equal "David of the House, speaking", @response.body + end end def test_calling_from_controller_with_different_status_code - get :calling_from_controller_with_different_status_code - assert_equal 500, @response.response_code + assert_deprecated do + get :calling_from_controller_with_different_status_code + assert_equal 500, @response.response_code + end end def test_calling_from_template - get :calling_from_template - assert_equal "Ring, ring: Lady of the House, speaking", @response.body + assert_deprecated do + get :calling_from_template + assert_equal "Ring, ring: Lady of the House, speaking", @response.body + end end def test_etag_is_set_for_parent_template_when_calling_from_template - get :calling_from_template - expected_etag = etag_for("Ring, ring: Lady of the House, speaking") - assert_equal expected_etag, @response.headers['ETag'] + assert_deprecated do + get :calling_from_template + expected_etag = etag_for("Ring, ring: Lady of the House, speaking") + assert_equal expected_etag, @response.headers['ETag'] + end end def test_internal_calling - get :internal_caller - assert_equal "Are you there? Yes, ma'am", @response.body + assert_deprecated do + get :internal_caller + assert_equal "Are you there? Yes, ma'am", @response.body + end end def test_flash - get :set_flash - assert_equal 'My stoney baby', flash[:notice] - get :use_flash - assert_equal 'My stoney baby', @response.body - get :use_flash - assert_equal 'no flash', @response.body + assert_deprecated do + get :set_flash + assert_equal 'My stoney baby', flash[:notice] + get :use_flash + assert_equal 'My stoney baby', @response.body + get :use_flash + assert_equal 'no flash', @response.body + end end def test_component_redirect_redirects - get :calling_redirected - - assert_redirected_to :controller=>"callee", :action => "being_called" + assert_deprecated do + get :calling_redirected + assert_redirected_to :controller=>"callee", :action => "being_called" + end end def test_component_multiple_redirect_redirects @@ -128,9 +143,10 @@ class ComponentsTest < Test::Unit::TestCase end def test_component_as_string_redirect_renders_redirected_action - get :calling_redirected_as_string - - assert_equal "Lady of the House, speaking", @response.body + assert_deprecated do + get :calling_redirected_as_string + assert_equal "Lady of the House, speaking", @response.body + end end protected diff --git a/actionpack/test/controller/filter_params_test.rb b/actionpack/test/controller/filter_params_test.rb index c4de10181d..0b259a7980 100644 --- a/actionpack/test/controller/filter_params_test.rb +++ b/actionpack/test/controller/filter_params_test.rb @@ -27,7 +27,7 @@ class FilterParamTest < Test::Unit::TestCase test_hashes.each do |before_filter, after_filter, filter_words| FilterParamController.filter_parameter_logging(*filter_words) - assert_equal after_filter, @controller.send!(:filter_parameters, before_filter) + assert_equal after_filter, @controller.__send__(:filter_parameters, before_filter) filter_words.push('blah') FilterParamController.filter_parameter_logging(*filter_words) do |key, value| @@ -37,7 +37,7 @@ class FilterParamTest < Test::Unit::TestCase before_filter['barg'] = {'bargain'=>'gain', 'blah'=>'bar', 'bar'=>{'bargain'=>{'blah'=>'foo'}}} after_filter['barg'] = {'bargain'=>'niag', 'blah'=>'[FILTERED]', 'bar'=>{'bargain'=>{'blah'=>'[FILTERED]'}}} - assert_equal after_filter, @controller.send!(:filter_parameters, before_filter) + assert_equal after_filter, @controller.__send__(:filter_parameters, before_filter) end end diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb index 3652c482f1..dafa344473 100644 --- a/actionpack/test/controller/filters_test.rb +++ b/actionpack/test/controller/filters_test.rb @@ -111,15 +111,15 @@ class FilterTest < Test::Unit::TestCase end class OnlyConditionProcController < ConditionalFilterController - before_filter(:only => :show) {|c| c.assigns["ran_proc_filter"] = true } + before_filter(:only => :show) {|c| c.instance_variable_set(:"@ran_proc_filter", true) } end class ExceptConditionProcController < ConditionalFilterController - before_filter(:except => :show_without_filter) {|c| c.assigns["ran_proc_filter"] = true } + before_filter(:except => :show_without_filter) {|c| c.instance_variable_set(:"@ran_proc_filter", true) } end class ConditionalClassFilter - def self.filter(controller) controller.assigns["ran_class_filter"] = true end + def self.filter(controller) controller.instance_variable_set(:"@ran_class_filter", true) end end class OnlyConditionClassController < ConditionalFilterController @@ -131,7 +131,7 @@ class FilterTest < Test::Unit::TestCase end class AnomolousYetValidConditionController < ConditionalFilterController - before_filter(ConditionalClassFilter, :ensure_login, Proc.new {|c| c.assigns["ran_proc_filter1"] = true }, :except => :show_without_filter) { |c| c.assigns["ran_proc_filter2"] = true} + before_filter(ConditionalClassFilter, :ensure_login, Proc.new {|c| c.instance_variable_set(:"@ran_proc_filter1", true)}, :except => :show_without_filter) { |c| c.instance_variable_set(:"@ran_proc_filter2", true)} end class ConditionalOptionsFilter < ConditionalFilterController @@ -225,16 +225,16 @@ class FilterTest < Test::Unit::TestCase end class ProcController < PrependingController - before_filter(proc { |c| c.assigns["ran_proc_filter"] = true }) + before_filter(proc { |c| c.instance_variable_set(:"@ran_proc_filter", true) }) end class ImplicitProcController < PrependingController - before_filter { |c| c.assigns["ran_proc_filter"] = true } + before_filter { |c| c.instance_variable_set(:"@ran_proc_filter", true) } end class AuditFilter def self.filter(controller) - controller.assigns["was_audited"] = true + controller.instance_variable_set(:"@was_audited", true) end end @@ -242,12 +242,12 @@ class FilterTest < Test::Unit::TestCase def before(controller) @execution_log = "before" controller.class.execution_log << " before aroundfilter " if controller.respond_to? :execution_log - controller.assigns["before_ran"] = true + controller.instance_variable_set(:"@before_ran", true) end def after(controller) - controller.assigns["execution_log"] = @execution_log + " and after" - controller.assigns["after_ran"] = true + controller.instance_variable_set(:"@execution_log", @execution_log + " and after") + controller.instance_variable_set(:"@after_ran", true) controller.class.execution_log << " after aroundfilter " if controller.respond_to? :execution_log end end @@ -364,7 +364,7 @@ class FilterTest < Test::Unit::TestCase begin yield rescue ErrorToRescue => ex - controller.send! :render, :text => "I rescued this: #{ex.inspect}" + controller.__send__ :render, :text => "I rescued this: #{ex.inspect}" end end end @@ -726,9 +726,9 @@ end class ControllerWithProcFilter < PostsController around_filter(:only => :no_raise) do |c,b| - c.assigns['before'] = true + c.instance_variable_set(:"@before", true) b.call - c.assigns['after'] = true + c.instance_variable_set(:"@after", true) end end diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index c986941140..7e4c3e171a 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -243,7 +243,7 @@ class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest reset! stub_integration_session(@integration_session) %w( get post head put delete ).each do |verb| - assert_nothing_raised("'#{verb}' should use integration test methods") { send!(verb, '/') } + assert_nothing_raised("'#{verb}' should use integration test methods") { __send__(verb, '/') } end end end diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb index 71f110f241..1120fdbff5 100644 --- a/actionpack/test/controller/layout_test.rb +++ b/actionpack/test/controller/layout_test.rb @@ -79,53 +79,6 @@ class LayoutAutoDiscoveryTest < Test::Unit::TestCase end end -class ExemptFromLayoutTest < Test::Unit::TestCase - def setup - @controller = LayoutTest.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - end - - def test_rjs_exempt_from_layout - assert @controller.send!(:template_exempt_from_layout?, 'test.rjs') - end - - def test_rhtml_and_rxml_not_exempt_from_layout - assert !@controller.send!(:template_exempt_from_layout?, 'test.rhtml') - assert !@controller.send!(:template_exempt_from_layout?, 'test.rxml') - end - - def test_other_extension_not_exempt_from_layout - assert !@controller.send!(:template_exempt_from_layout?, 'test.random') - end - - def test_add_extension_to_exempt_from_layout - ['rpdf', :rpdf].each do |ext| - assert_nothing_raised do - ActionController::Base.exempt_from_layout ext - end - assert @controller.send!(:template_exempt_from_layout?, "test.#{ext}") - end - end - - def test_add_regexp_to_exempt_from_layout - ActionController::Base.exempt_from_layout /\.rdoc/ - assert @controller.send!(:template_exempt_from_layout?, 'test.rdoc') - end - - def test_rhtml_exempt_from_layout_status_should_prevent_layout_render - ActionController::Base.exempt_from_layout :rhtml - - assert @controller.send!(:template_exempt_from_layout?, 'test.rhtml') - assert @controller.send!(:template_exempt_from_layout?, 'hello.rhtml') - - get :hello - assert_equal 'hello.rhtml', @response.body - ActionController::Base.exempt_from_layout.delete(/\.rhtml$/) - end -end - - class DefaultLayoutController < LayoutTest end @@ -179,8 +132,6 @@ class LayoutSetInResponseTest < Test::Unit::TestCase ActionController::Base.exempt_from_layout :rhtml @controller = RenderWithTemplateOptionController.new - assert @controller.send(:template_exempt_from_layout?, 'alt/hello.rhtml') - get :hello assert_equal "alt/hello.rhtml", @response.body.strip diff --git a/actionpack/test/controller/new_render_test.rb b/actionpack/test/controller/new_render_test.rb deleted file mode 100644 index 82919b7777..0000000000 --- a/actionpack/test/controller/new_render_test.rb +++ /dev/null @@ -1,981 +0,0 @@ -require 'abstract_unit' -require 'controller/fake_models' - -class CustomersController < ActionController::Base -end - -module Fun - class GamesController < ActionController::Base - def hello_world - end - end -end - -module NewRenderTestHelper - def rjs_helper_method_from_module - page.visual_effect :highlight - end -end - -class LabellingFormBuilder < ActionView::Helpers::FormBuilder -end - -class NewRenderTestController < ActionController::Base - layout :determine_layout - - def self.controller_name; "test"; end - def self.controller_path; "test"; end - - def hello_world - end - - def render_hello_world - render :template => "test/hello_world" - end - - def render_hello_world_from_variable - @person = "david" - render :text => "hello #{@person}" - end - - def render_action_hello_world - render :action => "hello_world" - end - - def render_action_hello_world_as_symbol - render :action => :hello_world - end - - def render_text_hello_world - render :text => "hello world" - end - - def render_text_hello_world_with_layout - @variable_for_layout = ", I'm here!" - render :text => "hello world", :layout => true - end - - def hello_world_with_layout_false - render :layout => false - end - - def render_custom_code - render :text => "hello world", :status => "404 Moved" - end - - def render_file_with_instance_variables - @secret = 'in the sauce' - path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb') - render :file => path - end - - def render_file_from_template - @secret = 'in the sauce' - @path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) - end - - def render_file_with_locals - path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb') - render :file => path, :locals => {:secret => 'in the sauce'} - end - - def render_file_not_using_full_path - @secret = 'in the sauce' - render :file => 'test/render_file_with_ivar' - end - - def render_file_not_using_full_path_with_dot_in_path - @secret = 'in the sauce' - render :file => 'test/dot.directory/render_file_with_ivar' - end - - def render_xml_hello - @name = "David" - render :template => "test/hello" - end - - def greeting - # let's just rely on the template - end - - def layout_test - render :action => "hello_world" - end - - def layout_test_with_different_layout - render :action => "hello_world", :layout => "standard" - end - - def rendering_without_layout - render :action => "hello_world", :layout => false - end - - def layout_overriding_layout - render :action => "hello_world", :layout => "standard" - end - - def rendering_nothing_on_layout - render :nothing => true - end - - def builder_layout_test - render :action => "hello" - end - - def partials_list - @test_unchanged = 'hello' - @customers = [ Customer.new("david"), Customer.new("mary") ] - render :action => "list" - end - - def partial_only - render :partial => true - end - - def partial_only_with_layout - render :partial => "partial_only", :layout => true - end - - def partial_with_counter - render :partial => "counter", :locals => { :counter_counter => 5 } - end - - def partial_with_locals - render :partial => "customer", :locals => { :customer => Customer.new("david") } - end - - def partial_with_form_builder - render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, @template, {}, Proc.new {}) - end - - def partial_with_form_builder_subclass - render :partial => LabellingFormBuilder.new(:post, nil, @template, {}, Proc.new {}) - end - - def partial_collection - render :partial => "customer", :collection => [ Customer.new("david"), Customer.new("mary") ] - end - - def partial_collection_with_as - render :partial => "customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :customer - end - - def partial_collection_with_spacer - render :partial => "customer", :spacer_template => "partial_only", :collection => [ Customer.new("david"), Customer.new("mary") ] - end - - def partial_collection_with_counter - render :partial => "customer_counter", :collection => [ Customer.new("david"), Customer.new("mary") ] - end - - def partial_collection_with_locals - render :partial => "customer_greeting", :collection => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } - end - - def partial_collection_shorthand_with_locals - render :partial => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } - end - - def partial_collection_shorthand_with_different_types_of_records - render :partial => [ - BadCustomer.new("mark"), - GoodCustomer.new("craig"), - BadCustomer.new("john"), - GoodCustomer.new("zach"), - GoodCustomer.new("brandon"), - BadCustomer.new("dan") ], - :locals => { :greeting => "Bonjour" } - end - - def partial_collection_shorthand_with_different_types_of_records_with_counter - partial_collection_shorthand_with_different_types_of_records - end - - def empty_partial_collection - render :partial => "customer", :collection => [] - end - - def partial_with_hash_object - render :partial => "hash_object", :object => {:first_name => "Sam"} - end - - def partial_hash_collection - render :partial => "hash_object", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ] - end - - def partial_hash_collection_with_locals - render :partial => "hash_greeting", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ], :locals => { :greeting => "Hola" } - end - - def partial_with_implicit_local_assignment - @customer = Customer.new("Marcel") - render :partial => "customer" - end - - def missing_partial - render :partial => 'thisFileIsntHere' - end - - def hello_in_a_string - @customers = [ Customer.new("david"), Customer.new("mary") ] - render :text => "How's there? " << render_to_string(:template => "test/list") - end - - def render_to_string_with_assigns - @before = "i'm before the render" - render_to_string :text => "foo" - @after = "i'm after the render" - render :action => "test/hello_world" - end - - def render_to_string_with_partial - @partial_only = render_to_string :partial => "partial_only" - @partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") } - render :action => "test/hello_world" - end - - def render_to_string_with_exception - render_to_string :file => "exception that will not be caught - this will certainly not work" - end - - def render_to_string_with_caught_exception - @before = "i'm before the render" - begin - render_to_string :file => "exception that will be caught- hope my future instance vars still work!" - rescue - end - @after = "i'm after the render" - render :action => "test/hello_world" - end - - def accessing_params_in_template - render :inline => "Hello: <%= params[:name] %>" - end - - def accessing_request_in_template - render :inline => "Hello: <%= request.host %>" - end - - def accessing_logger_in_template - render :inline => "<%= logger.class %>" - end - - def accessing_action_name_in_template - render :inline => "<%= action_name %>" - end - - def accessing_controller_name_in_template - render :inline => "<%= controller_name %>" - end - - def accessing_params_in_template_with_layout - render :layout => nil, :inline => "Hello: <%= params[:name] %>" - end - - def render_with_explicit_template - render :template => "test/hello_world" - end - - def render_with_explicit_template_with_locals - render :template => "test/render_file_with_locals", :locals => { :secret => 'area51' } - end - - def double_render - render :text => "hello" - render :text => "world" - end - - def double_redirect - redirect_to :action => "double_render" - redirect_to :action => "double_render" - end - - def render_and_redirect - render :text => "hello" - redirect_to :action => "double_render" - end - - def render_to_string_and_render - @stuff = render_to_string :text => "here is some cached stuff" - render :text => "Hi web users! #{@stuff}" - end - - def rendering_with_conflicting_local_vars - @name = "David" - def @template.name() nil end - render :action => "potential_conflicts" - end - - def hello_world_from_rxml_using_action - render :action => "hello_world_from_rxml.builder" - end - - def hello_world_from_rxml_using_template - render :template => "test/hello_world_from_rxml.builder" - end - - def head_with_location_header - head :location => "/foo" - end - - def head_with_symbolic_status - head :status => params[:status].intern - end - - def head_with_integer_status - head :status => params[:status].to_i - end - - def head_with_string_status - head :status => params[:status] - end - - def head_with_custom_header - head :x_custom_header => "something" - end - - def head_with_status_code_first - head :forbidden, :x_custom_header => "something" - end - - def render_with_location - render :xml => "<hello/>", :location => "http://example.com", :status => 201 - end - - def render_with_object_location - customer = Customer.new("Some guy", 1) - render :xml => "<customer/>", :location => customer_url(customer), :status => :created - end - - def render_with_to_xml - to_xmlable = Class.new do - def to_xml - "<i-am-xml/>" - end - end.new - - render :xml => to_xmlable - end - - helper NewRenderTestHelper - helper do - def rjs_helper_method(value) - page.visual_effect :highlight, value - end - end - - def enum_rjs_test - render :update do |page| - page.select('.product').each do |value| - page.rjs_helper_method_from_module - page.rjs_helper_method(value) - page.sortable(value, :url => { :action => "order" }) - page.draggable(value) - end - end - end - - def delete_with_js - @project_id = 4 - end - - def render_js_with_explicit_template - @project_id = 4 - render :template => 'test/delete_with_js' - end - - def render_js_with_explicit_action_template - @project_id = 4 - render :action => 'delete_with_js' - end - - def update_page - render :update do |page| - page.replace_html 'balance', '$37,000,000.00' - page.visual_effect :highlight, 'balance' - end - end - - def update_page_with_instance_variables - @money = '$37,000,000.00' - @div_id = 'balance' - render :update do |page| - page.replace_html @div_id, @money - page.visual_effect :highlight, @div_id - end - end - - def action_talk_to_layout - # Action template sets variable that's picked up by layout - end - - def render_text_with_assigns - @hello = "world" - render :text => "foo" - end - - def yield_content_for - render :action => "content_for", :layout => "yield" - end - - def render_content_type_from_body - response.content_type = Mime::RSS - render :text => "hello world!" - end - - def render_call_to_partial_with_layout - render :action => "calling_partial_with_layout" - end - - def render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout - render :action => "calling_partial_with_layout" - end - - def render_using_layout_around_block - render :action => "using_layout_around_block" - end - - def render_using_layout_around_block_with_args - render :action => "using_layout_around_block_with_args" - end - - def render_using_layout_around_block_in_main_layout_and_within_content_for_layout - render :action => "using_layout_around_block" - end - - def rescue_action(e) raise end - - private - def determine_layout - case action_name - when "hello_world", "layout_test", "rendering_without_layout", - "rendering_nothing_on_layout", "render_text_hello_world", - "render_text_hello_world_with_layout", - "hello_world_with_layout_false", - "partial_only", "partial_only_with_layout", - "accessing_params_in_template", - "accessing_params_in_template_with_layout", - "render_with_explicit_template", - "render_js_with_explicit_template", - "render_js_with_explicit_action_template", - "delete_with_js", "update_page", "update_page_with_instance_variables" - - "layouts/standard" - when "builder_layout_test" - "layouts/builder" - when "action_talk_to_layout", "layout_overriding_layout" - "layouts/talk_from_action" - when "render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout" - "layouts/partial_with_layout" - when "render_using_layout_around_block_in_main_layout_and_within_content_for_layout" - "layouts/block_with_layout" - end - end -end - -class NewRenderTest < Test::Unit::TestCase - def setup - @controller = NewRenderTestController.new - - # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get - # a more accurate simulation of what happens in "real life". - @controller.logger = Logger.new(nil) - - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - - @request.host = "www.nextangle.com" - end - - def test_simple_show - get :hello_world - assert_response :success - assert_template "test/hello_world" - assert_equal "<html>Hello world!</html>", @response.body - end - - def test_renders_default_template_for_missing_action - get :'hyphen-ated' - assert_template 'test/hyphen-ated' - end - - def test_do_with_render - get :render_hello_world - assert_template "test/hello_world" - end - - def test_do_with_render_from_variable - get :render_hello_world_from_variable - assert_equal "hello david", @response.body - end - - def test_do_with_render_action - get :render_action_hello_world - assert_template "test/hello_world" - end - - def test_do_with_render_action_as_symbol - get :render_action_hello_world_as_symbol - assert_template "test/hello_world" - end - - def test_do_with_render_text - get :render_text_hello_world - assert_equal "hello world", @response.body - end - - def test_do_with_render_text_and_layout - get :render_text_hello_world_with_layout - assert_equal "<html>hello world, I'm here!</html>", @response.body - end - - def test_do_with_render_action_and_layout_false - get :hello_world_with_layout_false - assert_equal 'Hello world!', @response.body - end - - def test_do_with_render_custom_code - get :render_custom_code - assert_response :missing - end - - def test_render_file_with_instance_variables - get :render_file_with_instance_variables - assert_equal "The secret is in the sauce\n", @response.body - end - - def test_render_file_not_using_full_path - get :render_file_not_using_full_path - assert_equal "The secret is in the sauce\n", @response.body - end - - def test_render_file_not_using_full_path_with_dot_in_path - get :render_file_not_using_full_path_with_dot_in_path - assert_equal "The secret is in the sauce\n", @response.body - end - - def test_render_file_with_locals - get :render_file_with_locals - assert_equal "The secret is in the sauce\n", @response.body - end - - def test_render_file_from_template - get :render_file_from_template - assert_equal "The secret is in the sauce\n", @response.body - end - - def test_attempt_to_access_object_method - assert_raises(ActionController::UnknownAction, "No action responded to [clone]") { get :clone } - end - - def test_private_methods - assert_raises(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout } - end - - def test_access_to_request_in_view - get :accessing_request_in_template - assert_equal "Hello: www.nextangle.com", @response.body - end - - def test_access_to_logger_in_view - get :accessing_logger_in_template - assert_equal "Logger", @response.body - end - - def test_access_to_action_name_in_view - get :accessing_action_name_in_template - assert_equal "accessing_action_name_in_template", @response.body - end - - def test_access_to_controller_name_in_view - get :accessing_controller_name_in_template - assert_equal "test", @response.body # name is explicitly set to 'test' inside the controller. - end - - def test_render_xml - get :render_xml_hello - assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body - end - - def test_enum_rjs_test - get :enum_rjs_test - assert_equal <<-EOS.strip, @response.body -$$(".product").each(function(value, index) { -new Effect.Highlight(element,{}); -new Effect.Highlight(value,{}); -Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value)})}}); -new Draggable(value, {}); -}); -EOS - end - - def test_render_xml_with_default - get :greeting - assert_equal "<p>This is grand!</p>\n", @response.body - end - - def test_render_with_default_from_accept_header - xhr :get, :greeting - assert_equal "$(\"body\").visualEffect(\"highlight\");", @response.body - end - - def test_render_rjs_with_default - get :delete_with_js - assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body - end - - def test_render_rjs_template_explicitly - get :render_js_with_explicit_template - assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body - end - - def test_rendering_rjs_action_explicitly - get :render_js_with_explicit_action_template - assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body - end - - def test_layout_rendering - get :layout_test - assert_equal "<html>Hello world!</html>", @response.body - end - - def test_layout_test_with_different_layout - get :layout_test_with_different_layout - assert_equal "<html>Hello world!</html>", @response.body - end - - def test_rendering_without_layout - get :rendering_without_layout - assert_equal "Hello world!", @response.body - end - - def test_layout_overriding_layout - get :layout_overriding_layout - assert_no_match %r{<title>}, @response.body - end - - def test_rendering_nothing_on_layout - get :rendering_nothing_on_layout - assert_equal " ", @response.body - end - - def test_render_xml_with_layouts - get :builder_layout_test - assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body - end - - def test_partial_only - get :partial_only - assert_equal "only partial", @response.body - end - - def test_partial_only_with_layout - get :partial_only_with_layout - assert_equal "<html>only partial</html>", @response.body - end - - def test_render_to_string - assert_not_deprecated { get :hello_in_a_string } - assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body - end - - def test_render_to_string_doesnt_break_assigns - get :render_to_string_with_assigns - assert_equal "i'm before the render", assigns(:before) - assert_equal "i'm after the render", assigns(:after) - end - - def test_render_to_string_partial - get :render_to_string_with_partial - assert_equal "only partial", assigns(:partial_only) - assert_equal "Hello: david", assigns(:partial_with_locals) - end - - def test_bad_render_to_string_still_throws_exception - assert_raises(ActionView::MissingTemplate) { get :render_to_string_with_exception } - end - - def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns - assert_nothing_raised { get :render_to_string_with_caught_exception } - assert_equal "i'm before the render", assigns(:before) - assert_equal "i'm after the render", assigns(:after) - end - - def test_nested_rendering - get :hello_world - assert_equal "Living in a nested world", Fun::GamesController.process(@request, @response).body - end - - def test_accessing_params_in_template - get :accessing_params_in_template, :name => "David" - assert_equal "Hello: David", @response.body - end - - def test_accessing_params_in_template_with_layout - get :accessing_params_in_template_with_layout, :name => "David" - assert_equal "<html>Hello: David</html>", @response.body - end - - def test_render_with_explicit_template - get :render_with_explicit_template - assert_response :success - end - - def test_double_render - assert_raises(ActionController::DoubleRenderError) { get :double_render } - end - - def test_double_redirect - assert_raises(ActionController::DoubleRenderError) { get :double_redirect } - end - - def test_render_and_redirect - assert_raises(ActionController::DoubleRenderError) { get :render_and_redirect } - end - - # specify the one exception to double render rule - render_to_string followed by render - def test_render_to_string_and_render - get :render_to_string_and_render - assert_equal("Hi web users! here is some cached stuff", @response.body) - end - - def test_rendering_with_conflicting_local_vars - get :rendering_with_conflicting_local_vars - assert_equal("First: David\nSecond: Stephan\nThird: David\nFourth: David\nFifth: ", @response.body) - end - - def test_action_talk_to_layout - get :action_talk_to_layout - assert_equal "<title>Talking to the layout</title>\nAction was here!", @response.body - end - - def test_partial_with_counter - get :partial_with_counter - assert_equal "5", @response.body - end - - def test_partials_list - get :partials_list - assert_equal "goodbyeHello: davidHello: marygoodbye\n", @response.body - end - - def test_partial_with_locals - get :partial_with_locals - assert_equal "Hello: david", @response.body - end - - def test_partial_with_form_builder - get :partial_with_form_builder - assert_match(/<label/, @response.body) - assert_template('test/_form') - end - - def test_partial_with_form_builder_subclass - get :partial_with_form_builder_subclass - assert_match(/<label/, @response.body) - assert_template('test/_labelling_form') - end - - def test_partial_collection - get :partial_collection - assert_equal "Hello: davidHello: mary", @response.body - end - - def test_partial_collection_with_as - get :partial_collection_with_as - assert_equal "david david davidmary mary mary", @response.body - end - - def test_partial_collection_with_counter - get :partial_collection_with_counter - assert_equal "david0mary1", @response.body - end - - def test_partial_collection_with_locals - get :partial_collection_with_locals - assert_equal "Bonjour: davidBonjour: mary", @response.body - end - - def test_partial_collection_with_spacer - get :partial_collection_with_spacer - assert_equal "Hello: davidonly partialHello: mary", @response.body - end - - def test_partial_collection_shorthand_with_locals - get :partial_collection_shorthand_with_locals - assert_equal "Bonjour: davidBonjour: mary", @response.body - end - - def test_partial_collection_shorthand_with_different_types_of_records - get :partial_collection_shorthand_with_different_types_of_records - assert_equal "Bonjour bad customer: mark0Bonjour good customer: craig1Bonjour bad customer: john2Bonjour good customer: zach3Bonjour good customer: brandon4Bonjour bad customer: dan5", @response.body - end - - def test_empty_partial_collection - get :empty_partial_collection - assert_equal " ", @response.body - end - - def test_partial_with_hash_object - get :partial_with_hash_object - assert_equal "Sam\nmaS\n", @response.body - end - - def test_hash_partial_collection - get :partial_hash_collection - assert_equal "Pratik\nkitarP\nAmy\nymA\n", @response.body - end - - def test_partial_hash_collection_with_locals - get :partial_hash_collection_with_locals - assert_equal "Hola: PratikHola: Amy", @response.body - end - - def test_partial_with_implicit_local_assignment - get :partial_with_implicit_local_assignment - assert_equal "Hello: Marcel", @response.body - end - - def test_render_missing_partial_template - assert_raises(ActionView::MissingTemplate) do - get :missing_partial - end - end - - def test_render_text_with_assigns - get :render_text_with_assigns - assert_equal "world", assigns["hello"] - end - - def test_template_with_locals - get :render_with_explicit_template_with_locals - assert_equal "The secret is area51\n", @response.body - end - - def test_update_page - get :update_page - assert_template nil - assert_equal 'text/javascript; charset=utf-8', @response.headers['type'] - assert_equal 2, @response.body.split($/).length - end - - def test_update_page_with_instance_variables - get :update_page_with_instance_variables - assert_template nil - assert_equal 'text/javascript; charset=utf-8', @response.headers['type'] - assert_match /balance/, @response.body - assert_match /\$37/, @response.body - end - - def test_yield_content_for - assert_not_deprecated { get :yield_content_for } - assert_equal "<title>Putting stuff in the title!</title>\n\nGreat stuff!\n", @response.body - end - - - def test_overwritting_rendering_relative_file_with_extension - get :hello_world_from_rxml_using_template - assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body - - get :hello_world_from_rxml_using_action - assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body - end - - - def test_head_with_location_header - get :head_with_location_header - assert @response.body.blank? - assert_equal "/foo", @response.headers["Location"] - assert_response :ok - end - - def test_head_with_custom_header - get :head_with_custom_header - assert @response.body.blank? - assert_equal "something", @response.headers["X-Custom-Header"] - assert_response :ok - end - - def test_head_with_symbolic_status - get :head_with_symbolic_status, :status => "ok" - assert_equal "200 OK", @response.headers["Status"] - assert_response :ok - - get :head_with_symbolic_status, :status => "not_found" - assert_equal "404 Not Found", @response.headers["Status"] - assert_response :not_found - - ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE.each do |status, code| - get :head_with_symbolic_status, :status => status.to_s - assert_equal code, @response.response_code - assert_response status - end - end - - def test_head_with_integer_status - ActionController::StatusCodes::STATUS_CODES.each do |code, message| - get :head_with_integer_status, :status => code.to_s - assert_equal message, @response.message - end - end - - def test_head_with_string_status - get :head_with_string_status, :status => "404 Eat Dirt" - assert_equal 404, @response.response_code - assert_equal "Eat Dirt", @response.message - assert_response :not_found - end - - def test_head_with_status_code_first - get :head_with_status_code_first - assert_equal 403, @response.response_code - assert_equal "Forbidden", @response.message - assert_equal "something", @response.headers["X-Custom-Header"] - assert_response :forbidden - end - - def test_rendering_with_location_should_set_header - get :render_with_location - assert_equal "http://example.com", @response.headers["Location"] - end - - def test_rendering_xml_should_call_to_xml_if_possible - get :render_with_to_xml - assert_equal "<i-am-xml/>", @response.body - end - - def test_rendering_with_object_location_should_set_header_with_url_for - ActionController::Routing::Routes.draw do |map| - map.resources :customers - map.connect ':controller/:action/:id' - end - - get :render_with_object_location - assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"] - end - - def test_render_call_to_partial_with_layout - get :render_call_to_partial_with_layout - assert_equal "Before (David)\nInside from partial (David)\nAfter", @response.body - end - - def test_render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout - get :render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout - assert_equal "Before (Anthony)\nInside from partial (Anthony)\nAfter\nBefore (David)\nInside from partial (David)\nAfter\nBefore (Ramm)\nInside from partial (Ramm)\nAfter", @response.body - end - - def test_using_layout_around_block - get :render_using_layout_around_block - assert_equal "Before (David)\nInside from block\nAfter", @response.body - end - - def test_using_layout_around_block_in_main_layout_and_within_content_for_layout - get :render_using_layout_around_block_in_main_layout_and_within_content_for_layout - assert_equal "Before (Anthony)\nInside from first block in layout\nAfter\nBefore (David)\nInside from block\nAfter\nBefore (Ramm)\nInside from second block in layout\nAfter\n", @response.body - end - - def test_using_layout_around_block_with_args - get :render_using_layout_around_block_with_args - assert_equal "Before\narg1arg2\nAfter", @response.body - end -end diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index 3008f5ca03..af7b5dde62 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -8,7 +8,22 @@ module Fun end end +class MockLogger + attr_reader :logged + + def initialize + @logged = [] + end + + def method_missing(method, *args) + @logged << args.first + end +end + class TestController < ActionController::Base + class LabellingFormBuilder < ActionView::Helpers::FormBuilder + end + layout :determine_layout def hello_world @@ -58,6 +73,57 @@ class TestController < ActionController::Base render :text => "hello world" end + def render_text_hello_world_with_layout + @variable_for_layout = ", I'm here!" + render :text => "hello world", :layout => true + end + + def hello_world_with_layout_false + render :layout => false + end + + def render_file_with_instance_variables + @secret = 'in the sauce' + path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb') + render :file => path + end + + def render_file_not_using_full_path + @secret = 'in the sauce' + render :file => 'test/render_file_with_ivar' + end + + def render_file_not_using_full_path_with_dot_in_path + @secret = 'in the sauce' + render :file => 'test/dot.directory/render_file_with_ivar' + end + + def render_file_from_template + @secret = 'in the sauce' + @path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) + end + + def render_file_with_locals + path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb') + render :file => path, :locals => {:secret => 'in the sauce'} + end + + def accessing_request_in_template + render :inline => "Hello: <%= request.host %>" + end + + def accessing_logger_in_template + render :inline => "<%= logger.class %>" + end + + def accessing_action_name_in_template + render :inline => "<%= action_name %>" + end + + def accessing_controller_name_in_template + render :inline => "<%= controller_name %>" + end + def render_json_hello_world render :json => {:hello => 'world'}.to_json end @@ -126,7 +192,7 @@ class TestController < ActionController::Base end def builder_layout_test - render :action => "hello" + render :action => "hello", :layout => "layouts/builder" end def builder_partial_test @@ -168,8 +234,232 @@ class TestController < ActionController::Base @foo = render_to_string :inline => "this is a test" end - def partial - render :partial => 'partial' + def default_render + if @alternate_default_render + @alternate_default_render.call + else + render + end + end + + def render_action_hello_world_as_symbol + render :action => :hello_world + end + + def layout_test_with_different_layout + render :action => "hello_world", :layout => "standard" + end + + def rendering_without_layout + render :action => "hello_world", :layout => false + end + + def layout_overriding_layout + render :action => "hello_world", :layout => "standard" + end + + def rendering_nothing_on_layout + render :nothing => true + end + + def render_to_string_with_assigns + @before = "i'm before the render" + render_to_string :text => "foo" + @after = "i'm after the render" + render :action => "test/hello_world" + end + + def render_to_string_with_exception + render_to_string :file => "exception that will not be caught - this will certainly not work" + end + + def render_to_string_with_caught_exception + @before = "i'm before the render" + begin + render_to_string :file => "exception that will be caught- hope my future instance vars still work!" + rescue + end + @after = "i'm after the render" + render :action => "test/hello_world" + end + + def accessing_params_in_template_with_layout + render :layout => nil, :inline => "Hello: <%= params[:name] %>" + end + + def render_with_explicit_template + render :template => "test/hello_world" + end + + def render_with_explicit_template_with_locals + render :template => "test/render_file_with_locals", :locals => { :secret => 'area51' } + end + + def double_render + render :text => "hello" + render :text => "world" + end + + def double_redirect + redirect_to :action => "double_render" + redirect_to :action => "double_render" + end + + def render_and_redirect + render :text => "hello" + redirect_to :action => "double_render" + end + + def render_to_string_and_render + @stuff = render_to_string :text => "here is some cached stuff" + render :text => "Hi web users! #{@stuff}" + end + + def rendering_with_conflicting_local_vars + @name = "David" + def @template.name() nil end + render :action => "potential_conflicts" + end + + def hello_world_from_rxml_using_action + render :action => "hello_world_from_rxml.builder" + end + + def hello_world_from_rxml_using_template + render :template => "test/hello_world_from_rxml.builder" + end + + module RenderTestHelper + def rjs_helper_method_from_module + page.visual_effect :highlight + end + end + + helper RenderTestHelper + helper do + def rjs_helper_method(value) + page.visual_effect :highlight, value + end + end + + def enum_rjs_test + render :update do |page| + page.select('.product').each do |value| + page.rjs_helper_method_from_module + page.rjs_helper_method(value) + page.sortable(value, :url => { :action => "order" }) + page.draggable(value) + end + end + end + + def delete_with_js + @project_id = 4 + end + + def render_js_with_explicit_template + @project_id = 4 + render :template => 'test/delete_with_js' + end + + def render_js_with_explicit_action_template + @project_id = 4 + render :action => 'delete_with_js' + end + + def update_page + render :update do |page| + page.replace_html 'balance', '$37,000,000.00' + page.visual_effect :highlight, 'balance' + end + end + + def update_page_with_instance_variables + @money = '$37,000,000.00' + @div_id = 'balance' + render :update do |page| + page.replace_html @div_id, @money + page.visual_effect :highlight, @div_id + end + end + + def update_page_with_view_method + render :update do |page| + page.replace_html 'person', pluralize(2, 'person') + end + end + + def action_talk_to_layout + # Action template sets variable that's picked up by layout + end + + def render_text_with_assigns + @hello = "world" + render :text => "foo" + end + + def yield_content_for + render :action => "content_for", :layout => "yield" + end + + def render_content_type_from_body + response.content_type = Mime::RSS + render :text => "hello world!" + end + + def head_with_location_header + head :location => "/foo" + end + + def head_with_symbolic_status + head :status => params[:status].intern + end + + def head_with_integer_status + head :status => params[:status].to_i + end + + def head_with_string_status + head :status => params[:status] + end + + def head_with_custom_header + head :x_custom_header => "something" + end + + def head_with_status_code_first + head :forbidden, :x_custom_header => "something" + end + + def render_with_location + render :xml => "<hello/>", :location => "http://example.com", :status => 201 + end + + def render_with_object_location + customer = Customer.new("Some guy", 1) + render :xml => "<customer/>", :location => customer_url(customer), :status => :created + end + + def render_with_to_xml + to_xmlable = Class.new do + def to_xml + "<i-am-xml/>" + end + end.new + + render :xml => to_xmlable + end + + def render_using_layout_around_block + render :action => "using_layout_around_block" + end + + def render_using_layout_around_block_with_args + render :action => "using_layout_around_block_with_args" + end + + def render_using_layout_around_block_in_main_layout_and_within_content_for_layout + render :action => "using_layout_around_block", :layout => "layouts/block_with_layout" end def partial_dot_html @@ -192,12 +482,8 @@ class TestController < ActionController::Base end end - def default_render - if @alternate_default_render - @alternate_default_render.call - else - render - end + def partial + render :partial => 'partial' end def render_alternate_default @@ -209,14 +495,126 @@ class TestController < ActionController::Base end end - def rescue_action(e) raise end + def partial_only_with_layout + render :partial => "partial_only", :layout => true + end + + def render_to_string_with_partial + @partial_only = render_to_string :partial => "partial_only" + @partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") } + render :action => "test/hello_world" + end + + def partial_with_counter + render :partial => "counter", :locals => { :counter_counter => 5 } + end + + def partial_with_locals + render :partial => "customer", :locals => { :customer => Customer.new("david") } + end + + def partial_with_form_builder + render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, @template, {}, Proc.new {}) + end + + def partial_with_form_builder_subclass + render :partial => LabellingFormBuilder.new(:post, nil, @template, {}, Proc.new {}) + end + + def partial_collection + render :partial => "customer", :collection => [ Customer.new("david"), Customer.new("mary") ] + end + + def partial_collection_with_as + render :partial => "customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :customer + end + + def partial_collection_with_counter + render :partial => "customer_counter", :collection => [ Customer.new("david"), Customer.new("mary") ] + end + + def partial_collection_with_locals + render :partial => "customer_greeting", :collection => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } + end + + def partial_collection_with_spacer + render :partial => "customer", :spacer_template => "partial_only", :collection => [ Customer.new("david"), Customer.new("mary") ] + end + + def partial_collection_shorthand_with_locals + render :partial => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } + end + + def partial_collection_shorthand_with_different_types_of_records + render :partial => [ + BadCustomer.new("mark"), + GoodCustomer.new("craig"), + BadCustomer.new("john"), + GoodCustomer.new("zach"), + GoodCustomer.new("brandon"), + BadCustomer.new("dan") ], + :locals => { :greeting => "Bonjour" } + end + + def empty_partial_collection + render :partial => "customer", :collection => [] + end + + def partial_collection_shorthand_with_different_types_of_records_with_counter + partial_collection_shorthand_with_different_types_of_records + end + + def missing_partial + render :partial => 'thisFileIsntHere' + end + + def partial_with_hash_object + render :partial => "hash_object", :object => {:first_name => "Sam"} + end + + def partial_hash_collection + render :partial => "hash_object", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ] + end + + def partial_hash_collection_with_locals + render :partial => "hash_greeting", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ], :locals => { :greeting => "Hola" } + end + + def partial_with_implicit_local_assignment + @customer = Customer.new("Marcel") + render :partial => "customer" + end + + def render_call_to_partial_with_layout + render :action => "calling_partial_with_layout" + end + + def render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout + render :action => "calling_partial_with_layout", :layout => "layouts/partial_with_layout" + end + + def rescue_action(e) + raise + end private def determine_layout case action_name - when "layout_test"; "layouts/standard" - when "builder_layout_test"; "layouts/builder" - when "render_symbol_json"; "layouts/standard" # to make sure layouts don't interfere + when "hello_world", "layout_test", "rendering_without_layout", + "rendering_nothing_on_layout", "render_text_hello_world", + "render_text_hello_world_with_layout", + "hello_world_with_layout_false", + "partial_only", "partial_only_with_layout", + "accessing_params_in_template", + "accessing_params_in_template_with_layout", + "render_with_explicit_template", + "render_js_with_explicit_template", + "render_js_with_explicit_action_template", + "delete_with_js", "update_page", "update_page_with_instance_variables" + + "layouts/standard" + when "action_talk_to_layout", "layout_overriding_layout" + "layouts/talk_from_action" end end end @@ -227,13 +625,24 @@ class RenderTest < Test::Unit::TestCase @response = ActionController::TestResponse.new @controller = TestController.new + # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get + # a more accurate simulation of what happens in "real life". + @controller.logger = Logger.new(nil) + @request.host = "www.nextangle.com" end def test_simple_show get :hello_world assert_response 200 + assert_response :success assert_template "test/hello_world" + assert_equal "<html>Hello world!</html>", @response.body + end + + def test_renders_default_template_for_missing_action + get :'hyphen-ated' + assert_template 'test/hyphen-ated' end def test_render @@ -290,6 +699,41 @@ class RenderTest < Test::Unit::TestCase assert_equal "hello world", @response.body end + def test_do_with_render_text_and_layout + get :render_text_hello_world_with_layout + assert_equal "<html>hello world, I'm here!</html>", @response.body + end + + def test_do_with_render_action_and_layout_false + get :hello_world_with_layout_false + assert_equal 'Hello world!', @response.body + end + + def test_render_file_with_instance_variables + get :render_file_with_instance_variables + assert_equal "The secret is in the sauce\n", @response.body + end + + def test_render_file_not_using_full_path + get :render_file_not_using_full_path + assert_equal "The secret is in the sauce\n", @response.body + end + + def test_render_file_not_using_full_path_with_dot_in_path + get :render_file_not_using_full_path_with_dot_in_path + assert_equal "The secret is in the sauce\n", @response.body + end + + def test_render_file_with_locals + get :render_file_with_locals + assert_equal "The secret is in the sauce\n", @response.body + end + + def test_render_file_from_template + get :render_file_from_template + assert_equal "The secret is in the sauce\n", @response.body + end + def test_render_json get :render_json_hello_world assert_equal '{"hello": "world"}', @response.body @@ -317,6 +761,7 @@ class RenderTest < Test::Unit::TestCase def test_render_custom_code get :render_custom_code assert_response 404 + assert_response :missing assert_equal 'hello world', @response.body end @@ -355,6 +800,26 @@ class RenderTest < Test::Unit::TestCase assert_raises(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout } end + def test_access_to_request_in_view + get :accessing_request_in_template + assert_equal "Hello: www.nextangle.com", @response.body + end + + def test_access_to_logger_in_view + get :accessing_logger_in_template + assert_equal "Logger", @response.body + end + + def test_access_to_action_name_in_view + get :accessing_action_name_in_template + assert_equal "accessing_action_name_in_template", @response.body + end + + def test_access_to_controller_name_in_view + get :accessing_controller_name_in_template + assert_equal "test", @response.body # name is explicitly set to 'test' inside the controller. + end + def test_render_xml get :render_xml_hello assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body @@ -371,6 +836,19 @@ class RenderTest < Test::Unit::TestCase assert_equal "<test>\n <hello/>\n</test>\n", @response.body end + def test_enum_rjs_test + get :enum_rjs_test + body = %{ + $$(".product").each(function(value, index) { + new Effect.Highlight(element,{}); + new Effect.Highlight(value,{}); + Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value)})}}); + new Draggable(value, {}); + }); + }.gsub(/^ /, '').strip + assert_equal body, @response.body + end + def test_layout_rendering get :layout_test assert_equal "<html>Hello world!</html>", @response.body @@ -381,14 +859,9 @@ class RenderTest < Test::Unit::TestCase assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body end - # def test_partials_list - # get :partials_list - # assert_equal "goodbyeHello: davidHello: marygoodbye\n", process_request.body - # end - - def test_partial_only - get :partial_only - assert_equal "only partial", @response.body + def test_partials_list + get :partials_list + assert_equal "goodbyeHello: davidHello: marygoodbye\n", @response.body end def test_render_to_string @@ -438,6 +911,252 @@ class RenderTest < Test::Unit::TestCase assert_equal '<test>passed formatted html erb</test>', @response.body end + def test_should_render_xml_but_keep_custom_content_type + get :render_xml_with_custom_content_type + assert_equal "application/atomsvc+xml", @response.content_type + end + + def test_render_with_default_from_accept_header + xhr :get, :greeting + assert_equal "$(\"body\").visualEffect(\"highlight\");", @response.body + end + + def test_render_rjs_with_default + get :delete_with_js + assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body + end + + def test_render_rjs_template_explicitly + get :render_js_with_explicit_template + assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body + end + + def test_rendering_rjs_action_explicitly + get :render_js_with_explicit_action_template + assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body + end + + def test_layout_test_with_different_layout + get :layout_test_with_different_layout + assert_equal "<html>Hello world!</html>", @response.body + end + + def test_rendering_without_layout + get :rendering_without_layout + assert_equal "Hello world!", @response.body + end + + def test_layout_overriding_layout + get :layout_overriding_layout + assert_no_match %r{<title>}, @response.body + end + + def test_rendering_nothing_on_layout + get :rendering_nothing_on_layout + assert_equal " ", @response.body + end + + def test_render_to_string + assert_not_deprecated { get :hello_in_a_string } + assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body + end + + def test_render_to_string_doesnt_break_assigns + get :render_to_string_with_assigns + assert_equal "i'm before the render", assigns(:before) + assert_equal "i'm after the render", assigns(:after) + end + + def test_bad_render_to_string_still_throws_exception + assert_raises(ActionView::MissingTemplate) { get :render_to_string_with_exception } + end + + def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns + assert_nothing_raised { get :render_to_string_with_caught_exception } + assert_equal "i'm before the render", assigns(:before) + assert_equal "i'm after the render", assigns(:after) + end + + def test_accessing_params_in_template_with_layout + get :accessing_params_in_template_with_layout, :name => "David" + assert_equal "<html>Hello: David</html>", @response.body + end + + def test_render_with_explicit_template + get :render_with_explicit_template + assert_response :success + end + + def test_double_render + assert_raises(ActionController::DoubleRenderError) { get :double_render } + end + + def test_double_redirect + assert_raises(ActionController::DoubleRenderError) { get :double_redirect } + end + + def test_render_and_redirect + assert_raises(ActionController::DoubleRenderError) { get :render_and_redirect } + end + + # specify the one exception to double render rule - render_to_string followed by render + def test_render_to_string_and_render + get :render_to_string_and_render + assert_equal("Hi web users! here is some cached stuff", @response.body) + end + + def test_rendering_with_conflicting_local_vars + get :rendering_with_conflicting_local_vars + assert_equal("First: David\nSecond: Stephan\nThird: David\nFourth: David\nFifth: ", @response.body) + end + + def test_action_talk_to_layout + get :action_talk_to_layout + assert_equal "<title>Talking to the layout</title>\nAction was here!", @response.body + end + + def test_render_text_with_assigns + get :render_text_with_assigns + assert_equal "world", assigns["hello"] + end + + def test_template_with_locals + get :render_with_explicit_template_with_locals + assert_equal "The secret is area51\n", @response.body + end + + def test_update_page + get :update_page + assert_template nil + assert_equal 'text/javascript; charset=utf-8', @response.headers['type'] + assert_equal 2, @response.body.split($/).length + end + + def test_update_page_with_instance_variables + get :update_page_with_instance_variables + assert_template nil + assert_equal 'text/javascript; charset=utf-8', @response.headers['type'] + assert_match /balance/, @response.body + assert_match /\$37/, @response.body + end + + def test_update_page_with_view_method + get :update_page_with_view_method + assert_template nil + assert_equal 'text/javascript; charset=utf-8', @response.headers['type'] + assert_match /2 people/, @response.body + end + + def test_yield_content_for + assert_not_deprecated { get :yield_content_for } + assert_equal "<title>Putting stuff in the title!</title>\n\nGreat stuff!\n", @response.body + end + + def test_overwritting_rendering_relative_file_with_extension + get :hello_world_from_rxml_using_template + assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body + + get :hello_world_from_rxml_using_action + assert_equal "<html>\n <p>Hello</p>\n</html>\n", @response.body + end + + def test_head_with_location_header + get :head_with_location_header + assert @response.body.blank? + assert_equal "/foo", @response.headers["Location"] + assert_response :ok + end + + def test_head_with_custom_header + get :head_with_custom_header + assert @response.body.blank? + assert_equal "something", @response.headers["X-Custom-Header"] + assert_response :ok + end + + def test_head_with_symbolic_status + get :head_with_symbolic_status, :status => "ok" + assert_equal "200 OK", @response.headers["Status"] + assert_response :ok + + get :head_with_symbolic_status, :status => "not_found" + assert_equal "404 Not Found", @response.headers["Status"] + assert_response :not_found + + ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE.each do |status, code| + get :head_with_symbolic_status, :status => status.to_s + assert_equal code, @response.response_code + assert_response status + end + end + + def test_head_with_integer_status + ActionController::StatusCodes::STATUS_CODES.each do |code, message| + get :head_with_integer_status, :status => code.to_s + assert_equal message, @response.message + end + end + + def test_head_with_string_status + get :head_with_string_status, :status => "404 Eat Dirt" + assert_equal 404, @response.response_code + assert_equal "Eat Dirt", @response.message + assert_response :not_found + end + + def test_head_with_status_code_first + get :head_with_status_code_first + assert_equal 403, @response.response_code + assert_equal "Forbidden", @response.message + assert_equal "something", @response.headers["X-Custom-Header"] + assert_response :forbidden + end + + def test_rendering_with_location_should_set_header + get :render_with_location + assert_equal "http://example.com", @response.headers["Location"] + end + + def test_rendering_xml_should_call_to_xml_if_possible + get :render_with_to_xml + assert_equal "<i-am-xml/>", @response.body + end + + def test_rendering_with_object_location_should_set_header_with_url_for + ActionController::Routing::Routes.draw do |map| + map.resources :customers + map.connect ':controller/:action/:id' + end + + get :render_with_object_location + assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"] + end + + def test_should_use_implicit_content_type + get :implicit_content_type, :format => 'atom' + assert_equal Mime::ATOM, @response.content_type + end + + def test_using_layout_around_block + get :render_using_layout_around_block + assert_equal "Before (David)\nInside from block\nAfter", @response.body + end + + def test_using_layout_around_block_in_main_layout_and_within_content_for_layout + get :render_using_layout_around_block_in_main_layout_and_within_content_for_layout + assert_equal "Before (Anthony)\nInside from first block in layout\nAfter\nBefore (David)\nInside from block\nAfter\nBefore (Ramm)\nInside from second block in layout\nAfter\n", @response.body + end + + def test_using_layout_around_block_with_args + get :render_using_layout_around_block_with_args + assert_equal "Before\narg1arg2\nAfter", @response.body + end + + def test_partial_only + get :partial_only + assert_equal "only partial", @response.body + end + def test_should_render_html_formatted_partial get :partial assert_equal 'partial html', @response.body @@ -468,14 +1187,115 @@ class RenderTest < Test::Unit::TestCase assert_equal %(Element.replace("foo", "partial html");), @response.body end - def test_should_render_xml_but_keep_custom_content_type - get :render_xml_with_custom_content_type - assert_equal "application/atomsvc+xml", @response.content_type + def test_partial_only_with_layout + get :partial_only_with_layout + assert_equal "<html>only partial</html>", @response.body end - def test_should_use_implicit_content_type - get :implicit_content_type, :format => 'atom' - assert_equal Mime::ATOM, @response.content_type + def test_render_to_string_partial + get :render_to_string_with_partial + assert_equal "only partial", assigns(:partial_only) + assert_equal "Hello: david", assigns(:partial_with_locals) + end + + def test_partial_with_counter + get :partial_with_counter + assert_equal "5", @response.body + end + + def test_partial_with_locals + get :partial_with_locals + assert_equal "Hello: david", @response.body + end + + def test_partial_with_form_builder + get :partial_with_form_builder + assert_match(/<label/, @response.body) + assert_template('test/_form') + end + + def test_partial_with_form_builder_subclass + get :partial_with_form_builder_subclass + assert_match(/<label/, @response.body) + assert_template('test/_labelling_form') + end + + def test_partial_collection + get :partial_collection + assert_equal "Hello: davidHello: mary", @response.body + end + + def test_partial_collection_with_as + get :partial_collection_with_as + assert_equal "david david davidmary mary mary", @response.body + end + + def test_partial_collection_with_counter + get :partial_collection_with_counter + assert_equal "david0mary1", @response.body + end + + def test_partial_collection_with_locals + get :partial_collection_with_locals + assert_equal "Bonjour: davidBonjour: mary", @response.body + end + + def test_partial_collection_with_spacer + get :partial_collection_with_spacer + assert_equal "Hello: davidonly partialHello: mary", @response.body + end + + def test_partial_collection_shorthand_with_locals + get :partial_collection_shorthand_with_locals + assert_equal "Bonjour: davidBonjour: mary", @response.body + end + + def test_partial_collection_shorthand_with_different_types_of_records + get :partial_collection_shorthand_with_different_types_of_records + assert_equal "Bonjour bad customer: mark0Bonjour good customer: craig1Bonjour bad customer: john2Bonjour good customer: zach3Bonjour good customer: brandon4Bonjour bad customer: dan5", @response.body + end + + def test_empty_partial_collection + get :empty_partial_collection + assert_equal " ", @response.body + end + + def test_partial_with_hash_object + get :partial_with_hash_object + assert_equal "Sam\nmaS\n", @response.body + end + + def test_hash_partial_collection + get :partial_hash_collection + assert_equal "Pratik\nkitarP\nAmy\nymA\n", @response.body + end + + def test_partial_hash_collection_with_locals + get :partial_hash_collection_with_locals + assert_equal "Hola: PratikHola: Amy", @response.body + end + + def test_partial_with_implicit_local_assignment + assert_deprecated do + get :partial_with_implicit_local_assignment + assert_equal "Hello: Marcel", @response.body + end + end + + def test_render_missing_partial_template + assert_raises(ActionView::MissingTemplate) do + get :missing_partial + end + end + + def test_render_call_to_partial_with_layout + get :render_call_to_partial_with_layout + assert_equal "Before (David)\nInside from partial (David)\nAfter", @response.body + end + + def test_render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout + get :render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout + assert_equal "Before (Anthony)\nInside from partial (Anthony)\nAfter\nBefore (David)\nInside from partial (David)\nAfter\nBefore (Ramm)\nInside from partial (Ramm)\nAfter", @response.body end end @@ -501,6 +1321,12 @@ class EtagRenderTest < Test::Unit::TestCase assert @response.body.empty? end + def test_render_against_etag_request_should_have_no_content_length_when_match + @request.if_none_match = etag_for("hello david") + get :render_hello_world_from_variable + assert !@response.headers.has_key?("Content-Length") + end + def test_render_against_etag_request_should_200_when_no_match @request.if_none_match = etag_for("hello somewhere else") get :render_hello_world_from_variable @@ -577,3 +1403,21 @@ class LastModifiedRenderTest < Test::Unit::TestCase assert_equal @last_modified, @response.headers['Last-Modified'] end end + +class RenderingLoggingTest < Test::Unit::TestCase + def setup + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + @controller = TestController.new + + @request.host = "www.nextangle.com" + end + + def test_logger_prints_layout_and_template_rendering_info + @controller.logger = MockLogger.new + get :layout_test + logged = @controller.logger.logged.find_all {|l| l =~ /render/i } + assert_equal "Rendering template within layouts/standard", logged[0] + assert_equal "Rendering test/hello_world", logged[1] + end +end diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index e153b0cc98..1fea82e564 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -264,6 +264,19 @@ class ResourcesTest < Test::Unit::TestCase end end + def test_array_as_collection_or_member_method_value + with_restful_routing :messages, :collection => { :search => [:get, :post] }, :member => { :toggle => [:get, :post] } do + assert_restful_routes_for :messages do |options| + [:get, :post].each do |method| + assert_recognizes(options.merge(:action => 'search'), :path => "/messages/search", :method => method) + end + [:get, :post].each do |method| + assert_recognizes(options.merge(:action => 'toggle', :id => '1'), :path => '/messages/1/toggle', :method => method) + end + end + end + end + def test_with_new_action with_restful_routing :messages, :new => { :preview => :post } do preview_options = {:action => 'preview'} @@ -366,6 +379,31 @@ class ResourcesTest < Test::Unit::TestCase end end + def test_shallow_nested_restful_routes + with_routing do |set| + set.draw do |map| + map.resources :threads, :shallow => true do |map| + map.resources :messages do |map| + map.resources :comments + end + end + end + + assert_simply_restful_for :threads, + :shallow => true + assert_simply_restful_for :messages, + :name_prefix => 'thread_', + :path_prefix => 'threads/1/', + :shallow => true, + :options => { :thread_id => '1' } + assert_simply_restful_for :comments, + :name_prefix => 'message_', + :path_prefix => 'messages/2/', + :shallow => true, + :options => { :message_id => '2' } + end + end + def test_restful_routes_dont_generate_duplicates with_restful_routing :messages do routes = ActionController::Routing::Routes.routes @@ -416,6 +454,32 @@ class ResourcesTest < Test::Unit::TestCase end end + def test_resources_has_many_hash_should_become_nested_resources + with_routing do |set| + set.draw do |map| + map.resources :threads, :has_many => { :messages => [ :comments, { :authors => :threads } ] } + end + + assert_simply_restful_for :threads + assert_simply_restful_for :messages, :name_prefix => "thread_", :path_prefix => 'threads/1/', :options => { :thread_id => '1' } + assert_simply_restful_for :comments, :name_prefix => "thread_message_", :path_prefix => 'threads/1/messages/1/', :options => { :thread_id => '1', :message_id => '1' } + assert_simply_restful_for :authors, :name_prefix => "thread_message_", :path_prefix => 'threads/1/messages/1/', :options => { :thread_id => '1', :message_id => '1' } + assert_simply_restful_for :threads, :name_prefix => "thread_message_author_", :path_prefix => 'threads/1/messages/1/authors/1/', :options => { :thread_id => '1', :message_id => '1', :author_id => '1' } + end + end + + def test_shallow_resource_has_many_should_become_shallow_nested_resources + with_routing do |set| + set.draw do |map| + map.resources :messages, :has_many => [ :comments, :authors ], :shallow => true + end + + assert_simply_restful_for :messages, :shallow => true + assert_simply_restful_for :comments, :name_prefix => "message_", :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' } + assert_simply_restful_for :authors, :name_prefix => "message_", :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' } + end + end + def test_resource_has_one_should_become_nested_resources with_routing do |set| set.draw do |map| @@ -427,6 +491,17 @@ class ResourcesTest < Test::Unit::TestCase end end + def test_shallow_resource_has_one_should_become_shallow_nested_resources + with_routing do |set| + set.draw do |map| + map.resources :messages, :has_one => :logo, :shallow => true + end + + assert_simply_restful_for :messages, :shallow => true + assert_singleton_restful_for :logo, :name_prefix => 'message_', :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' } + end + end + def test_singleton_resource_with_member_action [:put, :post].each do |method| with_singleton_resources :account, :member => { :reset => method } do @@ -731,6 +806,13 @@ class ResourcesTest < Test::Unit::TestCase options[:options] ||= {} options[:options][:controller] = options[:controller] || controller_name.to_s + if options[:shallow] + options[:shallow_options] ||= {} + options[:shallow_options][:controller] = options[:options][:controller] + else + options[:shallow_options] = options[:options] + end + new_action = ActionController::Base.resources_path_names[:new] || "new" edit_action = ActionController::Base.resources_path_names[:edit] || "edit" if options[:path_names] @@ -738,8 +820,10 @@ class ResourcesTest < Test::Unit::TestCase edit_action = options[:path_names][:edit] if options[:path_names][:edit] end - collection_path = "/#{options[:path_prefix]}#{options[:as] || controller_name}" - member_path = "#{collection_path}/1" + path = "#{options[:as] || controller_name}" + collection_path = "/#{options[:path_prefix]}#{path}" + shallow_path = "/#{options[:path_prefix] unless options[:shallow]}#{path}" + member_path = "#{shallow_path}/1" new_path = "#{collection_path}/#{new_action}" edit_member_path = "#{member_path}/#{edit_action}" formatted_edit_member_path = "#{member_path}/#{edit_action}.xml" @@ -747,10 +831,13 @@ class ResourcesTest < Test::Unit::TestCase with_options(options[:options]) do |controller| controller.assert_routing collection_path, :action => 'index' controller.assert_routing new_path, :action => 'new' - controller.assert_routing member_path, :action => 'show', :id => '1' - controller.assert_routing edit_member_path, :action => 'edit', :id => '1' controller.assert_routing "#{collection_path}.xml", :action => 'index', :format => 'xml' controller.assert_routing "#{new_path}.xml", :action => 'new', :format => 'xml' + end + + with_options(options[:shallow_options]) do |controller| + controller.assert_routing member_path, :action => 'show', :id => '1' + controller.assert_routing edit_member_path, :action => 'edit', :id => '1' controller.assert_routing "#{member_path}.xml", :action => 'show', :id => '1', :format => 'xml' controller.assert_routing formatted_edit_member_path, :action => 'edit', :id => '1', :format => 'xml' end @@ -758,18 +845,18 @@ class ResourcesTest < Test::Unit::TestCase assert_recognizes(options[:options].merge(:action => 'index'), :path => collection_path, :method => :get) assert_recognizes(options[:options].merge(:action => 'new'), :path => new_path, :method => :get) assert_recognizes(options[:options].merge(:action => 'create'), :path => collection_path, :method => :post) - assert_recognizes(options[:options].merge(:action => 'show', :id => '1'), :path => member_path, :method => :get) - assert_recognizes(options[:options].merge(:action => 'edit', :id => '1'), :path => edit_member_path, :method => :get) - assert_recognizes(options[:options].merge(:action => 'update', :id => '1'), :path => member_path, :method => :put) - assert_recognizes(options[:options].merge(:action => 'destroy', :id => '1'), :path => member_path, :method => :delete) - - assert_recognizes(options[:options].merge(:action => 'index', :format => 'xml'), :path => "#{collection_path}.xml", :method => :get) - assert_recognizes(options[:options].merge(:action => 'new', :format => 'xml'), :path => "#{new_path}.xml", :method => :get) - assert_recognizes(options[:options].merge(:action => 'create', :format => 'xml'), :path => "#{collection_path}.xml", :method => :post) - assert_recognizes(options[:options].merge(:action => 'show', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :get) - assert_recognizes(options[:options].merge(:action => 'edit', :id => '1', :format => 'xml'), :path => formatted_edit_member_path, :method => :get) - assert_recognizes(options[:options].merge(:action => 'update', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :put) - assert_recognizes(options[:options].merge(:action => 'destroy', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :delete) + assert_recognizes(options[:shallow_options].merge(:action => 'show', :id => '1'), :path => member_path, :method => :get) + assert_recognizes(options[:shallow_options].merge(:action => 'edit', :id => '1'), :path => edit_member_path, :method => :get) + assert_recognizes(options[:shallow_options].merge(:action => 'update', :id => '1'), :path => member_path, :method => :put) + assert_recognizes(options[:shallow_options].merge(:action => 'destroy', :id => '1'), :path => member_path, :method => :delete) + + assert_recognizes(options[:options].merge(:action => 'index', :format => 'xml'), :path => "#{collection_path}.xml", :method => :get) + assert_recognizes(options[:options].merge(:action => 'new', :format => 'xml'), :path => "#{new_path}.xml", :method => :get) + assert_recognizes(options[:options].merge(:action => 'create', :format => 'xml'), :path => "#{collection_path}.xml", :method => :post) + assert_recognizes(options[:shallow_options].merge(:action => 'show', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :get) + assert_recognizes(options[:shallow_options].merge(:action => 'edit', :id => '1', :format => 'xml'), :path => formatted_edit_member_path, :method => :get) + assert_recognizes(options[:shallow_options].merge(:action => 'update', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :put) + assert_recognizes(options[:shallow_options].merge(:action => 'destroy', :id => '1', :format => 'xml'), :path => "#{member_path}.xml", :method => :delete) yield options[:options] if block_given? end @@ -785,14 +872,24 @@ class ResourcesTest < Test::Unit::TestCase options[:options] ||= {} options[:options][:controller] = options[:controller] || controller_name.to_s + if options[:shallow] + options[:shallow_options] ||= {} + options[:shallow_options][:controller] = options[:options][:controller] + else + options[:shallow_options] = options[:options] + end + @controller = "#{options[:options][:controller].camelize}Controller".constantize.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new get :index, options[:options] options[:options].delete :action - full_prefix = "/#{options[:path_prefix]}#{options[:as] || controller_name}" + path = "#{options[:as] || controller_name}" + shallow_path = "/#{options[:path_prefix] unless options[:shallow]}#{path}" + full_path = "/#{options[:path_prefix]}#{path}" name_prefix = options[:name_prefix] + shallow_prefix = "#{options[:name_prefix] unless options[:shallow]}" new_action = "new" edit_action = "edit" @@ -801,15 +898,15 @@ class ResourcesTest < Test::Unit::TestCase edit_action = options[:path_names][:edit] || "edit" end - assert_named_route "#{full_prefix}", "#{name_prefix}#{controller_name}_path", options[:options] - assert_named_route "#{full_prefix}.xml", "formatted_#{name_prefix}#{controller_name}_path", options[:options].merge( :format => 'xml') - assert_named_route "#{full_prefix}/1", "#{name_prefix}#{singular_name}_path", options[:options].merge(:id => '1') - assert_named_route "#{full_prefix}/1.xml", "formatted_#{name_prefix}#{singular_name}_path", options[:options].merge(:id => '1', :format => 'xml') + assert_named_route "#{full_path}", "#{name_prefix}#{controller_name}_path", options[:options] + assert_named_route "#{full_path}.xml", "formatted_#{name_prefix}#{controller_name}_path", options[:options].merge(:format => 'xml') + assert_named_route "#{shallow_path}/1", "#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1') + assert_named_route "#{shallow_path}/1.xml", "formatted_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml') - assert_named_route "#{full_prefix}/#{new_action}", "new_#{name_prefix}#{singular_name}_path", options[:options] - assert_named_route "#{full_prefix}/#{new_action}.xml", "formatted_new_#{name_prefix}#{singular_name}_path", options[:options].merge( :format => 'xml') - assert_named_route "#{full_prefix}/1/#{edit_action}", "edit_#{name_prefix}#{singular_name}_path", options[:options].merge(:id => '1') - assert_named_route "#{full_prefix}/1/#{edit_action}.xml", "formatted_edit_#{name_prefix}#{singular_name}_path", options[:options].merge(:id => '1', :format => 'xml') + assert_named_route "#{full_path}/#{new_action}", "new_#{name_prefix}#{singular_name}_path", options[:options] + assert_named_route "#{full_path}/#{new_action}.xml", "formatted_new_#{name_prefix}#{singular_name}_path", options[:options].merge(:format => 'xml') + assert_named_route "#{shallow_path}/1/#{edit_action}", "edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1') + assert_named_route "#{shallow_path}/1/#{edit_action}.xml", "formatted_edit_#{shallow_prefix}#{singular_name}_path", options[:shallow_options].merge(:id => '1', :format => 'xml') yield options[:options] if block_given? end diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 6cf134c26f..8bb1c49cbd 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -1297,6 +1297,29 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do end end + def test_recognize_array_of_methods + Object.const_set(:BooksController, Class.new(ActionController::Base)) + rs.draw do |r| + r.connect '/match', :controller => 'books', :action => 'get_or_post', :conditions => { :method => [:get, :post] } + r.connect '/match', :controller => 'books', :action => 'not_get_or_post' + end + + @request = ActionController::TestRequest.new + @request.env["REQUEST_METHOD"] = 'POST' + @request.request_uri = "/match" + assert_nothing_raised { rs.recognize(@request) } + assert_equal 'get_or_post', @request.path_parameters[:action] + + # have to recreate or else the RouteSet uses a cached version: + @request = ActionController::TestRequest.new + @request.env["REQUEST_METHOD"] = 'PUT' + @request.request_uri = "/match" + assert_nothing_raised { rs.recognize(@request) } + assert_equal 'not_get_or_post', @request.path_parameters[:action] + ensure + Object.send(:remove_const, :BooksController) rescue nil + end + def test_subpath_recognized Object.const_set(:SubpathBooksController, Class.new(ActionController::Base)) @@ -1671,6 +1694,12 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do controller.send(:multi_url, 7, "hello", 5, :baz => "bar") end + def test_named_route_url_method_with_ordered_parameters_and_empty_hash + controller = setup_named_route_test + assert_equal "http://named.route.test/people/go/7/hello/joe/5", + controller.send(:multi_url, 7, "hello", 5, {}) + end + def test_named_route_url_method_with_no_positional_arguments controller = setup_named_route_test assert_equal "http://named.route.test/people?baz=bar", diff --git a/actionpack/test/template/prototype_helper_test.rb b/actionpack/test/template/prototype_helper_test.rb index abc9f930dd..a1f541fd7b 100644 --- a/actionpack/test/template/prototype_helper_test.rb +++ b/actionpack/test/template/prototype_helper_test.rb @@ -79,6 +79,8 @@ class PrototypeHelperTest < PrototypeHelperBaseTest link_to_remote("Remote outauthor", :failure => "alert(request.responseText)", :url => { :action => "whatnot", :a => '10', :b => '20' }) assert_dom_equal %(<a href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:false, evalScripts:true}); return false;\">Remote outauthor</a>), link_to_remote("Remote outauthor", :url => { :action => "whatnot" }, :type => :synchronous) + assert_dom_equal %(<a href=\"#\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true, insertion:'bottom'}); return false;\">Remote outauthor</a>), + link_to_remote("Remote outauthor", :url => { :action => "whatnot" }, :position => :bottom) end def test_link_to_remote_html_options @@ -91,6 +93,19 @@ class PrototypeHelperTest < PrototypeHelperBaseTest link_to_remote("Remote", { :url => { :action => "whatnot's" } }) end + def test_button_to_remote + assert_dom_equal %(<input class=\"fine\" type=\"button\" value=\"Remote outpost\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true});\" />), + button_to_remote("Remote outpost", { :url => { :action => "whatnot" }}, { :class => "fine" }) + assert_dom_equal %(<input type=\"button\" value=\"Remote outpost\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true, onComplete:function(request){alert(request.reponseText)}});\" />), + button_to_remote("Remote outpost", :complete => "alert(request.reponseText)", :url => { :action => "whatnot" }) + assert_dom_equal %(<input type=\"button\" value=\"Remote outpost\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true, onSuccess:function(request){alert(request.reponseText)}});\" />), + button_to_remote("Remote outpost", :success => "alert(request.reponseText)", :url => { :action => "whatnot" }) + assert_dom_equal %(<input type=\"button\" value=\"Remote outpost\" onclick=\"new Ajax.Request('http://www.example.com/whatnot', {asynchronous:true, evalScripts:true, onFailure:function(request){alert(request.reponseText)}});\" />), + button_to_remote("Remote outpost", :failure => "alert(request.reponseText)", :url => { :action => "whatnot" }) + assert_dom_equal %(<input type=\"button\" value=\"Remote outpost\" onclick=\"new Ajax.Request('http://www.example.com/whatnot?a=10&b=20', {asynchronous:true, evalScripts:true, onFailure:function(request){alert(request.reponseText)}});\" />), + button_to_remote("Remote outpost", :failure => "alert(request.reponseText)", :url => { :action => "whatnot", :a => '10', :b => '20' }) + end + def test_periodically_call_remote assert_dom_equal %(<script type="text/javascript">\n//<![CDATA[\nnew PeriodicalExecuter(function() {new Ajax.Updater('schremser_bier', 'http://www.example.com/mehr_bier', {asynchronous:true, evalScripts:true})}, 10)\n//]]>\n</script>), periodically_call_remote(:update => "schremser_bier", :url => { :action => "mehr_bier" }) diff --git a/actionpack/test/template/record_tag_helper_test.rb b/actionpack/test/template/record_tag_helper_test.rb index 34a200b933..67aa047745 100644 --- a/actionpack/test/template/record_tag_helper_test.rb +++ b/actionpack/test/template/record_tag_helper_test.rb @@ -34,6 +34,14 @@ class RecordTagHelperTest < ActionView::TestCase assert_dom_equal expected, actual end + def test_block_not_in_erb_multiple_calls + expected = %(<div class="post bar" id="post_45">#{@post.body}</div>) + actual = div_for(@post, :class => "bar") { @post.body } + assert_dom_equal expected, actual + actual = div_for(@post, :class => "bar") { @post.body } + assert_dom_equal expected, actual + end + def test_block_works_with_content_tag_for_in_erb __in_erb_template = '' expected = %(<tr class="post" id="post_45">#{@post.body}</tr>) diff --git a/activemodel/lib/active_model/state_machine/event.rb b/activemodel/lib/active_model/state_machine/event.rb index e8bc8ebdb7..8acde7fd47 100644 --- a/activemodel/lib/active_model/state_machine/event.rb +++ b/activemodel/lib/active_model/state_machine/event.rb @@ -2,15 +2,15 @@ module ActiveModel module StateMachine class Event attr_reader :name, :success - + def initialize(machine, name, options = {}, &block) @machine, @name, @transitions = machine, name, [] if machine - machine.klass.send(:define_method, "#{name.to_s}!") do |*args| + machine.klass.send(:define_method, "#{name}!") do |*args| machine.fire_event(name, self, true, *args) end - machine.klass.send(:define_method, "#{name.to_s}") do |*args| + machine.klass.send(:define_method, name.to_s) do |*args| machine.fire_event(name, self, false, *args) end end diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb index 7efe9901ca..460d2d82e5 100644 --- a/activemodel/lib/active_model/validations.rb +++ b/activemodel/lib/active_model/validations.rb @@ -4,7 +4,7 @@ module ActiveModel module Validations def self.included(base) # :nodoc: base.extend(ClassMethods) - base.send!(:include, ActiveSupport::Callbacks) + base.__send__(:include, ActiveSupport::Callbacks) base.define_callbacks :validate, :validate_on_create, :validate_on_update end diff --git a/activemodel/lib/active_model/validations/exclusion.rb b/activemodel/lib/active_model/validations/exclusion.rb index f3367abcf8..1592000fc7 100644 --- a/activemodel/lib/active_model/validations/exclusion.rb +++ b/activemodel/lib/active_model/validations/exclusion.rb @@ -26,7 +26,7 @@ module ActiveModel enum = configuration[:in] || configuration[:within] - raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?("include?") + raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?) validates_each(attr_names, configuration) do |record, attr_name, value| record.errors.add(attr_name, configuration[:message] % value) if enum.include?(value) diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb index 9fc1caaabe..9b4cb64307 100644 --- a/activemodel/lib/active_model/validations/inclusion.rb +++ b/activemodel/lib/active_model/validations/inclusion.rb @@ -26,7 +26,7 @@ module ActiveModel enum = configuration[:in] || configuration[:within] - raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?("include?") + raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?) validates_each(attr_names, configuration) do |record, attr_name, value| record.errors.add(attr_name, configuration[:message] % value) unless enum.include?(value) diff --git a/activemodel/lib/active_model/validations/uniqueness.rb b/activemodel/lib/active_model/validations/uniqueness.rb index 68cd6169e5..593d2cfd54 100644 --- a/activemodel/lib/active_model/validations/uniqueness.rb +++ b/activemodel/lib/active_model/validations/uniqueness.rb @@ -79,8 +79,8 @@ module ActiveModel results = finder_class.with_exclusive_scope do connection.select_all( construct_finder_sql( - :select => "#{attr_name}", - :from => "#{finder_class.quoted_table_name}", + :select => attr_name, + :from => finder_class.quoted_table_name, :conditions => [condition_sql, *condition_params] ) ) diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 12295ac799..58d0669770 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,9 @@ *Edge* +* Connection pooling. #936 [Nick Sieger] + +* Merge scoped :joins together instead of overwriting them. May expose scoping bugs in your code! #501 [Andrew White] + * before_save, before_validation and before_destroy callbacks that return false will now ROLLBACK the transaction. Previously this would have been committed before the processing was aborted. #891 [Xavier Noria] * Transactional migrations for databases which support them. #834 [divoxx, Adam Wiggins, Tarmo Tänav] diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 1af8ddcaf8..6405071354 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -878,10 +878,10 @@ module ActiveRecord method_name = "has_one_after_save_for_#{reflection.name}".to_sym define_method(method_name) do - association = instance_variable_get("#{ivar}") if instance_variable_defined?("#{ivar}") + association = instance_variable_get(ivar) if instance_variable_defined?(ivar) - if !association.nil? && (new_record? || association.new_record? || association["#{reflection.primary_key_name}"] != id) - association["#{reflection.primary_key_name}"] = id + if !association.nil? && (new_record? || association.new_record? || association[reflection.primary_key_name] != id) + association[reflection.primary_key_name] = id association.save(true) end end @@ -994,7 +994,7 @@ module ActiveRecord method_name = "polymorphic_belongs_to_before_save_for_#{reflection.name}".to_sym define_method(method_name) do - association = instance_variable_get("#{ivar}") if instance_variable_defined?("#{ivar}") + association = instance_variable_get(ivar) if instance_variable_defined?(ivar) if association && association.target if association.new_record? @@ -1002,8 +1002,8 @@ module ActiveRecord end if association.updated? - self["#{reflection.primary_key_name}"] = association.id - self["#{reflection.options[:foreign_type]}"] = association.class.base_class.name.to_s + self[reflection.primary_key_name] = association.id + self[reflection.options[:foreign_type]] = association.class.base_class.name.to_s end end end @@ -1015,7 +1015,7 @@ module ActiveRecord method_name = "belongs_to_before_save_for_#{reflection.name}".to_sym define_method(method_name) do - association = instance_variable_get("#{ivar}") if instance_variable_defined?("#{ivar}") + association = instance_variable_get(ivar) if instance_variable_defined?(ivar) if !association.nil? if association.new_record? @@ -1023,7 +1023,7 @@ module ActiveRecord end if association.updated? - self["#{reflection.primary_key_name}"] = association.id + self[reflection.primary_key_name] = association.id end end end @@ -1038,15 +1038,15 @@ module ActiveRecord method_name = "belongs_to_counter_cache_after_create_for_#{reflection.name}".to_sym define_method(method_name) do - association = send("#{reflection.name}") - association.class.increment_counter("#{cache_column}", send("#{reflection.primary_key_name}")) unless association.nil? + association = send(reflection.name) + association.class.increment_counter(cache_column, send(reflection.primary_key_name)) unless association.nil? end after_create method_name method_name = "belongs_to_counter_cache_before_destroy_for_#{reflection.name}".to_sym define_method(method_name) do - association = send("#{reflection.name}") - association.class.decrement_counter("#{cache_column}", send("#{reflection.primary_key_name}")) unless association.nil? + association = send(reflection.name) + association.class.decrement_counter(cache_column, send(reflection.primary_key_name)) unless association.nil? end before_destroy method_name @@ -1164,6 +1164,9 @@ module ActiveRecord # If true, duplicate associated objects will be ignored by accessors and query methods. # [:finder_sql] # Overwrite the default generated SQL statement used to fetch the association with a manual statement + # [:counter_sql] + # Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is + # specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>. # [:delete_sql] # Overwrite the default generated SQL statement used to remove links between the associated # classes with a manual statement. @@ -1300,7 +1303,11 @@ module ActiveRecord end define_method("#{reflection.name.to_s.singularize}_ids") do - send(reflection.name).map { |record| record.id } + if send(reflection.name).loaded? + send(reflection.name).map(&:id) + else + send(reflection.name).all(:select => "#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").map(&:id) + end end end @@ -1321,19 +1328,19 @@ module ActiveRecord end end end - + def add_single_associated_validation_callbacks(association_name) method_name = "validate_associated_records_for_#{association_name}".to_sym define_method(method_name) do association = instance_variable_get("@#{association_name}") if !association.nil? - errors.add "#{association_name}" unless association.target.nil? || association.valid? + errors.add association_name unless association.target.nil? || association.valid? end end - + validate method_name end - + def add_multiple_associated_validation_callbacks(association_name) method_name = "validate_associated_records_for_#{association_name}".to_sym ivar = "@#{association_name}" @@ -1349,7 +1356,7 @@ module ActiveRecord else association.target.select { |record| record.new_record? } end.each do |record| - errors.add "#{association_name}" unless record.valid? + errors.add association_name unless record.valid? end end end @@ -1369,7 +1376,7 @@ module ActiveRecord method_name = "after_create_or_update_associated_records_for_#{association_name}".to_sym define_method(method_name) do - association = instance_variable_get("#{ivar}") if instance_variable_defined?("#{ivar}") + association = instance_variable_get(ivar) if instance_variable_defined?(ivar) records_to_save = if @new_record_before_save association @@ -1436,7 +1443,7 @@ module ActiveRecord when :destroy method_name = "has_many_dependent_destroy_for_#{reflection.name}".to_sym define_method(method_name) do - send("#{reflection.name}").each { |o| o.destroy } + send(reflection.name).each { |o| o.destroy } end before_destroy method_name when :delete_all @@ -1455,22 +1462,22 @@ module ActiveRecord when :destroy method_name = "has_one_dependent_destroy_for_#{reflection.name}".to_sym define_method(method_name) do - association = send("#{reflection.name}") + association = send(reflection.name) association.destroy unless association.nil? end before_destroy method_name when :delete method_name = "has_one_dependent_delete_for_#{reflection.name}".to_sym define_method(method_name) do - association = send("#{reflection.name}") + association = send(reflection.name) association.class.delete(association.id) unless association.nil? end before_destroy method_name when :nullify method_name = "has_one_dependent_nullify_for_#{reflection.name}".to_sym define_method(method_name) do - association = send("#{reflection.name}") - association.update_attribute("#{reflection.primary_key_name}", nil) unless association.nil? + association = send(reflection.name) + association.update_attribute(reflection.primary_key_name, nil) unless association.nil? end before_destroy method_name else @@ -1485,14 +1492,14 @@ module ActiveRecord when :destroy method_name = "belongs_to_dependent_destroy_for_#{reflection.name}".to_sym define_method(method_name) do - association = send("#{reflection.name}") + association = send(reflection.name) association.destroy unless association.nil? end before_destroy method_name when :delete method_name = "belongs_to_dependent_delete_for_#{reflection.name}".to_sym define_method(method_name) do - association = send("#{reflection.name}") + association = send(reflection.name) association.class.delete(association.id) unless association.nil? end before_destroy method_name @@ -1527,7 +1534,7 @@ module ActiveRecord create_reflection(:has_one, association_id, options, self) end - + def create_has_one_through_reflection(association_id, options) options.assert_valid_keys( :class_name, :foreign_key, :remote, :select, :conditions, :order, :include, :dependent, :counter_cache, :extend, :as, :through, :source, :source_type, :validate @@ -1595,7 +1602,7 @@ module ActiveRecord sql = "SELECT #{column_aliases(join_dependency)} FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} " sql << join_dependency.join_associations.collect{|join| join.association_join }.join - add_joins!(sql, options, scope) + add_joins!(sql, options[:joins], scope) add_conditions!(sql, options[:conditions], scope) add_limited_ids_condition!(sql, options, join_dependency) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit]) @@ -1651,7 +1658,7 @@ module ActiveRecord if is_distinct sql << distinct_join_associations.collect { |assoc| assoc.association_join }.join - add_joins!(sql, options, scope) + add_joins!(sql, options[:joins], scope) end add_conditions!(sql, options[:conditions], scope) @@ -1919,7 +1926,7 @@ module ActiveRecord end def aliased_primary_key - "#{ aliased_prefix }_r0" + "#{aliased_prefix}_r0" end def aliased_table_name @@ -1931,7 +1938,7 @@ module ActiveRecord @column_names_with_alias = [] ([primary_key] + (column_names - [primary_key])).each_with_index do |column_name, i| - @column_names_with_alias << [column_name, "#{ aliased_prefix }_r#{ i }"] + @column_names_with_alias << [column_name, "#{aliased_prefix}_r#{i}"] end end @@ -1968,11 +1975,11 @@ module ActiveRecord @aliased_prefix = "t#{ join_dependency.joins.size }" @parent_table_name = parent.active_record.table_name @aliased_table_name = aliased_table_name_for(table_name) - + if reflection.macro == :has_and_belongs_to_many @aliased_join_table_name = aliased_table_name_for(reflection.options[:join_table], "_join") end - + if [:has_many, :has_one].include?(reflection.macro) && reflection.options[:through] @aliased_join_table_name = aliased_table_name_for(reflection.through_reflection.klass.table_name, "_join") end @@ -2109,7 +2116,7 @@ module ActiveRecord end protected - + def aliased_table_name_for(name, suffix = nil) if !parent.table_joins.blank? && parent.table_joins.to_s.downcase =~ %r{join(\s+\w+)?\s+#{name.downcase}\son} @join_dependency.table_aliases[name] += 1 @@ -2127,7 +2134,7 @@ module ActiveRecord name end - + def pluralize(table_name) ActiveRecord::Base.pluralize_table_names ? table_name.to_s.pluralize : table_name end diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index a12d4face4..168443e092 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -141,6 +141,35 @@ module ActiveRecord end end + # Count all records using SQL. If the +:counter_sql+ option is set for the association, it will + # be used for the query. If no +:counter_sql+ was supplied, but +:finder_sql+ was set, the + # descendant's +construct_sql+ method will have set :counter_sql automatically. + # Otherwise, construct options and pass them with scope to the target class's +count+. + def count(*args) + if @reflection.options[:counter_sql] + @reflection.klass.count_by_sql(@counter_sql) + else + column_name, options = @reflection.klass.send(:construct_count_options_from_args, *args) + if @reflection.options[:uniq] + # This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL. + column_name = "#{@reflection.quoted_table_name}.#{@reflection.klass.primary_key}" if column_name == :all + options.merge!(:distinct => true) + end + + value = @reflection.klass.send(:with_scope, construct_scope) { @reflection.klass.count(column_name, options) } + + limit = @reflection.options[:limit] + offset = @reflection.options[:offset] + + if limit || offset + [ [value - offset.to_i, 0].max, limit.to_i ].min + else + value + end + end + end + + # Remove +records+ from this association. Does not destroy +records+. def delete(*records) records = flatten_deeper(records) diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb index e7e433b6b6..3d689098b5 100644 --- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb @@ -78,6 +78,16 @@ module ActiveRecord end @join_sql = "INNER JOIN #{@owner.connection.quote_table_name @reflection.options[:join_table]} ON #{@reflection.quoted_table_name}.#{@reflection.klass.primary_key} = #{@owner.connection.quote_table_name @reflection.options[:join_table]}.#{@reflection.association_foreign_key}" + + if @reflection.options[:counter_sql] + @counter_sql = interpolate_sql(@reflection.options[:counter_sql]) + elsif @reflection.options[:finder_sql] + # replace the SELECT clause with COUNT(*), preserving any hints within /* ... */ + @reflection.options[:counter_sql] = @reflection.options[:finder_sql].sub(/SELECT (\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" } + @counter_sql = interpolate_sql(@reflection.options[:counter_sql]) + else + @counter_sql = @finder_sql + end end def construct_scope diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 451bf8faa9..dda22668c6 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -5,32 +5,6 @@ module ActiveRecord # If the association has a <tt>:through</tt> option further specialization # is provided by its child HasManyThroughAssociation. class HasManyAssociation < AssociationCollection #:nodoc: - # Count the number of associated records. All arguments are optional. - def count(*args) - if @reflection.options[:counter_sql] - @reflection.klass.count_by_sql(@counter_sql) - elsif @reflection.options[:finder_sql] - @reflection.klass.count_by_sql(@finder_sql) - else - column_name, options = @reflection.klass.send(:construct_count_options_from_args, *args) - options[:conditions] = options[:conditions].blank? ? - @finder_sql : - @finder_sql + " AND (#{sanitize_sql(options[:conditions])})" - options[:include] ||= @reflection.options[:include] - - value = @reflection.klass.count(column_name, options) - - limit = @reflection.options[:limit] - offset = @reflection.options[:offset] - - if limit || offset - [ [value - offset.to_i, 0].max, limit.to_i ].min - else - value - end - end - end - protected def owner_quoted_id if @reflection.options[:primary_key] diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 24b02efc35..84fa900f46 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -31,16 +31,6 @@ module ActiveRecord return count end - def count(*args) - column_name, options = @reflection.klass.send(:construct_count_options_from_args, *args) - if @reflection.options[:uniq] - # This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL statement. - column_name = "#{@reflection.quoted_table_name}.#{@reflection.klass.primary_key}" if column_name == :all - options.merge!(:distinct => true) - end - @reflection.klass.send(:with_scope, construct_scope) { @reflection.klass.count(column_name, options) } - end - protected def construct_find_options!(options) options[:select] = construct_select(options[:select]) diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index fab16a4446..0a1baff87d 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -214,7 +214,7 @@ module ActiveRecord if logger logger.warn "Exception occurred during reader method compilation." logger.warn "Maybe #{attr_name} is not a valid Ruby identifier?" - logger.warn "#{err.message}" + logger.warn err.message end end end @@ -330,8 +330,8 @@ module ActiveRecord end end - # A Person object with a name attribute can ask <tt>person.respond_to?("name")</tt>, - # <tt>person.respond_to?("name=")</tt>, and <tt>person.respond_to?("name?")</tt> + # A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>, + # <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt> # which will all return +true+. alias :respond_to_without_attributes? :respond_to? def respond_to?(method, include_priv = false) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 4a23c8c690..3419aad580 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -452,13 +452,6 @@ module ActiveRecord #:nodoc: cattr_accessor :default_timezone, :instance_writer => false @@default_timezone = :local - # Determines whether to use a connection for each thread, or a single shared connection for all threads. - # Defaults to false. If you're writing a threaded application, set to true - # and periodically call verify_active_connections! to clear out connections - # assigned to stale threads. - cattr_accessor :allow_concurrency, :instance_writer => false - @@allow_concurrency = false - # Specifies the format to use when dumping the database schema with Rails' # Rakefile. If :sql, the schema is dumped as (potentially database- # specific) SQL statements. If :ruby, the schema is dumped as an @@ -930,12 +923,12 @@ module ActiveRecord #:nodoc: # To start from an all-closed default and enable attributes as needed, # have a look at +attr_accessible+. def attr_protected(*attributes) - write_inheritable_attribute("attr_protected", Set.new(attributes.map(&:to_s)) + (protected_attributes || [])) + write_inheritable_attribute(:attr_protected, Set.new(attributes.map(&:to_s)) + (protected_attributes || [])) end # Returns an array of all the attributes that have been protected from mass-assignment. def protected_attributes # :nodoc: - read_inheritable_attribute("attr_protected") + read_inheritable_attribute(:attr_protected) end # Specifies a white list of model attributes that can be set via @@ -963,22 +956,22 @@ module ActiveRecord #:nodoc: # customer.credit_rating = "Average" # customer.credit_rating # => "Average" def attr_accessible(*attributes) - write_inheritable_attribute("attr_accessible", Set.new(attributes.map(&:to_s)) + (accessible_attributes || [])) + write_inheritable_attribute(:attr_accessible, Set.new(attributes.map(&:to_s)) + (accessible_attributes || [])) end # Returns an array of all the attributes that have been made accessible to mass-assignment. def accessible_attributes # :nodoc: - read_inheritable_attribute("attr_accessible") + read_inheritable_attribute(:attr_accessible) end # Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards. def attr_readonly(*attributes) - write_inheritable_attribute("attr_readonly", Set.new(attributes.map(&:to_s)) + (readonly_attributes || [])) + write_inheritable_attribute(:attr_readonly, Set.new(attributes.map(&:to_s)) + (readonly_attributes || [])) end # Returns an array of all the attributes that have been specified as readonly. def readonly_attributes - read_inheritable_attribute("attr_readonly") + read_inheritable_attribute(:attr_readonly) end # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, @@ -1002,7 +995,7 @@ module ActiveRecord #:nodoc: # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values. def serialized_attributes - read_inheritable_attribute("attr_serialized") or write_inheritable_attribute("attr_serialized", {}) + read_inheritable_attribute(:attr_serialized) or write_inheritable_attribute(:attr_serialized, {}) end @@ -1552,7 +1545,7 @@ module ActiveRecord #:nodoc: sql = "SELECT #{options[:select] || (scope && scope[:select]) || ((options[:joins] || (scope && scope[:joins])) && quoted_table_name + '.*') || '*'} " sql << "FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} " - add_joins!(sql, options, scope) + add_joins!(sql, options[:joins], scope) add_conditions!(sql, options[:conditions], scope) add_group!(sql, options[:group], scope) @@ -1568,6 +1561,22 @@ module ActiveRecord #:nodoc: (safe_to_array(first) + safe_to_array(second)).uniq end + def merge_joins(first, second) + if first.is_a?(String) && second.is_a?(String) + "#{first} #{second}" + elsif first.is_a?(String) || second.is_a?(String) + if first.is_a?(String) + join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, second, nil) + "#{first} #{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join}" + else + join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, first, nil) + "#{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join} #{second}" + end + else + (safe_to_array(first) + safe_to_array(second)).uniq + end + end + # Object#to_a is deprecated, though it does have the desired behavior def safe_to_array(o) case o @@ -1623,16 +1632,15 @@ module ActiveRecord #:nodoc: end # The optional scope argument is for the current <tt>:find</tt> scope. - def add_joins!(sql, options, scope = :auto) + def add_joins!(sql, joins, scope = :auto) scope = scope(:find) if :auto == scope - [(scope && scope[:joins]), options[:joins]].each do |join| - case join - when Symbol, Hash, Array - join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, join, nil) - sql << " #{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join} " - else - sql << " #{join} " - end + merged_joins = scope && scope[:joins] && joins ? merge_joins(scope[:joins], joins) : (joins || scope && scope[:joins]) + case merged_joins + when Symbol, Hash, Array + join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, merged_joins, nil) + sql << " #{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join} " + when String + sql << " #{merged_joins} " end end @@ -1882,6 +1890,8 @@ module ActiveRecord #:nodoc: hash[method][key] = merge_conditions(params[key], hash[method][key]) elsif key == :include && merge hash[method][key] = merge_includes(hash[method][key], params[key]).uniq + elsif key == :joins && merge + hash[method][key] = merge_joins(params[key], hash[method][key]) else hash[method][key] = hash[method][key] || params[key] end @@ -1929,22 +1939,11 @@ module ActiveRecord #:nodoc: end end - def thread_safe_scoped_methods #:nodoc: + def scoped_methods #:nodoc: scoped_methods = (Thread.current[:scoped_methods] ||= {}) scoped_methods[self] ||= [] end - def single_threaded_scoped_methods #:nodoc: - @scoped_methods ||= [] - end - - # pick up the correct scoped_methods version from @@allow_concurrency - if @@allow_concurrency - alias_method :scoped_methods, :thread_safe_scoped_methods - else - alias_method :scoped_methods, :single_threaded_scoped_methods - end - def current_scoped_methods #:nodoc: scoped_methods.last end diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index 26acbf53b5..a675af4787 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -188,7 +188,7 @@ module ActiveRecord end joins = "" - add_joins!(joins, options, scope) + add_joins!(joins, options[:joins], scope) if merged_includes.any? join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merged_includes, joins) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb new file mode 100644 index 0000000000..838b0434b0 --- /dev/null +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -0,0 +1,281 @@ +require 'monitor' +require 'set' + +module ActiveRecord + # Raised when a connection could not be obtained within the connection + # acquisition timeout period. + class ConnectionTimeoutError < ConnectionNotEstablished + end + + module ConnectionAdapters + # Connection pool base class for managing ActiveRecord database + # connections. + # + # Connections can be obtained and used from a connection pool in several + # ways: + # + # 1. Simply use ActiveRecord::Base.connection as with ActiveRecord 2.1 and + # earlier (pre-connection-pooling). Eventually, when you're done with + # the connection(s) and wish it to be returned to the pool, you call + # ActiveRecord::Base.clear_active_connections!. This will be the + # default behavior for ActiveRecord when used in conjunction with + # ActionPack's request handling cycle. + # 2. Manually check out a connection from the pool with + # ActiveRecord::Base.connection_pool.checkout. You are responsible for + # returning this connection to the pool when finished by calling + # ActiveRecord::Base.connection_pool.checkin(connection). + # 3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which + # obtains a connection, yields it as the sole argument to the block, + # and returns it to the pool after the block completes. + # + # There are two connection-pooling-related options that you can add to + # your database connection configuration: + # + # * +pool+: number indicating size of connection pool (default 5) + # * +wait_timeout+: number of seconds to block and wait for a connection + # before giving up and raising a timeout error (default 5 seconds). + class ConnectionPool + delegate :verification_timeout, :to => "::ActiveRecord::Base" + attr_reader :spec + + def initialize(spec) + @spec = spec + # The cache of reserved connections mapped to threads + @reserved_connections = {} + # The mutex used to synchronize pool access + @connection_mutex = Monitor.new + @queue = @connection_mutex.new_cond + # default 5 second timeout + @timeout = spec.config[:wait_timeout] || 5 + # default max pool size to 5 + @size = (spec.config[:pool] && spec.config[:pool].to_i) || 5 + @connections = [] + @checked_out = [] + end + + # Retrieve the connection associated with the current thread, or call + # #checkout to obtain one if necessary. + # + # #connection can be called any number of times; the connection is + # held in a hash keyed by the thread id. + def connection + if conn = @reserved_connections[current_connection_id] + conn.verify!(verification_timeout) + conn + else + @reserved_connections[current_connection_id] = checkout + end + end + + # Signal that the thread is finished with the current connection. + # #release_connection releases the connection-thread association + # and returns the connection to the pool. + def release_connection + conn = @reserved_connections.delete(current_connection_id) + checkin conn if conn + end + + # Reserve a connection, and yield it to a block. Ensure the connection is + # checked back in when finished. + def with_connection + conn = checkout + yield conn + ensure + checkin conn + end + + # Returns true if a connection has already been opened. + def connected? + !@connections.empty? + end + + # Disconnect all connections in the pool. + def disconnect! + @reserved_connections.each do |name,conn| + checkin conn + end + @reserved_connections = {} + @connections.each do |conn| + conn.disconnect! + end + @connections = [] + end + + # Clears the cache which maps classes + def clear_reloadable_connections! + @reserved_connections.each do |name, conn| + checkin conn + end + @reserved_connections = {} + @connections.each do |conn| + conn.disconnect! if conn.requires_reloading? + end + @connections = [] + end + + # Verify active connections and remove and disconnect connections + # associated with stale threads. + def verify_active_connections! #:nodoc: + clear_stale_cached_connections! + @connections.each do |connection| + connection.verify!(verification_timeout) + end + end + + # Return any checked-out connections back to the pool by threads that + # are no longer alive. + def clear_stale_cached_connections! + remove_stale_cached_threads!(@reserved_connections) do |name, conn| + checkin conn + end + end + + # Check-out a database connection from the pool. + def checkout + # Checkout an available connection + conn = @connection_mutex.synchronize do + if @checked_out.size < @connections.size + checkout_existing_connection + elsif @connections.size < @size + checkout_new_connection + end + end + return conn if conn + + # No connections available; wait for one + @connection_mutex.synchronize do + if @queue.wait(@timeout) + checkout_existing_connection + else + raise ConnectionTimeoutError, "could not obtain a database connection in a timely fashion" + end + end + end + + # Check-in a database connection back into the pool. + def checkin(conn) + @connection_mutex.synchronize do + conn.run_callbacks :checkin + @checked_out.delete conn + @queue.signal + end + end + + synchronize :clear_reloadable_connections!, :verify_active_connections!, + :connected?, :disconnect!, :with => :@connection_mutex + + private + def new_connection + config = spec.config.reverse_merge(:allow_concurrency => true) + ActiveRecord::Base.send(spec.adapter_method, config) + end + + def current_connection_id #:nodoc: + Thread.current.object_id + end + + # Remove stale threads from the cache. + def remove_stale_cached_threads!(cache, &block) + keys = Set.new(cache.keys) + + Thread.list.each do |thread| + keys.delete(thread.object_id) if thread.alive? + end + keys.each do |key| + next unless cache.has_key?(key) + block.call(key, cache[key]) + cache.delete(key) + end + end + + def checkout_new_connection + c = new_connection + @connections << c + checkout_and_verify(c) + end + + def checkout_existing_connection + c = (@connections - @checked_out).first + checkout_and_verify(c) + end + + def checkout_and_verify(c) + c.run_callbacks :checkout + c.verify!(verification_timeout) + @checked_out << c + c + end + end + + class ConnectionHandler + def initialize(pools = {}) + @connection_pools = pools + end + + def connection_pools + @connection_pools ||= {} + end + + def establish_connection(name, spec) + @connection_pools[name] = ConnectionAdapters::ConnectionPool.new(spec) + end + + # Returns any connections in use by the current thread back to the pool, + # and also returns connections to the pool cached by threads that are no + # longer alive. + def clear_active_connections! + @connection_pools.each_value do |pool| + pool.release_connection + pool.clear_stale_cached_connections! + end + end + + # Clears the cache which maps classes + def clear_reloadable_connections! + @connection_pools.each_value {|pool| pool.clear_reloadable_connections! } + end + + def clear_all_connections! + @connection_pools.each_value {|pool| pool.disconnect! } + end + + # Verify active connections. + def verify_active_connections! #:nodoc: + @connection_pools.each_value {|pool| pool.verify_active_connections! } + end + + # Locate the connection of the nearest super class. This can be an + # active or defined connection: if it is the latter, it will be + # opened and set as the active connection for the class it was defined + # for (not necessarily the current class). + def retrieve_connection(klass) #:nodoc: + pool = retrieve_connection_pool(klass) + (pool && pool.connection) or raise ConnectionNotEstablished + end + + # Returns true if a connection that's accessible to this class has + # already been opened. + def connected?(klass) + retrieve_connection_pool(klass).connected? + end + + # Remove the connection for this class. This will close the active + # connection and the defined connection (if they exist). The result + # can be used as an argument for establish_connection, for easily + # re-establishing the connection. + def remove_connection(klass) + pool = @connection_pools[klass.name] + @connection_pools.delete_if { |key, value| value == pool } + pool.disconnect! if pool + pool.spec.config if pool + end + + def retrieve_connection_pool(klass) + pool = @connection_pools[klass.name] + return pool if pool + return nil if ActiveRecord::Base == klass + retrieve_connection_pool klass.superclass + end + end + end +end
\ No newline at end of file diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb index 2a8807fb78..417a333aab 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb @@ -1,5 +1,3 @@ -require 'set' - module ActiveRecord class Base class ConnectionSpecification #:nodoc: @@ -14,158 +12,9 @@ module ActiveRecord cattr_accessor :verification_timeout, :instance_writer => false @@verification_timeout = 0 - # The class -> [adapter_method, config] map - @@defined_connections = {} - - # The class -> thread id -> adapter cache. (class -> adapter if not allow_concurrency) - @@active_connections = {} - - class << self - # Retrieve the connection cache. - def thread_safe_active_connections #:nodoc: - @@active_connections[Thread.current.object_id] ||= {} - end - - def single_threaded_active_connections #:nodoc: - @@active_connections - end - - # pick up the right active_connection method from @@allow_concurrency - if @@allow_concurrency - alias_method :active_connections, :thread_safe_active_connections - else - alias_method :active_connections, :single_threaded_active_connections - end - - # set concurrency support flag (not thread safe, like most of the methods in this file) - def allow_concurrency=(threaded) #:nodoc: - logger.debug "allow_concurrency=#{threaded}" if logger - return if @@allow_concurrency == threaded - clear_all_cached_connections! - @@allow_concurrency = threaded - method_prefix = threaded ? "thread_safe" : "single_threaded" - sing = (class << self; self; end) - [:active_connections, :scoped_methods].each do |method| - sing.send(:alias_method, method, "#{method_prefix}_#{method}") - end - log_connections if logger - end - - def active_connection_name #:nodoc: - @active_connection_name ||= - if active_connections[name] || @@defined_connections[name] - name - elsif self == ActiveRecord::Base - nil - else - superclass.active_connection_name - end - end - - def clear_active_connection_name #:nodoc: - @active_connection_name = nil - subclasses.each { |klass| klass.clear_active_connection_name } - end - - # Returns the connection currently associated with the class. This can - # also be used to "borrow" the connection to do database work unrelated - # to any of the specific Active Records. - def connection - if defined?(@active_connection_name) && (conn = active_connections[@active_connection_name]) - conn - else - # retrieve_connection sets the cache key. - conn = retrieve_connection - active_connections[@active_connection_name] = conn - end - end - - # Clears the cache which maps classes to connections. - def clear_active_connections! - clear_cache!(@@active_connections) do |name, conn| - conn.disconnect! - end - end - - # Clears the cache which maps classes - def clear_reloadable_connections! - if @@allow_concurrency - # With concurrent connections @@active_connections is - # a hash keyed by thread id. - @@active_connections.each do |thread_id, conns| - conns.each do |name, conn| - if conn.requires_reloading? - conn.disconnect! - @@active_connections[thread_id].delete(name) - end - end - end - else - @@active_connections.each do |name, conn| - if conn.requires_reloading? - conn.disconnect! - @@active_connections.delete(name) - end - end - end - end - - # Verify active connections. - def verify_active_connections! #:nodoc: - if @@allow_concurrency - remove_stale_cached_threads!(@@active_connections) do |name, conn| - conn.disconnect! - end - end - - active_connections.each_value do |connection| - connection.verify!(@@verification_timeout) - end - end - - private - def clear_cache!(cache, thread_id = nil, &block) - if cache - if @@allow_concurrency - thread_id ||= Thread.current.object_id - thread_cache, cache = cache, cache[thread_id] - return unless cache - end - - cache.each(&block) if block_given? - cache.clear - end - ensure - if thread_cache && @@allow_concurrency - thread_cache.delete(thread_id) - end - end - - # Remove stale threads from the cache. - def remove_stale_cached_threads!(cache, &block) - stale = Set.new(cache.keys) - - Thread.list.each do |thread| - stale.delete(thread.object_id) if thread.alive? - end - - stale.each do |thread_id| - clear_cache!(cache, thread_id, &block) - end - end - - def clear_all_cached_connections! - if @@allow_concurrency - @@active_connections.each_value do |connection_hash_for_thread| - connection_hash_for_thread.each_value {|conn| conn.disconnect! } - connection_hash_for_thread.clear - end - else - @@active_connections.each_value {|conn| conn.disconnect! } - end - @@active_connections.clear - end - end + # The connection handler + cattr_accessor :connection_handler, :instance_writer => false + @@connection_handler = ConnectionAdapters::ConnectionHandler.new # Returns the connection currently associated with the class. This can # also be used to "borrow" the connection to do database work that isn't @@ -208,9 +57,7 @@ module ActiveRecord raise AdapterNotSpecified unless defined? RAILS_ENV establish_connection(RAILS_ENV) when ConnectionSpecification - clear_active_connection_name - @active_connection_name = name - @@defined_connections[name] = spec + @@connection_handler.establish_connection(name, spec) when Symbol, String if configuration = configurations[spec.to_s] establish_connection(configuration) @@ -243,67 +90,42 @@ module ActiveRecord end end - # Locate the connection of the nearest super class. This can be an - # active or defined connection: if it is the latter, it will be - # opened and set as the active connection for the class it was defined - # for (not necessarily the current class). - def self.retrieve_connection #:nodoc: - # Name is nil if establish_connection hasn't been called for - # some class along the inheritance chain up to AR::Base yet. - if name = active_connection_name - if conn = active_connections[name] - # Verify the connection. - conn.verify!(@@verification_timeout) - elsif spec = @@defined_connections[name] - # Activate this connection specification. - klass = name.constantize - klass.connection = spec - conn = active_connections[name] - end + class << self + # Deprecated and no longer has any effect. + def allow_concurrency + ActiveSupport::Deprecation.warn("ActiveRecord::Base.allow_concurrency has been deprecated and no longer has any effect. Please remove all references to allow_concurrency.") end - conn or raise ConnectionNotEstablished - end + # Deprecated and no longer has any effect. + def allow_concurrency=(flag) + ActiveSupport::Deprecation.warn("ActiveRecord::Base.allow_concurrency= has been deprecated and no longer has any effect. Please remove all references to allow_concurrency=.") + end - # Returns true if a connection that's accessible to this class has already been opened. - def self.connected? - active_connections[active_connection_name] ? true : false - end + # Returns the connection currently associated with the class. This can + # also be used to "borrow" the connection to do database work unrelated + # to any of the specific Active Records. + def connection + retrieve_connection + end - # Remove the connection for this class. This will close the active - # connection and the defined connection (if they exist). The result - # can be used as an argument for establish_connection, for easily - # re-establishing the connection. - def self.remove_connection(klass=self) - spec = @@defined_connections[klass.name] - konn = active_connections[klass.name] - @@defined_connections.delete_if { |key, value| value == spec } - active_connections.delete_if { |key, value| value == konn } - konn.disconnect! if konn - spec.config if spec - end + def connection_pool + connection_handler.retrieve_connection_pool(self) + end - # Set the connection for the class. - def self.connection=(spec) #:nodoc: - if spec.kind_of?(ActiveRecord::ConnectionAdapters::AbstractAdapter) - active_connections[name] = spec - elsif spec.kind_of?(ConnectionSpecification) - config = spec.config.reverse_merge(:allow_concurrency => @@allow_concurrency) - self.connection = self.send(spec.adapter_method, config) - elsif spec.nil? - raise ConnectionNotEstablished - else - establish_connection spec + def retrieve_connection + connection_handler.retrieve_connection(self) end - end - # connection state logging - def self.log_connections #:nodoc: - if logger - logger.info "Defined connections: #{@@defined_connections.inspect}" - logger.info "Active connections: #{active_connections.inspect}" - logger.info "Active connection name: #{@active_connection_name}" + def connected? + connection_handler.connected?(self) end + + def remove_connection(klass = self) + connection_handler.remove_connection(klass) + end + + delegate :clear_active_connections!, :clear_reloadable_connections!, + :clear_all_connections!,:verify_active_connections!, :to => :connection_handler end end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb index 2afd6064ad..2fc50b9bfa 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb @@ -4,7 +4,6 @@ module ActiveRecord class << self def included(base) base.class_eval do - attr_accessor :query_cache_enabled alias_method_chain :columns, :query_cache alias_method_chain :select_all, :query_cache end @@ -16,7 +15,7 @@ module ActiveRecord method_names.each do |method_name| base.class_eval <<-end_code, __FILE__, __LINE__ def #{method_name}_with_query_dirty(*args) - clear_query_cache if @query_cache_enabled + clear_query_cache if query_cache_enabled #{method_name}_without_query_dirty(*args) end @@ -26,22 +25,38 @@ module ActiveRecord end end + def query_cache_enabled + Thread.current['query_cache_enabled'] + end + + def query_cache_enabled=(flag) + Thread.current['query_cache_enabled'] = flag + end + + def query_cache + Thread.current['query_cache'] + end + + def query_cache=(cache) + Thread.current['query_cache'] = cache + end + # Enable the query cache within the block. def cache - old, @query_cache_enabled = @query_cache_enabled, true - @query_cache ||= {} + old, self.query_cache_enabled = query_cache_enabled, true + self.query_cache ||= {} yield ensure clear_query_cache - @query_cache_enabled = old + self.query_cache_enabled = old end # Disable the query cache within the block. def uncached - old, @query_cache_enabled = @query_cache_enabled, false + old, self.query_cache_enabled = query_cache_enabled, false yield ensure - @query_cache_enabled = old + self.query_cache_enabled = old end # Clears the query cache. @@ -51,11 +66,11 @@ module ActiveRecord # the same SQL query and repeatedly return the same result each time, silently # undermining the randomness you were expecting. def clear_query_cache - @query_cache.clear if @query_cache + query_cache.clear if query_cache end def select_all_with_query_cache(*args) - if @query_cache_enabled + if query_cache_enabled cache_sql(args.first) { select_all_without_query_cache(*args) } else select_all_without_query_cache(*args) @@ -63,8 +78,8 @@ module ActiveRecord end def columns_with_query_cache(*args) - if @query_cache_enabled - @query_cache["SHOW FIELDS FROM #{args.first}"] ||= columns_without_query_cache(*args) + if query_cache_enabled + query_cache["SHOW FIELDS FROM #{args.first}"] ||= columns_without_query_cache(*args) else columns_without_query_cache(*args) end @@ -73,11 +88,11 @@ module ActiveRecord private def cache_sql(sql) result = - if @query_cache.has_key?(sql) + if query_cache.has_key?(sql) log_info(sql, "CACHE", 0.0) - @query_cache[sql] + query_cache[sql] else - @query_cache[sql] = yield + query_cache[sql] = yield end if Array === result diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 6924bb7e6f..005be9d72f 100644..100755 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -7,6 +7,7 @@ require 'active_record/connection_adapters/abstract/schema_definitions' require 'active_record/connection_adapters/abstract/schema_statements' require 'active_record/connection_adapters/abstract/database_statements' require 'active_record/connection_adapters/abstract/quoting' +require 'active_record/connection_adapters/abstract/connection_pool' require 'active_record/connection_adapters/abstract/connection_specification' require 'active_record/connection_adapters/abstract/query_cache' @@ -24,6 +25,9 @@ module ActiveRecord class AbstractAdapter include Quoting, DatabaseStatements, SchemaStatements include QueryCache + include ActiveSupport::Callbacks + define_callbacks :checkout, :checkin + checkout :reset! @@row_even = true def initialize(connection, logger = nil) #:nodoc: @@ -102,14 +106,25 @@ module ActiveRecord @active = false end + # Reset the state of this connection, directing the DBMS to clear + # transactions and other connection-related server-side state. Usually a + # database-dependent operation; the default method simply executes a + # ROLLBACK and swallows any exceptions which is probably not enough to + # ensure the connection is clean. + def reset! + silence_stderr do # postgres prints on stderr when you do this w/o a txn + execute "ROLLBACK" rescue nil + end + end + # Returns true if its safe to reload the connection between requests for development mode. # This is not the case for Ruby/MySQL and it's not necessary for any adapters except SQLite. def requires_reloading? false end - # Lazily verify this connection, calling <tt>active?</tt> only if it hasn't - # been called for +timeout+ seconds. + # Lazily verify this connection, calling <tt>active?</tt> only if it + # hasn't been called for +timeout+ seconds. def verify!(timeout) now = Time.now.to_i if (now - @last_verification) > timeout diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 204ebaa2e2..14c76ac455 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -280,6 +280,16 @@ module ActiveRecord @connection.close rescue nil end + def reset! + if @connection.respond_to?(:change_user) + # See http://bugs.mysql.com/bug.php?id=33540 -- the workaround way to + # reset the connection is to change the user to the same user. + @connection.change_user(@config[:username], @config[:password], @config[:database]) + configure_connection + else + super + end + end # DATABASE STATEMENTS ====================================== @@ -529,7 +539,11 @@ module ActiveRecord end @connection.real_connect(*@connection_options) + configure_connection + end + def configure_connection + encoding = @config[:encoding] execute("SET NAMES '#{encoding}'") if encoding # By default, MySQL 'where id is null' selects the last inserted id. diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 622cfc3c3f..114141a646 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -955,7 +955,7 @@ module Test #:nodoc: ActiveRecord::Base.connection.rollback_db_transaction ActiveRecord::Base.connection.decrement_open_transactions end - ActiveRecord::Base.verify_active_connections! + ActiveRecord::Base.clear_active_connections! end private diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb index 46eaa42a55..83043c2c22 100644 --- a/activerecord/lib/active_record/named_scope.rb +++ b/activerecord/lib/active_record/named_scope.rb @@ -101,9 +101,9 @@ module ActiveRecord class Scope attr_reader :proxy_scope, :proxy_options - + NON_DELEGATE_METHODS = %w(nil? send object_id class extend find size count sum average maximum minimum paginate first last empty? any? respond_to?).to_set [].methods.each do |m| - unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|^find$|count|sum|average|maximum|minimum|paginate|first|last|empty?|any?|respond_to?)/ + unless m =~ /^__/ || NON_DELEGATE_METHODS.include?(m.to_s) delegate m, :to => :proxy_found end end @@ -136,6 +136,10 @@ module ActiveRecord end end + def size + @found ? @found.length : count + end + def empty? @found ? @found.empty? : count.zero? end diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 687f1261cd..577e30ec86 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -54,7 +54,7 @@ module ActiveRecord def add_on_empty(attributes, custom_message = nil) for attr in [attributes].flatten value = @base.respond_to?(attr.to_s) ? @base.send(attr.to_s) : @base[attr.to_s] - is_empty = value.respond_to?("empty?") ? value.empty? : false + is_empty = value.respond_to?(:empty?) ? value.empty? : false add(attr, :empty, :default => custom_message) unless !value.nil? && !is_empty end end @@ -87,6 +87,8 @@ module ActiveRecord # </ol> def generate_message(attribute, message = :invalid, options = {}) + message, options[:default] = options[:default], message if options[:default].is_a?(Symbol) + defaults = @base.class.self_and_descendents_from_active_record.map do |klass| [ :"models.#{klass.name.underscore}.attributes.#{attribute}.#{message}", :"models.#{klass.name.underscore}.#{message}" ] @@ -95,7 +97,6 @@ module ActiveRecord defaults << options.delete(:default) defaults = defaults.compact.flatten << :"messages.#{message}" - model_name = @base.class.name key = defaults.shift value = @base.respond_to?(attribute) ? @base.send(attribute) : nil @@ -664,7 +665,7 @@ module ActiveRecord condition_params = [value] else condition_sql = "LOWER(#{sql_attribute}) #{comparison_operator}" - condition_params = [value.downcase] + condition_params = [value.chars.downcase] end if scope = configuration[:scope] @@ -750,7 +751,7 @@ module ActiveRecord enum = configuration[:in] || configuration[:within] - raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?("include?") + raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?) validates_each(attr_names, configuration) do |record, attr_name, value| unless enum.include?(value) @@ -784,7 +785,7 @@ module ActiveRecord enum = configuration[:in] || configuration[:within] - raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?("include?") + raise(ArgumentError, "An object with the method include? is required must be supplied as the :in option of the configuration hash") unless enum.respond_to?(:include?) validates_each(attr_names, configuration) do |record, attr_name, value| if enum.include?(value) diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 0572418e3b..edca3c622b 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -223,10 +223,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase devel = Developer.find(1) proj = assert_no_queries { devel.projects.build("name" => "Projekt") } assert !devel.projects.loaded? - + assert_equal devel.projects.last, proj assert devel.projects.loaded? - + assert proj.new_record? devel.save assert !proj.new_record? @@ -251,10 +251,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase devel = Developer.find(1) proj = devel.projects.create("name" => "Projekt") assert !devel.projects.loaded? - + assert_equal devel.projects.last, proj assert devel.projects.loaded? - + assert !proj.new_record? assert_equal Developer.find(1).projects.sort_by(&:id).last, proj # prove join table is updated end @@ -274,10 +274,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase def test_creation_respects_hash_condition post = categories(:general).post_with_conditions.build(:body => '') - + assert post.save assert_equal 'Yet Another Testing Title', post.title - + another_post = categories(:general).post_with_conditions.create(:body => '') assert !another_post.new_record? @@ -288,7 +288,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase dev = developers(:jamis) dev.projects << projects(:active_record) dev.projects << projects(:active_record) - + assert_equal 3, dev.projects.size assert_equal 1, dev.projects.uniq.size end @@ -415,13 +415,13 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase project.developers.class # force load target developer = project.developers.first - + assert_no_queries do assert project.developers.loaded? assert project.developers.include?(developer) end end - + def test_include_checks_if_record_exists_if_target_not_loaded project = projects(:active_record) developer = project.developers.first @@ -641,6 +641,22 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert_equal [projects(:active_record).id], developers(:jamis).project_ids end + def test_get_ids_for_loaded_associations + developer = developers(:david) + developer.projects(true) + assert_queries(0) do + developer.project_ids + developer.project_ids + end + end + + def test_get_ids_for_unloaded_associations_does_not_load_them + developer = developers(:david) + assert !developer.projects.loaded? + assert_equal projects(:active_record, :action_controller).map(&:id).sort, developer.project_ids.sort + assert !developer.projects.loaded? + end + def test_assign_ids developer = Developer.new("name" => "Joe") developer.project_ids = projects(:active_record, :action_controller).map(&:id) @@ -703,4 +719,11 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase # due to Unknown column 'authors.id' assert Category.find(1).posts_with_authors_sorted_by_author_id.find_by_title('Welcome to the weblog') end + + def test_counting_on_habtm_association_and_not_array + david = Developer.find(1) + # Extra parameter just to make sure we aren't falling back to + # Array#count in Ruby >=1.8.7, which would raise an ArgumentError + assert_nothing_raised { david.projects.count(:all, :conditions => '1=1') } + end end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 17fd88ce65..feac4b002b 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -384,7 +384,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase company = companies(:first_firm) new_client = assert_no_queries { company.clients_of_firm.build("name" => "Another Client") } assert !company.clients_of_firm.loaded? - + assert_equal "Another Client", new_client.name assert new_client.new_record? assert_equal new_client, company.clients_of_firm.last @@ -416,7 +416,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase def test_build_many company = companies(:first_firm) new_clients = assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) } - + assert_equal 2, new_clients.size company.name += '-changed' assert_queries(3) { assert company.save } @@ -655,10 +655,10 @@ class HasManyAssociationsTest < ActiveRecord::TestCase def test_creation_respects_hash_condition ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.build - + assert ms_client.save assert_equal 'Microsoft', ms_client.name - + another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create assert !another_ms_client.new_record? @@ -830,6 +830,22 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal [companies(:first_client).id, companies(:second_client).id], companies(:first_firm).client_ids end + def test_get_ids_for_loaded_associations + company = companies(:first_firm) + company.clients(true) + assert_queries(0) do + company.client_ids + company.client_ids + end + end + + def test_get_ids_for_unloaded_associations_does_not_load_them + company = companies(:first_firm) + assert !company.clients.loaded? + assert_equal [companies(:first_client).id, companies(:second_client).id], company.client_ids + assert !company.clients.loaded? + end + def test_assign_ids firm = Firm.new("name" => "Apple") firm.client_ids = [companies(:first_client).id, companies(:second_client).id] @@ -900,7 +916,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 4, authors(:david).limited_comments.find(:all, :conditions => "comments.type = 'SpecialComment'", :limit => 9_000).length assert_equal 4, authors(:david).limited_comments.find_all_by_type('SpecialComment', :limit => 9_000).length end - + def test_find_all_include_over_the_same_table_for_through assert_equal 2, people(:michael).posts.find(:all, :include => :people).length end @@ -937,13 +953,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase def test_include_loads_collection_if_target_uses_finder_sql firm = companies(:first_firm) client = firm.clients_using_sql.first - + firm.reload assert ! firm.clients_using_sql.loaded? assert firm.clients_using_sql.include?(client) assert firm.clients_using_sql.loaded? end - + def test_include_returns_false_for_non_matching_record_to_verify_scoping firm = companies(:first_firm) diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 353262c81b..0be050ec81 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -200,4 +200,24 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_count_with_include_should_alias_join_table assert_equal 2, people(:michael).posts.count(:include => :readers) end + + def test_get_ids + assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort + end + + def test_get_ids_for_loaded_associations + person = people(:michael) + person.posts(true) + assert_queries(0) do + person.post_ids + person.post_ids + end + end + + def test_get_ids_for_unloaded_associations_does_not_load_them + person = people(:michael) + assert !person.posts.loaded? + assert_equal [posts(:welcome).id, posts(:authorless).id].sort, person.post_ids.sort + assert !person.posts.loaded? + end end diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index c8111358e3..ac9081e003 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -880,7 +880,7 @@ class BasicsTest < ActiveRecord::TestCase def test_mass_assignment_protection_against_class_attribute_writers [:logger, :configurations, :primary_key_prefix_type, :table_name_prefix, :table_name_suffix, :pluralize_table_names, :colorize_logging, - :default_timezone, :allow_concurrency, :schema_format, :verification_timeout, :lock_optimistically, :record_timestamps].each do |method| + :default_timezone, :schema_format, :verification_timeout, :lock_optimistically, :record_timestamps].each do |method| assert Task.respond_to?(method) assert Task.respond_to?("#{method}=") assert Task.new.respond_to?(method) diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 701187223f..bbe8582466 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -210,13 +210,6 @@ unless current_adapter?(:SQLServerAdapter, :SybaseAdapter, :OpenBaseAdapter) def setup # Avoid introspection queries during tests. Person.columns; Reader.columns - - @allow_concurrency = ActiveRecord::Base.allow_concurrency - ActiveRecord::Base.allow_concurrency = true - end - - def teardown - ActiveRecord::Base.allow_concurrency = @allow_concurrency end # Test typical find. diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb index ee66ac948d..af6fcd32ad 100644 --- a/activerecord/test/cases/method_scoping_test.rb +++ b/activerecord/test/cases/method_scoping_test.rb @@ -1,4 +1,5 @@ require "cases/helper" +require 'models/author' require 'models/developer' require 'models/project' require 'models/comment' @@ -6,7 +7,7 @@ require 'models/post' require 'models/category' class MethodScopingTest < ActiveRecord::TestCase - fixtures :developers, :projects, :comments, :posts, :developers_projects + fixtures :authors, :developers, :projects, :comments, :posts, :developers_projects def test_set_conditions Developer.with_scope(:find => { :conditions => 'just a test...' }) do @@ -97,6 +98,46 @@ class MethodScopingTest < ActiveRecord::TestCase assert_equal developers(:david).attributes, scoped_developers.first.attributes end + def test_scoped_find_using_new_style_joins + scoped_developers = Developer.with_scope(:find => { :joins => :projects }) do + Developer.find(:all, :conditions => 'projects.id = 2') + end + assert scoped_developers.include?(developers(:david)) + assert !scoped_developers.include?(developers(:jamis)) + assert_equal 1, scoped_developers.size + assert_equal developers(:david).attributes, scoped_developers.first.attributes + end + + def test_scoped_find_merges_old_style_joins + scoped_authors = Author.with_scope(:find => { :joins => 'INNER JOIN posts ON authors.id = posts.author_id ' }) do + Author.find(:all, :select => 'DISTINCT authors.*', :joins => 'INNER JOIN comments ON posts.id = comments.post_id', :conditions => 'comments.id = 1') + end + assert scoped_authors.include?(authors(:david)) + assert !scoped_authors.include?(authors(:mary)) + assert_equal 1, scoped_authors.size + assert_equal authors(:david).attributes, scoped_authors.first.attributes + end + + def test_scoped_find_merges_new_style_joins + scoped_authors = Author.with_scope(:find => { :joins => :posts }) do + Author.find(:all, :select => 'DISTINCT authors.*', :joins => :comments, :conditions => 'comments.id = 1') + end + assert scoped_authors.include?(authors(:david)) + assert !scoped_authors.include?(authors(:mary)) + assert_equal 1, scoped_authors.size + assert_equal authors(:david).attributes, scoped_authors.first.attributes + end + + def test_scoped_find_merges_new_and_old_style_joins + scoped_authors = Author.with_scope(:find => { :joins => :posts }) do + Author.find(:all, :select => 'DISTINCT authors.*', :joins => 'JOIN comments ON posts.id = comments.post_id', :conditions => 'comments.id = 1') + end + assert scoped_authors.include?(authors(:david)) + assert !scoped_authors.include?(authors(:mary)) + assert_equal 1, scoped_authors.size + assert_equal authors(:david).attributes, scoped_authors.first.attributes + end + def test_scoped_count_include # with the include, will retrieve only developers for the given project Developer.with_scope(:find => { :include => :projects }) do @@ -152,7 +193,7 @@ class MethodScopingTest < ActiveRecord::TestCase end class NestedScopingTest < ActiveRecord::TestCase - fixtures :developers, :projects, :comments, :posts + fixtures :authors, :developers, :projects, :comments, :posts def test_merge_options Developer.with_scope(:find => { :conditions => 'salary = 80000' }) do @@ -357,6 +398,42 @@ class NestedScopingTest < ActiveRecord::TestCase assert_equal scoped_methods, Developer.instance_eval('current_scoped_methods') end end + + def test_nested_scoped_find_merges_old_style_joins + scoped_authors = Author.with_scope(:find => { :joins => 'INNER JOIN posts ON authors.id = posts.author_id' }) do + Author.with_scope(:find => { :joins => 'INNER JOIN comments ON posts.id = comments.post_id' }) do + Author.find(:all, :select => 'DISTINCT authors.*', :conditions => 'comments.id = 1') + end + end + assert scoped_authors.include?(authors(:david)) + assert !scoped_authors.include?(authors(:mary)) + assert_equal 1, scoped_authors.size + assert_equal authors(:david).attributes, scoped_authors.first.attributes + end + + def test_nested_scoped_find_merges_new_style_joins + scoped_authors = Author.with_scope(:find => { :joins => :posts }) do + Author.with_scope(:find => { :joins => :comments }) do + Author.find(:all, :select => 'DISTINCT authors.*', :conditions => 'comments.id = 1') + end + end + assert scoped_authors.include?(authors(:david)) + assert !scoped_authors.include?(authors(:mary)) + assert_equal 1, scoped_authors.size + assert_equal authors(:david).attributes, scoped_authors.first.attributes + end + + def test_nested_scoped_find_merges_new_and_old_style_joins + scoped_authors = Author.with_scope(:find => { :joins => :posts }) do + Author.with_scope(:find => { :joins => 'INNER JOIN comments ON posts.id = comments.post_id' }) do + Author.find(:all, :select => 'DISTINCT authors.*', :joins => '', :conditions => 'comments.id = 1') + end + end + assert scoped_authors.include?(authors(:david)) + assert !scoped_authors.include?(authors(:mary)) + assert_equal 1, scoped_authors.size + assert_equal authors(:david).attributes, scoped_authors.first.attributes + end end class HasManyScopingTest< ActiveRecord::TestCase diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 6f6ea1cbe9..444debd255 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -249,7 +249,26 @@ class NamedScopeTest < ActiveRecord::TestCase assert_equal Topic.base.select(&:approved), Topic.base.find_all(&:approved) end + def test_rand_should_select_a_random_object_from_proxy + assert Topic.approved.rand.is_a?(Topic) + end + def test_should_use_where_in_query_for_named_scope assert_equal Developer.find_all_by_name('Jamis'), Developer.find_all_by_id(Developer.jamises) end + + def test_size_should_use_count_when_results_are_not_loaded + topics = Topic.base + assert_queries(1) do + assert_sql(/COUNT/i) { topics.size } + end + end + + def test_size_should_use_length_when_results_are_loaded + topics = Topic.base + topics.reload # force load + assert_no_queries do + topics.size # use loaded (no query) + end + end end diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb new file mode 100644 index 0000000000..078ca1d679 --- /dev/null +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -0,0 +1,87 @@ +require "cases/helper" + +class PooledConnectionsTest < ActiveRecord::TestCase + def setup + super + @connection = ActiveRecord::Base.remove_connection + end + + def teardown + ActiveRecord::Base.clear_all_connections! + ActiveRecord::Base.establish_connection(@connection) + super + end + + def checkout_connections + ActiveRecord::Base.establish_connection(@connection.merge({:pool => 2, :wait_timeout => 0.3})) + @connections = [] + @timed_out = 0 + + 4.times do + Thread.new do + begin + @connections << ActiveRecord::Base.connection_pool.checkout + rescue ActiveRecord::ConnectionTimeoutError + @timed_out += 1 + end + end.join + end + end + + def test_pooled_connection_checkout + checkout_connections + assert_equal @connections.length, 2 + assert_equal @timed_out, 2 + end + + def checkout_checkin_connections(pool_size, threads) + ActiveRecord::Base.establish_connection(@connection.merge({:pool => pool_size, :wait_timeout => 0.5})) + @connection_count = 0 + @timed_out = 0 + threads.times do + Thread.new do + begin + conn = ActiveRecord::Base.connection_pool.checkout + sleep 0.1 + ActiveRecord::Base.connection_pool.checkin conn + @connection_count += 1 + rescue ActiveRecord::ConnectionTimeoutError + @timed_out += 1 + end + end.join + end + end + + def test_pooled_connection_checkin_one + checkout_checkin_connections 1, 2 + assert_equal 2, @connection_count + assert_equal 0, @timed_out + end + + def test_pooled_connection_checkin_two + checkout_checkin_connections 2, 3 + assert_equal 3, @connection_count + assert_equal 0, @timed_out + end + + def test_pooled_connection_checkout_existing_first + ActiveRecord::Base.establish_connection(@connection.merge({:pool => 1})) + conn_pool = ActiveRecord::Base.connection_pool + conn = conn_pool.checkout + conn_pool.checkin(conn) + conn = conn_pool.checkout + assert ActiveRecord::ConnectionAdapters::AbstractAdapter === conn + conn_pool.checkin(conn) + end +end unless %w(FrontBase).include? ActiveRecord::Base.connection.adapter_name + +class AllowConcurrencyDeprecatedTest < ActiveRecord::TestCase + def test_allow_concurrency_is_deprecated + assert_deprecated('ActiveRecord::Base.allow_concurrency') do + ActiveRecord::Base.allow_concurrency + end + assert_deprecated('ActiveRecord::Base.allow_concurrency=') do + ActiveRecord::Base.allow_concurrency = true + end + end +end diff --git a/activerecord/test/cases/threaded_connections_test.rb b/activerecord/test/cases/threaded_connections_test.rb deleted file mode 100644 index 28f8302367..0000000000 --- a/activerecord/test/cases/threaded_connections_test.rb +++ /dev/null @@ -1,48 +0,0 @@ -require "cases/helper" -require 'models/topic' -require 'models/reply' - -unless %w(FrontBase).include? ActiveRecord::Base.connection.adapter_name - class ThreadedConnectionsTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false - - fixtures :topics - - def setup - @connection = ActiveRecord::Base.remove_connection - @connections = [] - @allow_concurrency = ActiveRecord::Base.allow_concurrency - end - - def teardown - # clear the connection cache - ActiveRecord::Base.send(:clear_all_cached_connections!) - # set allow_concurrency to saved value - ActiveRecord::Base.allow_concurrency = @allow_concurrency - # reestablish old connection - ActiveRecord::Base.establish_connection(@connection) - end - - def gather_connections(use_threaded_connections) - ActiveRecord::Base.allow_concurrency = use_threaded_connections - ActiveRecord::Base.establish_connection(@connection) - - 5.times do - Thread.new do - Topic.find :first - @connections << ActiveRecord::Base.active_connections.values.first - end.join - end - end - - def test_threaded_connections - gather_connections(true) - assert_equal @connections.uniq.length, 5 - end - - def test_unthreaded_connections - gather_connections(false) - assert_equal @connections.uniq.length, 1 - end - end -end diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index af3ee6ddba..8383ba58e9 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -283,17 +283,6 @@ end if current_adapter?(:PostgreSQLAdapter) class ConcurrentTransactionTest < TransactionTest - def setup - @allow_concurrency = ActiveRecord::Base.allow_concurrency - ActiveRecord::Base.allow_concurrency = true - super - end - - def teardown - super - ActiveRecord::Base.allow_concurrency = @allow_concurrency - end - # This will cause transactions to overlap and fail unless they are performed on # separate database connections. def test_transaction_per_thread diff --git a/activerecord/test/cases/validations_i18n_test.rb b/activerecord/test/cases/validations_i18n_test.rb index 43592bcee3..090f347a20 100644 --- a/activerecord/test/cases/validations_i18n_test.rb +++ b/activerecord/test/cases/validations_i18n_test.rb @@ -675,6 +675,38 @@ class ActiveRecordValidationsI18nTests < Test::Unit::TestCase replied_topic.valid? assert_equal 'global message', replied_topic.errors.on(:replies) end + + def test_validations_with_message_symbol_must_translate + I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:messages => {:custom_error => "I am a custom error"}}} + Topic.validates_presence_of :title, :message => :custom_error + @topic.title = nil + @topic.valid? + assert_equal "I am a custom error", @topic.errors.on(:title) + end + + def test_validates_with_message_symbol_must_translate_per_attribute + I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:attributes => {:title => {:custom_error => "I am a custom error"}}}}}} + Topic.validates_presence_of :title, :message => :custom_error + @topic.title = nil + @topic.valid? + assert_equal "I am a custom error", @topic.errors.on(:title) + end + + def test_validates_with_message_symbol_must_translate_per_model + I18n.backend.store_translations 'en-US', :activerecord => {:errors => {:models => {:topic => {:custom_error => "I am a custom error"}}}} + Topic.validates_presence_of :title, :message => :custom_error + @topic.title = nil + @topic.valid? + assert_equal "I am a custom error", @topic.errors.on(:title) + end + + def test_validates_with_message_string + Topic.validates_presence_of :title, :message => "I am a custom error" + @topic.title = nil + @topic.valid? + assert_equal "I am a custom error", @topic.errors.on(:title) + end + end class ActiveRecordValidationsGenerateMessageI18nTests < Test::Unit::TestCase @@ -855,4 +887,5 @@ class ActiveRecordValidationsGenerateMessageI18nTests < Test::Unit::TestCase def test_generate_message_even_with_default_message assert_equal "must be even", @topic.errors.generate_message(:title, :even, :default => nil, :value => 'title', :count => 10) end + end diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index a40bda2533..4999d93a86 100644 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -451,6 +451,18 @@ class ValidationsTest < ActiveRecord::TestCase t2.title = nil assert t2.valid?, "should validate with nil" assert t2.save, "should save with nil" + + with_kcode('UTF8') do + t_utf8 = Topic.new("title" => "Я тоже уникальный!") + assert t_utf8.save, "Should save t_utf8 as unique" + + # If database hasn't UTF-8 character set, this test fails + if Topic.find(t_utf8, :select => 'LOWER(title) AS title').title == "я тоже уникальный!" + t2_utf8 = Topic.new("title" => "я тоже УНИКАЛЬНЫЙ!") + assert !t2_utf8.valid?, "Shouldn't be valid" + assert !t2_utf8.save, "Shouldn't save t2_utf8 as unique" + end + end end def test_validate_case_sensitive_uniqueness diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index 41e587d3cd..d966062c7f 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -289,13 +289,13 @@ module ActiveResource format = mime_type_reference_or_format.is_a?(Symbol) ? ActiveResource::Formats[mime_type_reference_or_format] : mime_type_reference_or_format - write_inheritable_attribute("format", format) + write_inheritable_attribute(:format, format) connection.format = format if site end # Returns the current format, default is ActiveResource::Formats::XmlFormat. def format - read_inheritable_attribute("format") || ActiveResource::Formats[:xml] + read_inheritable_attribute(:format) || ActiveResource::Formats[:xml] end # Sets the number of seconds after which requests to the REST API should time out. @@ -854,8 +854,13 @@ module ActiveResource # # my_group.to_xml(:skip_instruct => true) # # => <subsidiary_group> [...] </subsidiary_group> - def to_xml(options={}) - attributes.to_xml({:root => self.class.element_name}.merge(options)) + def encode(options={}) + case self.class.format + when ActiveResource::Formats[:xml] + self.class.format.encode(attributes, {:root => self.class.element_name}.merge(options)) + else + self.class.format.encode(attributes, options) + end end # A method to \reload the attributes of this object from the remote web service. @@ -916,8 +921,8 @@ module ActiveResource alias_method :respond_to_without_attributes?, :respond_to? # A method to determine if an object responds to a message (e.g., a method call). In Active Resource, a Person object with a - # +name+ attribute can answer <tt>true</tt> to <tt>my_person.respond_to?("name")</tt>, <tt>my_person.respond_to?("name=")</tt>, and - # <tt>my_person.respond_to?("name?")</tt>. + # +name+ attribute can answer <tt>true</tt> to <tt>my_person.respond_to?(:name)</tt>, <tt>my_person.respond_to?(:name=)</tt>, and + # <tt>my_person.respond_to?(:name?)</tt>. def respond_to?(method, include_priv = false) method_name = method.to_s if attributes.nil? @@ -940,14 +945,14 @@ module ActiveResource # Update the resource on the remote service. def update - returning connection.put(element_path(prefix_options), to_xml, self.class.headers) do |response| + returning connection.put(element_path(prefix_options), encode, self.class.headers) do |response| load_attributes_from_response(response) end end # Create (i.e., \save to the remote service) the \new resource. def create - returning connection.post(collection_path, to_xml, self.class.headers) do |response| + returning connection.post(collection_path, encode, self.class.headers) do |response| self.id = id_from_response(response) load_attributes_from_response(response) end @@ -1013,7 +1018,7 @@ module ActiveResource end def split_options(options = {}) - self.class.send!(:split_options, options) + self.class.__send__(:split_options, options) end def method_missing(method_symbol, *arguments) #:nodoc: diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb index d64fb79f1e..fe9c2d57fe 100644 --- a/activeresource/lib/active_resource/connection.rb +++ b/activeresource/lib/active_resource/connection.rb @@ -63,6 +63,13 @@ module ActiveResource # This class is used by ActiveResource::Base to interface with REST # services. class Connection + + HTTP_FORMAT_HEADER_NAMES = { :get => 'Accept', + :put => 'Content-Type', + :post => 'Content-Type', + :delete => 'Accept' + } + attr_reader :site, :user, :password, :timeout attr_accessor :format @@ -106,25 +113,25 @@ module ActiveResource # Execute a GET request. # Used to get (find) resources. def get(path, headers = {}) - format.decode(request(:get, path, build_request_headers(headers)).body) + format.decode(request(:get, path, build_request_headers(headers, :get)).body) end # Execute a DELETE request (see HTTP protocol documentation if unfamiliar). # Used to delete resources. def delete(path, headers = {}) - request(:delete, path, build_request_headers(headers)) + request(:delete, path, build_request_headers(headers, :delete)) end # Execute a PUT request (see HTTP protocol documentation if unfamiliar). # Used to update resources. def put(path, body = '', headers = {}) - request(:put, path, body.to_s, build_request_headers(headers)) + request(:put, path, body.to_s, build_request_headers(headers, :put)) end # Execute a POST request. # Used to create new resources. def post(path, body = '', headers = {}) - request(:post, path, body.to_s, build_request_headers(headers)) + request(:post, path, body.to_s, build_request_headers(headers, :post)) end # Execute a HEAD request. @@ -187,12 +194,12 @@ module ActiveResource end def default_header - @default_header ||= { 'Content-Type' => format.mime_type } + @default_header ||= {} end # Builds headers for request to remote service. - def build_request_headers(headers) - authorization_header.update(default_header).update(headers) + def build_request_headers(headers, http_method=nil) + authorization_header.update(default_header).update(headers).update(http_format_header(http_method)) end # Sets authorization header @@ -200,6 +207,10 @@ module ActiveResource (@user || @password ? { 'Authorization' => 'Basic ' + ["#{@user}:#{ @password}"].pack('m').delete("\r\n") } : {}) end + def http_format_header(http_method) + {HTTP_FORMAT_HEADER_NAMES[http_method] => format.mime_type} + end + def logger #:nodoc: Base.logger end diff --git a/activeresource/lib/active_resource/custom_methods.rb b/activeresource/lib/active_resource/custom_methods.rb index 770116ceb7..24306f251d 100644 --- a/activeresource/lib/active_resource/custom_methods.rb +++ b/activeresource/lib/active_resource/custom_methods.rb @@ -30,7 +30,7 @@ module ActiveResource # Person.get(:active) # GET /people/active.xml # # => [{:id => 1, :name => 'Ryan'}, {:id => 2, :name => 'Joe'}] # - module CustomMethods + module CustomMethods def self.included(base) base.class_eval do extend ActiveResource::CustomMethods::ClassMethods @@ -83,24 +83,25 @@ module ActiveResource "#{prefix(prefix_options)}#{collection_name}/#{method_name}.#{format.extension}#{query_string(query_options)}" end end - + module InstanceMethods def get(method_name, options = {}) connection.get(custom_method_element_url(method_name, options), self.class.headers) end - - def post(method_name, options = {}, body = '') + + def post(method_name, options = {}, body = nil) + request_body = body.nil? ? encode : body if new? - connection.post(custom_method_new_element_url(method_name, options), (body.nil? ? to_xml : body), self.class.headers) + connection.post(custom_method_new_element_url(method_name, options), request_body, self.class.headers) else - connection.post(custom_method_element_url(method_name, options), body, self.class.headers) + connection.post(custom_method_element_url(method_name, options), request_body, self.class.headers) end end - + def put(method_name, options = {}, body = '') connection.put(custom_method_element_url(method_name, options), body, self.class.headers) end - + def delete(method_name, options = {}) connection.delete(custom_method_element_url(method_name, options), self.class.headers) end @@ -108,11 +109,11 @@ module ActiveResource private def custom_method_element_url(method_name, options = {}) - "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.send!(:query_string, options)}" + "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}" end - + def custom_method_new_element_url(method_name, options = {}) - "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.send!(:query_string, options)}" + "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}" end end end diff --git a/activeresource/lib/active_resource/formats/json_format.rb b/activeresource/lib/active_resource/formats/json_format.rb index df0d6ca372..9e269d4ded 100644 --- a/activeresource/lib/active_resource/formats/json_format.rb +++ b/activeresource/lib/active_resource/formats/json_format.rb @@ -2,22 +2,22 @@ module ActiveResource module Formats module JsonFormat extend self - + def extension "json" end - + def mime_type "application/json" end - - def encode(hash) + + def encode(hash, options={}) hash.to_json end - + def decode(json) ActiveSupport::JSON.decode(json) end end end -end
\ No newline at end of file +end diff --git a/activeresource/lib/active_resource/formats/xml_format.rb b/activeresource/lib/active_resource/formats/xml_format.rb index 5e97ffa776..86c6cec745 100644 --- a/activeresource/lib/active_resource/formats/xml_format.rb +++ b/activeresource/lib/active_resource/formats/xml_format.rb @@ -2,23 +2,23 @@ module ActiveResource module Formats module XmlFormat extend self - + def extension "xml" end - + def mime_type "application/xml" end - - def encode(hash) - hash.to_xml + + def encode(hash, options={}) + hash.to_xml(options) end - + def decode(xml) from_xml_data(Hash.from_xml(xml)) end - + private # Manipulate from_xml Hash, because xml_simple is not exactly what we # want for Active Resource. @@ -28,7 +28,7 @@ module ActiveResource else data end - end + end end end -end
\ No newline at end of file +end diff --git a/activeresource/lib/active_resource/http_mock.rb b/activeresource/lib/active_resource/http_mock.rb index 554fc3bcfc..9ed532b48c 100644 --- a/activeresource/lib/active_resource/http_mock.rb +++ b/activeresource/lib/active_resource/http_mock.rb @@ -146,7 +146,7 @@ module ActiveResource attr_accessor :path, :method, :body, :headers def initialize(method, path, body = nil, headers = {}) - @method, @path, @body, @headers = method, path, body, headers.reverse_merge('Content-Type' => 'application/xml') + @method, @path, @body, @headers = method, path, body, headers.merge(ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[method] => 'application/xml') end def ==(other_request) diff --git a/activeresource/test/authorization_test.rb b/activeresource/test/authorization_test.rb index 9215227620..ead7f5c12f 100644 --- a/activeresource/test/authorization_test.rb +++ b/activeresource/test/authorization_test.rb @@ -19,7 +19,7 @@ class AuthorizationTest < Test::Unit::TestCase end def test_authorization_header - authorization_header = @authenticated_conn.send!(:authorization_header) + authorization_header = @authenticated_conn.__send__(:authorization_header) assert_equal @authorization_request_header['Authorization'], authorization_header['Authorization'] authorization = authorization_header["Authorization"].to_s.split @@ -29,7 +29,7 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_with_username_but_no_password @conn = ActiveResource::Connection.new("http://david:@localhost") - authorization_header = @conn.send!(:authorization_header) + authorization_header = @conn.__send__(:authorization_header) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -38,7 +38,7 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_with_password_but_no_username @conn = ActiveResource::Connection.new("http://:test123@localhost") - authorization_header = @conn.send!(:authorization_header) + authorization_header = @conn.__send__(:authorization_header) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -47,7 +47,7 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_with_decoded_credentials_from_url @conn = ActiveResource::Connection.new("http://my%40email.com:%31%32%33@localhost") - authorization_header = @conn.send!(:authorization_header) + authorization_header = @conn.__send__(:authorization_header) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -58,7 +58,7 @@ class AuthorizationTest < Test::Unit::TestCase @authenticated_conn = ActiveResource::Connection.new("http://@localhost") @authenticated_conn.user = 'david' @authenticated_conn.password = 'test123' - authorization_header = @authenticated_conn.send!(:authorization_header) + authorization_header = @authenticated_conn.__send__(:authorization_header) assert_equal @authorization_request_header['Authorization'], authorization_header['Authorization'] authorization = authorization_header["Authorization"].to_s.split @@ -69,7 +69,7 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_explicitly_setting_username_but_no_password @conn = ActiveResource::Connection.new("http://@localhost") @conn.user = "david" - authorization_header = @conn.send!(:authorization_header) + authorization_header = @conn.__send__(:authorization_header) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -79,7 +79,7 @@ class AuthorizationTest < Test::Unit::TestCase def test_authorization_header_explicitly_setting_password_but_no_username @conn = ActiveResource::Connection.new("http://@localhost") @conn.password = "test123" - authorization_header = @conn.send!(:authorization_header) + authorization_header = @conn.__send__(:authorization_header) authorization = authorization_header["Authorization"].to_s.split assert_equal "Basic", authorization[0] @@ -116,7 +116,7 @@ class AuthorizationTest < Test::Unit::TestCase protected def assert_response_raises(klass, code) assert_raise(klass, "Expected response code #{code} to raise #{klass}") do - @conn.send!(:handle_response, Response.new(code)) + @conn.__send__(:handle_response, Response.new(code)) end end end diff --git a/activeresource/test/base/custom_methods_test.rb b/activeresource/test/base/custom_methods_test.rb index 62c33ef9bc..ba5799edfb 100644 --- a/activeresource/test/base/custom_methods_test.rb +++ b/activeresource/test/base/custom_methods_test.rb @@ -10,8 +10,7 @@ class CustomMethodsTest < Test::Unit::TestCase @ryan = { :name => 'Ryan' }.to_xml(:root => 'person') @addy = { :id => 1, :street => '12345 Street' }.to_xml(:root => 'address') @addy_deep = { :id => 1, :street => '12345 Street', :zip => "27519" }.to_xml(:root => 'address') - @default_request_headers = { 'Content-Type' => 'application/xml' } - + ActiveResource::HttpMock.respond_to do |mock| mock.get "/people/1.xml", {}, @matz mock.get "/people/1/shallow.xml", {}, @matz diff --git a/activeresource/test/base/load_test.rb b/activeresource/test/base/load_test.rb index 737afb1748..a475fab34e 100644 --- a/activeresource/test/base/load_test.rb +++ b/activeresource/test/base/load_test.rb @@ -84,7 +84,7 @@ class BaseLoadTest < Test::Unit::TestCase end def test_load_collection_with_unknown_resource - Person.send!(:remove_const, :Address) if Person.const_defined?(:Address) + Person.__send__(:remove_const, :Address) if Person.const_defined?(:Address) assert !Person.const_defined?(:Address), "Address shouldn't exist until autocreated" addresses = silence_warnings { @person.load(:addresses => @addresses).addresses } assert Person.const_defined?(:Address), "Address should have been autocreated" @@ -100,7 +100,7 @@ class BaseLoadTest < Test::Unit::TestCase end def test_load_collection_with_single_unknown_resource - Person.send!(:remove_const, :Address) if Person.const_defined?(:Address) + Person.__send__(:remove_const, :Address) if Person.const_defined?(:Address) assert !Person.const_defined?(:Address), "Address shouldn't exist until autocreated" addresses = silence_warnings { @person.load(:addresses => [ @first_address ]).addresses } assert Person.const_defined?(:Address), "Address should have been autocreated" diff --git a/activeresource/test/base_test.rb b/activeresource/test/base_test.rb index 9a0789e0b4..7460fd45b0 100644 --- a/activeresource/test/base_test.rb +++ b/activeresource/test/base_test.rb @@ -468,7 +468,7 @@ class BaseTest < Test::Unit::TestCase def test_prefix assert_equal "/", Person.prefix - assert_equal Set.new, Person.send!(:prefix_parameters) + assert_equal Set.new, Person.__send__(:prefix_parameters) end def test_set_prefix @@ -504,7 +504,7 @@ class BaseTest < Test::Unit::TestCase def test_custom_prefix assert_equal '/people//', StreetAddress.prefix assert_equal '/people/1/', StreetAddress.prefix(:person_id => 1) - assert_equal [:person_id].to_set, StreetAddress.send!(:prefix_parameters) + assert_equal [:person_id].to_set, StreetAddress.__send__(:prefix_parameters) end def test_find_by_id @@ -607,10 +607,10 @@ class BaseTest < Test::Unit::TestCase def test_id_from_response p = Person.new resp = {'Location' => '/foo/bar/1'} - assert_equal '1', p.send!(:id_from_response, resp) + assert_equal '1', p.__send__(:id_from_response, resp) resp['Location'] << '.xml' - assert_equal '1', p.send!(:id_from_response, resp) + assert_equal '1', p.__send__(:id_from_response, resp) end def test_create_with_custom_prefix @@ -825,7 +825,7 @@ class BaseTest < Test::Unit::TestCase def test_to_xml matz = Person.find(1) - xml = matz.to_xml + xml = matz.encode assert xml.starts_with?('<?xml version="1.0" encoding="UTF-8"?>') assert xml.include?('<name>Matz</name>') assert xml.include?('<id type="integer">1</id>') diff --git a/activeresource/test/connection_test.rb b/activeresource/test/connection_test.rb index 8e43e451ff..06f31f1b57 100644 --- a/activeresource/test/connection_test.rb +++ b/activeresource/test/connection_test.rb @@ -185,6 +185,6 @@ class ConnectionTest < Test::Unit::TestCase end def handle_response(response) - @conn.send!(:handle_response, response) + @conn.__send__(:handle_response, response) end end diff --git a/activeresource/test/format_test.rb b/activeresource/test/format_test.rb index 3c81803fce..365576a092 100644 --- a/activeresource/test/format_test.rb +++ b/activeresource/test/format_test.rb @@ -5,14 +5,22 @@ class FormatTest < Test::Unit::TestCase def setup @matz = { :id => 1, :name => 'Matz' } @david = { :id => 2, :name => 'David' } - + @programmers = [ @matz, @david ] end - + + def test_http_format_header_name + header_name = ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:get] + assert_equal 'Accept', header_name + + headers_names = [ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:put], ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:post]] + headers_names.each{|header_name| assert_equal 'Content-Type', header_name} + end + def test_formats_on_single_element for format in [ :json, :xml ] using_format(Person, format) do - ActiveResource::HttpMock.respond_to.get "/people/1.#{format}", {}, ActiveResource::Formats[format].encode(@david) + ActiveResource::HttpMock.respond_to.get "/people/1.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david) assert_equal @david[:name], Person.find(1).name end end @@ -21,7 +29,7 @@ class FormatTest < Test::Unit::TestCase def test_formats_on_collection for format in [ :json, :xml ] using_format(Person, format) do - ActiveResource::HttpMock.respond_to.get "/people.#{format}", {}, ActiveResource::Formats[format].encode(@programmers) + ActiveResource::HttpMock.respond_to.get "/people.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@programmers) remote_programmers = Person.find(:all) assert_equal 2, remote_programmers.size assert remote_programmers.select { |p| p.name == 'David' } @@ -32,7 +40,7 @@ class FormatTest < Test::Unit::TestCase def test_formats_on_custom_collection_method for format in [ :json, :xml ] using_format(Person, format) do - ActiveResource::HttpMock.respond_to.get "/people/retrieve.#{format}?name=David", {}, ActiveResource::Formats[format].encode([@david]) + ActiveResource::HttpMock.respond_to.get "/people/retrieve.#{format}?name=David", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode([@david]) remote_programmers = Person.get(:retrieve, :name => 'David') assert_equal 1, remote_programmers.size assert_equal @david[:id], remote_programmers[0]['id'] @@ -40,13 +48,13 @@ class FormatTest < Test::Unit::TestCase end end end - + def test_formats_on_custom_element_method for format in [ :json, :xml ] using_format(Person, format) do ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/2.#{format}", {}, ActiveResource::Formats[format].encode(@david) - mock.get "/people/2/shallow.#{format}", {}, ActiveResource::Formats[format].encode(@david) + mock.get "/people/2.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david) + mock.get "/people/2/shallow.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david) end remote_programmer = Person.find(2).get(:shallow) assert_equal @david[:id], remote_programmer['id'] @@ -57,20 +65,24 @@ class FormatTest < Test::Unit::TestCase for format in [ :json, :xml ] ryan = ActiveResource::Formats[format].encode({ :name => 'Ryan' }) using_format(Person, format) do - ActiveResource::HttpMock.respond_to.post "/people/new/register.#{format}", {}, ryan, 201, 'Location' => "/people/5.#{format}" remote_ryan = Person.new(:name => 'Ryan') + ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, {'Location' => "/people/5.#{format}"} + remote_ryan.save + + remote_ryan = Person.new(:name => 'Ryan') + ActiveResource::HttpMock.respond_to.post "/people/new/register.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, {'Location' => "/people/5.#{format}"} assert_equal ActiveResource::Response.new(ryan, 201, {'Location' => "/people/5.#{format}"}), remote_ryan.post(:register) end end end - + def test_setting_format_before_site resource = Class.new(ActiveResource::Base) resource.format = :json resource.site = 'http://37s.sunrise.i:3000' assert_equal ActiveResource::Formats[:json], resource.connection.format end - + private def using_format(klass, mime_type_reference) previous_format = klass.format diff --git a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb index 8724a492bf..e6143a274b 100644 --- a/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb +++ b/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb @@ -91,14 +91,14 @@ class Class # :nodoc: def inheritable_attributes @inheritable_attributes ||= EMPTY_INHERITABLE_ATTRIBUTES end - + def write_inheritable_attribute(key, value) if inheritable_attributes.equal?(EMPTY_INHERITABLE_ATTRIBUTES) @inheritable_attributes = {} end inheritable_attributes[key] = value end - + def write_inheritable_array(key, elements) write_inheritable_attribute(key, []) if read_inheritable_attribute(key).nil? write_inheritable_attribute(key, read_inheritable_attribute(key) + elements) @@ -112,7 +112,7 @@ class Class # :nodoc: def read_inheritable_attribute(key) inheritable_attributes[key] end - + def reset_inheritable_attributes @inheritable_attributes = EMPTY_INHERITABLE_ATTRIBUTES end @@ -123,7 +123,7 @@ class Class # :nodoc: def inherited_with_inheritable_attributes(child) inherited_without_inheritable_attributes(child) if respond_to?(:inherited_without_inheritable_attributes) - + if inheritable_attributes.equal?(EMPTY_INHERITABLE_ATTRIBUTES) new_inheritable_attributes = EMPTY_INHERITABLE_ATTRIBUTES else @@ -131,7 +131,7 @@ class Class # :nodoc: memo.update(key => value.duplicable? ? value.dup : value) end end - + child.instance_variable_set('@inheritable_attributes', new_inheritable_attributes) end diff --git a/activesupport/lib/active_support/core_ext/date/behavior.rb b/activesupport/lib/active_support/core_ext/date/behavior.rb index 6f8f7c6a82..bd378eb375 100644 --- a/activesupport/lib/active_support/core_ext/date/behavior.rb +++ b/activesupport/lib/active_support/core_ext/date/behavior.rb @@ -1,3 +1,5 @@ +require 'date' + module ActiveSupport #:nodoc: module CoreExtensions #:nodoc: module Date #:nodoc: @@ -10,18 +12,29 @@ module ActiveSupport #:nodoc: # Date memoizes some instance methods using metaprogramming to wrap # the methods with one that caches the result in an instance variable. + # # If a Date is frozen but the memoized method hasn't been called, the # first call will result in a frozen object error since the memo - # instance variable is uninitialized. Work around by eagerly memoizing - # before freezing. - def freeze #:nodoc: - self.class.private_instance_methods(false).each do |m| - if m.to_s =~ /\A__\d+__\Z/ - instance_variable_set(:"@#{m}", [send(m)]) + # instance variable is uninitialized. + # + # Work around by eagerly memoizing before freezing. + # + # Ruby 1.9 uses a preinitialized instance variable so it's unaffected. + # This hack is as close as we can get to feature detection: + begin + ::Date.today.freeze.jd + rescue => frozen_object_error + if frozen_object_error.message =~ /frozen/ + def freeze #:nodoc: + self.class.private_instance_methods(false).each do |m| + if m.to_s =~ /\A__\d+__\Z/ + instance_variable_set(:"@#{m}", [send(m)]) + end + end + + super end end - - super end end end diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index e451e9933a..fd94bc051f 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -64,8 +64,28 @@ module Enumerable end end + # Iterates over a collection, passing the current element *and* the + # +memo+ to the block. Handy for building up hashes or + # reducing collections down to one object. Examples: + # + # %w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } #=> {'foo' => 'FOO', 'bar' => 'BAR'} + # + # *Note* that you can't use immutable objects like numbers, true or false as + # the memo. You would think the following returns 120, but since the memo is + # never changed, it does not. + # + # (1..5).each_with_object(1) { |value, memo| memo *= value } # => 1 + # + def each_with_object(memo, &block) + returning memo do |memo| + each do |element| + block.call(element, memo) + end + end + end unless [].respond_to?(:each_with_object) + # Convert an enumerable to a hash. Examples: - # + # # people.index_by(&:login) # => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...} # people.index_by { |person| "#{person.first_name} #{person.last_name}" } diff --git a/activesupport/lib/active_support/core_ext/module.rb b/activesupport/lib/active_support/core_ext/module.rb index 34fcbd124b..da8d28ec13 100644 --- a/activesupport/lib/active_support/core_ext/module.rb +++ b/activesupport/lib/active_support/core_ext/module.rb @@ -7,7 +7,17 @@ require 'active_support/core_ext/module/introspection' require 'active_support/core_ext/module/loading' require 'active_support/core_ext/module/aliasing' require 'active_support/core_ext/module/model_naming' +require 'active_support/core_ext/module/synchronization' + +module ActiveSupport + module CoreExtensions + # Various extensions for the Ruby core Module class. + module Module + # Nothing here. Only defined for API documentation purposes. + end + end +end class Module - include ActiveSupport::CoreExt::Module::ModelNaming + include ActiveSupport::CoreExtensions::Module end diff --git a/activesupport/lib/active_support/core_ext/module/aliasing.rb b/activesupport/lib/active_support/core_ext/module/aliasing.rb index 1894e3b0a2..e640f64520 100644 --- a/activesupport/lib/active_support/core_ext/module/aliasing.rb +++ b/activesupport/lib/active_support/core_ext/module/aliasing.rb @@ -1,70 +1,74 @@ -class Module - # Encapsulates the common pattern of: - # - # alias_method :foo_without_feature, :foo - # alias_method :foo, :foo_with_feature - # - # With this, you simply do: - # - # alias_method_chain :foo, :feature - # - # And both aliases are set up for you. - # - # Query and bang methods (foo?, foo!) keep the same punctuation: - # - # alias_method_chain :foo?, :feature - # - # is equivalent to - # - # alias_method :foo_without_feature?, :foo? - # alias_method :foo?, :foo_with_feature? - # - # so you can safely chain foo, foo?, and foo! with the same feature. - def alias_method_chain(target, feature) - # Strip out punctuation on predicates or bang methods since - # e.g. target?_without_feature is not a valid method name. - aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1 - yield(aliased_target, punctuation) if block_given? - - with_method, without_method = "#{aliased_target}_with_#{feature}#{punctuation}", "#{aliased_target}_without_#{feature}#{punctuation}" - - alias_method without_method, target - alias_method target, with_method - - case - when public_method_defined?(without_method) - public target - when protected_method_defined?(without_method) - protected target - when private_method_defined?(without_method) - private target - end - end +module ActiveSupport + module CoreExtensions + module Module + # Encapsulates the common pattern of: + # + # alias_method :foo_without_feature, :foo + # alias_method :foo, :foo_with_feature + # + # With this, you simply do: + # + # alias_method_chain :foo, :feature + # + # And both aliases are set up for you. + # + # Query and bang methods (foo?, foo!) keep the same punctuation: + # + # alias_method_chain :foo?, :feature + # + # is equivalent to + # + # alias_method :foo_without_feature?, :foo? + # alias_method :foo?, :foo_with_feature? + # + # so you can safely chain foo, foo?, and foo! with the same feature. + def alias_method_chain(target, feature) + # Strip out punctuation on predicates or bang methods since + # e.g. target?_without_feature is not a valid method name. + aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1 + yield(aliased_target, punctuation) if block_given? + + with_method, without_method = "#{aliased_target}_with_#{feature}#{punctuation}", "#{aliased_target}_without_#{feature}#{punctuation}" - # Allows you to make aliases for attributes, which includes - # getter, setter, and query methods. - # - # Example: - # - # class Content < ActiveRecord::Base - # # has a title attribute - # end - # - # class Email < Content - # alias_attribute :subject, :title - # end - # - # e = Email.find(1) - # e.title # => "Superstars" - # e.subject # => "Superstars" - # e.subject? # => true - # e.subject = "Megastars" - # e.title # => "Megastars" - def alias_attribute(new_name, old_name) - module_eval <<-STR, __FILE__, __LINE__+1 - def #{new_name}; self.#{old_name}; end - def #{new_name}?; self.#{old_name}?; end - def #{new_name}=(v); self.#{old_name} = v; end - STR + alias_method without_method, target + alias_method target, with_method + + case + when public_method_defined?(without_method) + public target + when protected_method_defined?(without_method) + protected target + when private_method_defined?(without_method) + private target + end + end + + # Allows you to make aliases for attributes, which includes + # getter, setter, and query methods. + # + # Example: + # + # class Content < ActiveRecord::Base + # # has a title attribute + # end + # + # class Email < Content + # alias_attribute :subject, :title + # end + # + # e = Email.find(1) + # e.title # => "Superstars" + # e.subject # => "Superstars" + # e.subject? # => true + # e.subject = "Megastars" + # e.title # => "Megastars" + def alias_attribute(new_name, old_name) + module_eval <<-STR, __FILE__, __LINE__+1 + def #{new_name}; self.#{old_name}; end + def #{new_name}?; self.#{old_name}?; end + def #{new_name}=(v); self.#{old_name} = v; end + STR + end + end end end diff --git a/activesupport/lib/active_support/core_ext/module/introspection.rb b/activesupport/lib/active_support/core_ext/module/introspection.rb index 45f3e4bf5c..8beaff4b82 100644 --- a/activesupport/lib/active_support/core_ext/module/introspection.rb +++ b/activesupport/lib/active_support/core_ext/module/introspection.rb @@ -1,86 +1,90 @@ -class Module - # Returns the name of the module containing this one. - # - # p M::N.parent_name # => "M" - def parent_name - unless defined? @parent_name - @parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil - end - @parent_name - end +module ActiveSupport + module CoreExtensions + module Module + # Returns the name of the module containing this one. + # + # p M::N.parent_name # => "M" + def parent_name + unless defined? @parent_name + @parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil + end + @parent_name + end - # Returns the module which contains this one according to its name. - # - # module M - # module N - # end - # end - # X = M::N - # - # p M::N.parent # => M - # p X.parent # => M - # - # The parent of top-level and anonymous modules is Object. - # - # p M.parent # => Object - # p Module.new.parent # => Object - # - def parent - parent_name ? parent_name.constantize : Object - end + # Returns the module which contains this one according to its name. + # + # module M + # module N + # end + # end + # X = M::N + # + # p M::N.parent # => M + # p X.parent # => M + # + # The parent of top-level and anonymous modules is Object. + # + # p M.parent # => Object + # p Module.new.parent # => Object + # + def parent + parent_name ? parent_name.constantize : Object + end - # Returns all the parents of this module according to its name, ordered from - # nested outwards. The receiver is not contained within the result. - # - # module M - # module N - # end - # end - # X = M::N - # - # p M.parents # => [Object] - # p M::N.parents # => [M, Object] - # p X.parents # => [M, Object] - # - def parents - parents = [] - if parent_name - parts = parent_name.split('::') - until parts.empty? - parents << (parts * '::').constantize - parts.pop + # Returns all the parents of this module according to its name, ordered from + # nested outwards. The receiver is not contained within the result. + # + # module M + # module N + # end + # end + # X = M::N + # + # p M.parents # => [Object] + # p M::N.parents # => [M, Object] + # p X.parents # => [M, Object] + # + def parents + parents = [] + if parent_name + parts = parent_name.split('::') + until parts.empty? + parents << (parts * '::').constantize + parts.pop + end + end + parents << Object unless parents.include? Object + parents end - end - parents << Object unless parents.include? Object - parents - end - if RUBY_VERSION < '1.9' - # Returns the constants that have been defined locally by this object and - # not in an ancestor. This method is exact if running under Ruby 1.9. In - # previous versions it may miss some constants if their definition in some - # ancestor is identical to their definition in the receiver. - def local_constants - inherited = {} + if RUBY_VERSION < '1.9' + # Returns the constants that have been defined locally by this object and + # not in an ancestor. This method is exact if running under Ruby 1.9. In + # previous versions it may miss some constants if their definition in some + # ancestor is identical to their definition in the receiver. + def local_constants + inherited = {} + + ancestors.each do |anc| + next if anc == self + anc.constants.each { |const| inherited[const] = anc.const_get(const) } + end - ancestors.each do |anc| - next if anc == self - anc.constants.each { |const| inherited[const] = anc.const_get(const) } + constants.select do |const| + !inherited.key?(const) || inherited[const].object_id != const_get(const).object_id + end + end + else + def local_constants #:nodoc: + constants(false) + end end - constants.select do |const| - !inherited.key?(const) || inherited[const].object_id != const_get(const).object_id + # Returns the names of the constants defined locally rather than the + # constants themselves. See <tt>local_constants</tt>. + def local_constant_names + local_constants.map { |c| c.to_s } end end - else - def local_constants #:nodoc: - constants(false) - end - end - - # Returns the names of the constants defined locally rather than the - # constants themselves. See <tt>local_constants</tt>. - def local_constant_names - local_constants.map { |c| c.to_s } end end diff --git a/activesupport/lib/active_support/core_ext/module/model_naming.rb b/activesupport/lib/active_support/core_ext/module/model_naming.rb index 5518f5417b..3ec4f3ba11 100644 --- a/activesupport/lib/active_support/core_ext/module/model_naming.rb +++ b/activesupport/lib/active_support/core_ext/module/model_naming.rb @@ -11,12 +11,12 @@ module ActiveSupport end end - module CoreExt + module CoreExtensions module Module - module ModelNaming - def model_name - @model_name ||= ModelName.new(name) - end + # Returns an ActiveSupport::ModelName object for module. It can be + # used to retrieve all kinds of naming-related information. + def model_name + @model_name ||= ModelName.new(name) end end end diff --git a/activesupport/lib/active_support/core_ext/module/synchronization.rb b/activesupport/lib/active_support/core_ext/module/synchronization.rb new file mode 100644 index 0000000000..6253594dfa --- /dev/null +++ b/activesupport/lib/active_support/core_ext/module/synchronization.rb @@ -0,0 +1,36 @@ +class Module + # Synchronize access around a method, delegating synchronization to a + # particular mutex. A mutex (either a Mutex, or any object that responds to + # #synchronize and yields to a block) must be provided as a final :with option. + # The :with option should be a symbol or string, and can represent a method, + # constant, or instance or class variable. + # Example: + # class SharedCache + # @@lock = Mutex.new + # def expire + # ... + # end + # synchronize :expire, :with => :@@lock + # end + def synchronize(*methods) + options = methods.extract_options! + unless options.is_a?(Hash) && with = options[:with] + raise ArgumentError, "Synchronization needs a mutex. Supply an options hash with a :with key as the last argument (e.g. synchronize :hello, :with => :@mutex)." + end + + methods.flatten.each do |method| + aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1 + if instance_methods.include?("#{aliased_method}_without_synchronization#{punctuation}") + raise ArgumentError, "#{method} is already synchronized. Double synchronization is not currently supported." + end + module_eval(<<-EOS, __FILE__, __LINE__) + def #{aliased_method}_with_synchronization#{punctuation}(*args, &block) + #{with}.synchronize do + #{aliased_method}_without_synchronization#{punctuation}(*args, &block) + end + end + EOS + alias_method_chain method, :synchronization + end + end +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb index 8384a12327..06a7d05702 100644 --- a/activesupport/lib/active_support/core_ext/object/misc.rb +++ b/activesupport/lib/active_support/core_ext/object/misc.rb @@ -1,9 +1,4 @@ class Object - unless respond_to?(:send!) - # Anticipating Ruby 1.9 neutering send - alias send! send - end - # A Ruby-ized realization of the K combinator, courtesy of Mikael Brockman. # # def foo diff --git a/activesupport/lib/active_support/core_ext/range/blockless_step.rb b/activesupport/lib/active_support/core_ext/range/blockless_step.rb index 39dac85636..6fa1eb5bee 100644 --- a/activesupport/lib/active_support/core_ext/range/blockless_step.rb +++ b/activesupport/lib/active_support/core_ext/range/blockless_step.rb @@ -8,7 +8,7 @@ module ActiveSupport #:nodoc: end if RUBY_VERSION < '1.9' - def step_with_blockless(value, &block) + def step_with_blockless(value = 1, &block) if block_given? step_without_blockless(value, &block) else @@ -18,7 +18,7 @@ module ActiveSupport #:nodoc: end end else - def step_with_blockless(value, &block) + def step_with_blockless(value = 1, &block) if block_given? step_without_blockless(value, &block) else diff --git a/activesupport/lib/active_support/core_ext/rexml.rb b/activesupport/lib/active_support/core_ext/rexml.rb new file mode 100644 index 0000000000..af8ce3af47 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/rexml.rb @@ -0,0 +1,35 @@ +require 'rexml/document' +require 'rexml/entity' + +# Fixes the rexml vulnerability disclosed at: +# http://www.ruby-lang.org/en/news/2008/08/23/dos-vulnerability-in-rexml/ +# This fix is identical to rexml-expansion-fix version 1.0.1 + +unless REXML::VERSION > "3.1.7.2" + module REXML + class Entity < Child + undef_method :unnormalized + def unnormalized + document.record_entity_expansion! if document + v = value() + return nil if v.nil? + @unnormalized = Text::unnormalize(v, parent) + @unnormalized + end + end + class Document < Element + @@entity_expansion_limit = 10_000 + def self.entity_expansion_limit= val + @@entity_expansion_limit = val + end + + def record_entity_expansion! + @number_of_expansions ||= 0 + @number_of_expansions += 1 + if @number_of_expansions > @@entity_expansion_limit + raise "Number of entity expansions exceeded, processing aborted." + end + end + end + end +end diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb index 079ecdd48e..9d8eb73908 100644 --- a/activesupport/lib/active_support/core_ext/time/zones.rb +++ b/activesupport/lib/active_support/core_ext/time/zones.rb @@ -78,7 +78,7 @@ module ActiveSupport #:nodoc: # # Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00 def in_time_zone(zone = ::Time.zone) - ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.send!(:get_zone, zone)) + ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.__send__(:get_zone, zone)) end end end diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb index 01eb5df593..950bca60a6 100644 --- a/activesupport/lib/active_support/deprecation.rb +++ b/activesupport/lib/active_support/deprecation.rb @@ -109,7 +109,7 @@ module ActiveSupport end def deprecation_horizon - '2.0' + '2.3' end end @@ -162,6 +162,22 @@ module ActiveSupport end end + class DeprecatedObjectProxy < DeprecationProxy + def initialize(object, message) + @object = object + @message = message + end + + private + def target + @object + end + + def warn(callstack, called, args) + ActiveSupport::Deprecation.warn(@message, callstack) + end + end + # Stand-in for <tt>@request</tt>, <tt>@attributes</tt>, <tt>@params</tt>, etc. # which emits deprecation warnings on any method call (except +inspect+). class DeprecatedInstanceVariableProxy < DeprecationProxy #:nodoc: diff --git a/activesupport/lib/active_support/option_merger.rb b/activesupport/lib/active_support/option_merger.rb index c77bca1ac9..b563b093ed 100644 --- a/activesupport/lib/active_support/option_merger.rb +++ b/activesupport/lib/active_support/option_merger.rb @@ -11,7 +11,7 @@ module ActiveSupport private def method_missing(method, *arguments, &block) arguments << (arguments.last.respond_to?(:to_hash) ? @options.deep_merge(arguments.pop) : @options.dup) - @context.send!(method, *arguments, &block) + @context.__send__(method, *arguments, &block) end end end diff --git a/activesupport/lib/active_support/testing/core_ext/test/unit/assertions.rb b/activesupport/lib/active_support/testing/core_ext/test/unit/assertions.rb index 70a44eab8c..63d1ba6507 100644 --- a/activesupport/lib/active_support/testing/core_ext/test/unit/assertions.rb +++ b/activesupport/lib/active_support/testing/core_ext/test/unit/assertions.rb @@ -36,7 +36,11 @@ module Test # post :delete, :id => ... # end def assert_difference(expressions, difference = 1, message = nil, &block) - expression_evaluations = Array(expressions).collect{ |expression| lambda { eval(expression, block.send!(:binding)) } } + expression_evaluations = Array(expressions).map do |expression| + lambda do + eval(expression, block.__send__(:binding)) + end + end original_values = expression_evaluations.inject([]) { |memo, expression| memo << expression.call } yield diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index 4866fa0dc8..75591b7c34 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -275,7 +275,7 @@ module ActiveSupport end def marshal_load(variables) - initialize(variables[0].utc, ::Time.send!(:get_zone, variables[1]), variables[2].utc) + initialize(variables[0].utc, ::Time.__send__(:get_zone, variables[1]), variables[2].utc) end # Ensure proxy class responds to all methods that underlying time instance responds to. diff --git a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb b/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb index 2e966a51be..da89b30c54 100644 --- a/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb +++ b/activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb @@ -3,6 +3,9 @@ require 'strscan' module I18n module Backend class Simple + INTERPOLATION_RESERVED_KEYS = %w(scope default) + MATCH = /(\\\\)?\{\{([^\}]+)\}\}/ + # Accepts a list of paths to translation files. Loads translations from # plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml # for details. @@ -114,29 +117,29 @@ module I18n # the <tt>{{...}}</tt> key in a string (once for the string and once for the # interpolation). def interpolate(locale, string, values = {}) - return string if !string.is_a?(String) + return string unless string.is_a?(String) string = string.gsub(/%d/, '{{count}}').gsub(/%s/, '{{value}}') + if string.respond_to?(:force_encoding) - original_encoding = string.encoding - string.force_encoding(Encoding::BINARY) - end - s = StringScanner.new(string) - - while s.skip_until(/\{\{/) - s.string[s.pos - 3, 1] = '' and next if s.pre_match[-1, 1] == '\\' - start_pos = s.pos - 2 - key = s.scan_until(/\}\}/)[0..-3] - end_pos = s.pos - 1 + original_encoding = string.encoding + string.force_encoding(Encoding::BINARY) + end - raise ReservedInterpolationKey.new(key, string) if %w(scope default).include?(key) - raise MissingInterpolationArgument.new(key, string) unless values.has_key? key.to_sym + result = string.gsub(MATCH) do + escaped, pattern, key = $1, $2, $2.to_sym - s.string[start_pos..end_pos] = values[key.to_sym].to_s - s.unscan + if escaped + pattern + elsif INTERPOLATION_RESERVED_KEYS.include?(pattern) + raise ReservedInterpolationKey.new(pattern, string) + elsif !values.include?(key) + raise MissingInterpolationArgument.new(pattern, string) + else + values[key].to_s + end end - - result = s.string + result.force_encoding(original_encoding) if original_encoding result end diff --git a/activesupport/test/buffered_logger_test.rb b/activesupport/test/buffered_logger_test.rb index 6319c09210..28dd34334f 100644 --- a/activesupport/test/buffered_logger_test.rb +++ b/activesupport/test/buffered_logger_test.rb @@ -134,6 +134,7 @@ class BufferedLoggerTest < Test::Unit::TestCase a.join b.join - assert_equal "a\nb\nc\nx\ny\nz\n", @output.string + assert @output.string.include?("a\nb\nc\n") + assert @output.string.include?("x\ny\nz\n") end end diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index 2315d8f3db..deb9b7544d 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -58,6 +58,11 @@ class EnumerableTests < Test::Unit::TestCase assert_equal Payment.new(0), [].sum(Payment.new(0)) end + def test_each_with_object + result = %w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } + assert_equal({'foo' => 'FOO', 'bar' => 'BAR'}, result) + end + def test_index_by payments = [ Payment.new(5), Payment.new(15), Payment.new(10) ] assert_equal({ 5 => payments[0], 15 => payments[1], 10 => payments[2] }, diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index fc8ed45358..7a414e946f 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -62,7 +62,7 @@ class HashExtTest < Test::Unit::TestCase @symbols = @symbols.with_indifferent_access @mixed = @mixed.with_indifferent_access - assert_equal 'a', @strings.send!(:convert_key, :a) + assert_equal 'a', @strings.__send__(:convert_key, :a) assert_equal 1, @strings.fetch('a') assert_equal 1, @strings.fetch(:a.to_s) @@ -75,9 +75,9 @@ class HashExtTest < Test::Unit::TestCase hashes.each do |name, hash| method_map.sort_by { |m| m.to_s }.each do |meth, expected| - assert_equal(expected, hash.send!(meth, 'a'), + assert_equal(expected, hash.__send__(meth, 'a'), "Calling #{name}.#{meth} 'a'") - assert_equal(expected, hash.send!(meth, :a), + assert_equal(expected, hash.__send__(meth, :a), "Calling #{name}.#{meth} :a") end end @@ -733,7 +733,7 @@ class HashToXmlTest < Test::Unit::TestCase def test_empty_string_works_for_typecast_xml_value assert_nothing_raised do - Hash.send!(:typecast_xml_value, "") + Hash.__send__(:typecast_xml_value, "") end end @@ -839,6 +839,27 @@ class QueryTest < Test::Unit::TestCase :person => {:id => [20, 10]} end + def test_expansion_count_is_limited + assert_raises RuntimeError do + attack_xml = <<-EOT + <?xml version="1.0" encoding="UTF-8"?> + <!DOCTYPE member [ + <!ENTITY a "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;"> + <!ENTITY b "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;"> + <!ENTITY c "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;"> + <!ENTITY d "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;"> + <!ENTITY e "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;"> + <!ENTITY f "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;"> + <!ENTITY g "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"> + ]> + <member> + &a; + </member> + EOT + Hash.from_xml(attack_xml) + end + end + private def assert_query_equal(expected, actual, message = nil) assert_equal expected.split('&'), actual.to_query.split('&') diff --git a/activesupport/test/core_ext/module/synchronization_test.rb b/activesupport/test/core_ext/module/synchronization_test.rb new file mode 100644 index 0000000000..b1d4bc5e06 --- /dev/null +++ b/activesupport/test/core_ext/module/synchronization_test.rb @@ -0,0 +1,85 @@ +require 'abstract_unit' + +class SynchronizationTest < Test::Unit::TestCase + def setup + @target = Class.new + @target.cattr_accessor :mutex, :instance_writer => false + @target.mutex = Mutex.new + @instance = @target.new + end + + def test_synchronize_aliases_method_chain_with_synchronize + @target.module_eval do + attr_accessor :value + synchronize :value, :with => :mutex + end + assert @instance.respond_to?(:value_with_synchronization) + assert @instance.respond_to?(:value_without_synchronization) + end + + def test_synchronize_does_not_change_behavior + @target.module_eval do + attr_accessor :value + synchronize :value, :with => :mutex + end + expected = "some state" + @instance.value = expected + assert_equal expected, @instance.value + end + + def test_synchronize_with_no_mutex_raises_an_argument_error + assert_raises(ArgumentError) do + @target.synchronize :to_s + end + end + + def test_double_synchronize_raises_an_argument_error + @target.synchronize :to_s, :with => :mutex + assert_raises(ArgumentError) do + @target.synchronize :to_s, :with => :mutex + end + end + + def dummy_sync + dummy = Object.new + def dummy.synchronize + @sync_count ||= 0 + @sync_count += 1 + yield + end + def dummy.sync_count; @sync_count; end + dummy + end + + def test_mutex_is_entered_during_method_call + @target.mutex = dummy_sync + @target.synchronize :to_s, :with => :mutex + @instance.to_s + @instance.to_s + assert_equal 2, @target.mutex.sync_count + end + + def test_can_synchronize_method_with_punctuation + @target.module_eval do + def dangerous? + @dangerous + end + def dangerous! + @dangerous = true + end + end + @target.synchronize :dangerous?, :dangerous!, :with => :mutex + @instance.dangerous! + assert @instance.dangerous? + end + + def test_can_synchronize_singleton_methods + @target.mutex = dummy_sync + class << @target + synchronize :to_s, :with => :mutex + end + assert @target.respond_to?(:to_s_without_synchronization) + assert_nothing_raised { @target.to_s; @target.to_s } + assert_equal 2, @target.mutex.sync_count + end +end
\ No newline at end of file diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb index b0a746fdc7..e88dcb52d5 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -108,11 +108,6 @@ class ClassExtTest < Test::Unit::TestCase end class ObjectTests < Test::Unit::TestCase - def test_send_bang_aliases_send_before_19 - assert_respond_to 'a', :send! - assert_equal 1, 'a'.send!(:size) - end - def test_suppress_re_raises assert_raises(LoadError) { suppress(ArgumentError) {raise LoadError} } end diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 39c9c74c94..18ad784837 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -146,42 +146,42 @@ class DependenciesTest < Test::Unit::TestCase def test_directories_manifest_as_modules_unless_const_defined with_loading 'autoloading_fixtures' do assert_kind_of Module, ModuleFolder - Object.send! :remove_const, :ModuleFolder + Object.__send__ :remove_const, :ModuleFolder end end def test_module_with_nested_class with_loading 'autoloading_fixtures' do assert_kind_of Class, ModuleFolder::NestedClass - Object.send! :remove_const, :ModuleFolder + Object.__send__ :remove_const, :ModuleFolder end end def test_module_with_nested_inline_class with_loading 'autoloading_fixtures' do assert_kind_of Class, ModuleFolder::InlineClass - Object.send! :remove_const, :ModuleFolder + Object.__send__ :remove_const, :ModuleFolder end end def test_directories_may_manifest_as_nested_classes with_loading 'autoloading_fixtures' do assert_kind_of Class, ClassFolder - Object.send! :remove_const, :ClassFolder + Object.__send__ :remove_const, :ClassFolder end end def test_class_with_nested_class with_loading 'autoloading_fixtures' do assert_kind_of Class, ClassFolder::NestedClass - Object.send! :remove_const, :ClassFolder + Object.__send__ :remove_const, :ClassFolder end end def test_class_with_nested_inline_class with_loading 'autoloading_fixtures' do assert_kind_of Class, ClassFolder::InlineClass - Object.send! :remove_const, :ClassFolder + Object.__send__ :remove_const, :ClassFolder end end @@ -190,7 +190,7 @@ class DependenciesTest < Test::Unit::TestCase assert_kind_of Class, ClassFolder::ClassFolderSubclass assert_kind_of Class, ClassFolder assert_equal 'indeed', ClassFolder::ClassFolderSubclass::ConstantInClassFolder - Object.send! :remove_const, :ClassFolder + Object.__send__ :remove_const, :ClassFolder end end @@ -199,7 +199,7 @@ class DependenciesTest < Test::Unit::TestCase sibling = ModuleFolder::NestedClass.class_eval "NestedSibling" assert defined?(ModuleFolder::NestedSibling) assert_equal ModuleFolder::NestedSibling, sibling - Object.send! :remove_const, :ModuleFolder + Object.__send__ :remove_const, :ModuleFolder end end @@ -208,7 +208,7 @@ class DependenciesTest < Test::Unit::TestCase assert ! defined?(ModuleFolder) assert_raises(NameError) { ModuleFolder::Object } assert_raises(NameError) { ModuleFolder::NestedClass::Object } - Object.send! :remove_const, :ModuleFolder + Object.__send__ :remove_const, :ModuleFolder end end diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index 0d818f8446..abdb863130 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -40,7 +40,7 @@ Rails::Initializer.run do |config| # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. - # Run "rake -D time" for a list of tasks for finding time zone names. Uncomment to use default local time. + # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. config.time_zone = 'UTC' # Your secret key for verifying cookie session data integrity. diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 008f1de8fa..74d2daa34b 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -488,7 +488,7 @@ Run `rake gems:install` to install the missing gems. # If assigned value cannot be matched to a TimeZone, an exception will be raised. def initialize_time_zone if configuration.time_zone - zone_default = Time.send!(:get_zone, configuration.time_zone) + zone_default = Time.__send__(:get_zone, configuration.time_zone) unless zone_default raise %{Value assigned to config.time_zone not recognized. Run "rake -D time" for a list of tasks for finding appropriate time zone names.} end @@ -784,7 +784,6 @@ Run `rake gems:install` to install the missing gems. def threadsafe! self.cache_classes = true self.dependency_loading = false - self.active_record.allow_concurrency = true self.action_controller.allow_concurrency = true self end diff --git a/railties/lib/tasks/documentation.rake b/railties/lib/tasks/documentation.rake index f4927a0ef1..4ef838626a 100644 --- a/railties/lib/tasks/documentation.rake +++ b/railties/lib/tasks/documentation.rake @@ -1,9 +1,9 @@ namespace :doc do - desc "Generate documentation for the application. Set custom template with TEMPLATE=/path/to/rdoc/template.rb" + desc "Generate documentation for the application. Set custom template with TEMPLATE=/path/to/rdoc/template.rb or title with TITLE=\"Custom Title\"" Rake::RDocTask.new("app") { |rdoc| rdoc.rdoc_dir = 'doc/app' rdoc.template = ENV['template'] if ENV['template'] - rdoc.title = "Rails Application Documentation" + rdoc.title = ENV['title'] || "Rails Application Documentation" rdoc.options << '--line-numbers' << '--inline-source' rdoc.options << '--charset' << 'utf-8' rdoc.rdoc_files.include('doc/README_FOR_APP') diff --git a/railties/test/secret_key_generation_test.rb b/railties/test/secret_key_generation_test.rb index 2a04cff856..7269f98ce5 100644 --- a/railties/test/secret_key_generation_test.rb +++ b/railties/test/secret_key_generation_test.rb @@ -31,6 +31,8 @@ class SecretKeyGenerationTest < Test::Unit::TestCase end def test_secret_key_generation - assert @generator.generate_secret.length >= SECRET_KEY_MIN_LENGTH + assert_deprecated /ActiveSupport::SecureRandom\.hex\(64\)/ do + assert @generator.generate_secret.length >= SECRET_KEY_MIN_LENGTH + end end end |