diff options
author | Emilio Tagua <miloops@gmail.com> | 2011-02-15 12:01:04 -0300 |
---|---|---|
committer | Emilio Tagua <miloops@gmail.com> | 2011-02-15 12:01:04 -0300 |
commit | 8ee0b4414890f919594c1a388d987b5b7364a505 (patch) | |
tree | 6c6c6aa19da0eb8066d2f0b9b02b08f2cc696c29 /actionpack | |
parent | 348c0ec7c656b3691aa4e687565d28259ca0f693 (diff) | |
parent | c9f1ab5365319e087e1b010a3f90626a2b8f080b (diff) | |
download | rails-8ee0b4414890f919594c1a388d987b5b7364a505.tar.gz rails-8ee0b4414890f919594c1a388d987b5b7364a505.tar.bz2 rails-8ee0b4414890f919594c1a388d987b5b7364a505.zip |
Merge remote branch 'rails/master' into identity_map
Conflicts:
activerecord/examples/performance.rb
activerecord/lib/active_record/association_preload.rb
activerecord/lib/active_record/associations.rb
activerecord/lib/active_record/associations/association_proxy.rb
activerecord/lib/active_record/autosave_association.rb
activerecord/lib/active_record/base.rb
activerecord/lib/active_record/nested_attributes.rb
activerecord/test/cases/relations_test.rb
Diffstat (limited to 'actionpack')
102 files changed, 1765 insertions, 622 deletions
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 93b29bcc3a..ee9d30e1fb 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,8 +1,14 @@ *Rails 3.1.0 (unreleased)* -* brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not [Piotr Sarnacki] +* Add an :authenticity_token option to form_tag for custom handling or to omit the token (pass :authenticity_token => false). [Jakub Kuźma, Igor Wiedler] -* url_for and named url helpers now accept :subdomain and :domain as options [Josh Kalderimis] +* HTML5 button_tag helper. [Rizwan Reza] + +* Template lookup now searches further up in the inheritance chain. [Artemave] + +* Brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not. [Piotr Sarnacki] + +* url_for and named url helpers now accept :subdomain and :domain as options, [Josh Kalderimis] * The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused (check the documentation for examples). [Josh Kalderimis] @@ -31,23 +37,24 @@ * Add Rack::Cache to the default stack. Create a Rails store that delegates to the Rails cache, so by default, whatever caching layer you are using will be used for HTTP caching. Note that Rack::Cache will be used if you use #expires_in, #fresh_when or #stale with :public => true. Otherwise, the caching rules will apply to the browser only. [Yehuda Katz, Carl Lerche] + *Rails 3.0.2 (unreleased)* * The helper number_to_currency accepts a new :negative_format option to be able to configure how to render negative amounts. [Don Wilson] + *Rails 3.0.1 (October 15, 2010)* * No Changes, just a version bump. + *Rails 3.0.0 (August 29, 2010)* * password_field renders with nil value by default making the use of passwords secure by default, if you want to render you should do for instance f.password_field(:password, :value => @user.password) [Santiago Pastorino] * Symbols and strings in routes should yield the same behavior. Note this may break existing apps that were using symbols with the new routes API. [José Valim] -* Add clear_helpers as a way to clean up all helpers added to this controller, maintaing just the helper with the same name as the controller. [José Valim] - -* See http://github.com/rails/rails/compare/v3.0.0_RC...v3.0.0_RC2 for gory details +* Add clear_helpers as a way to clean up all helpers added to this controller, maintaining just the helper with the same name as the controller. [José Valim] * Support routing constraints in functional tests. [Andrew White] diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc index 0ad33cfe26..a28d78f688 100644 --- a/actionpack/README.rdoc +++ b/actionpack/README.rdoc @@ -262,7 +262,7 @@ methods: layout "weblog/layout" def index - @posts = Post.find(:all) + @posts = Post.all end def show diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index b7d1d8c2af..f6bc5e0d37 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -21,11 +21,11 @@ Gem::Specification.new do |s| s.add_dependency('activesupport', version) s.add_dependency('activemodel', version) - s.add_dependency('rack-cache', '~> 0.5.3') + s.add_dependency('rack-cache', '~> 1.0.0') s.add_dependency('builder', '~> 3.0.0') s.add_dependency('i18n', '~> 0.5.0') s.add_dependency('rack', '~> 1.2.1') - s.add_dependency('rack-test', '~> 0.5.6') + s.add_dependency('rack-test', '~> 0.5.7') s.add_dependency('rack-mount', '~> 0.6.13') s.add_dependency('tzinfo', '~> 0.3.23') s.add_dependency('erubis', '~> 2.6.6') diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb index f169ab7c3a..95992c2698 100644 --- a/actionpack/lib/abstract_controller/callbacks.rb +++ b/actionpack/lib/abstract_controller/callbacks.rb @@ -13,7 +13,7 @@ module AbstractController # Override AbstractController::Base's process_action to run the # process_action callbacks around the normal behavior. - def process_action(method_name) + def process_action(method_name, *args) run_callbacks(:process_action, method_name) do super end diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index 606f7eedec..4ee54474cc 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -265,11 +265,11 @@ module AbstractController raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil" when nil if name - _prefix = "layouts" unless _implied_layout_name =~ /\blayouts/ + _prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"] self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 def _layout - if template_exists?("#{_implied_layout_name}", #{_prefix.inspect}) + if template_exists?("#{_implied_layout_name}", #{_prefixes.inspect}) "#{_implied_layout_name}" else super diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index 91b75273fa..691310d5d2 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -13,14 +13,15 @@ module AbstractController # This is a class to fix I18n global state. Whenever you provide I18n.locale during a request, # it will trigger the lookup_context and consequently expire the cache. class I18nProxy < ::I18n::Config #:nodoc: - attr_reader :i18n_config, :lookup_context + attr_reader :original_config, :lookup_context - def initialize(i18n_config, lookup_context) - @i18n_config, @lookup_context = i18n_config, lookup_context + def initialize(original_config, lookup_context) + original_config = original_config.original_config if original_config.respond_to?(:original_config) + @original_config, @lookup_context = original_config, lookup_context end def locale - @i18n_config.locale + @original_config.locale end def locale=(value) @@ -60,6 +61,20 @@ module AbstractController end end end + + def parent_prefixes + @parent_prefixes ||= begin + parent_controller = superclass + prefixes = [] + + until parent_controller.abstract? + prefixes << parent_controller.controller_path + parent_controller = parent_controller.superclass + end + + prefixes + end + end end attr_writer :view_context_class @@ -98,7 +113,7 @@ module AbstractController def render_to_string(*args, &block) options = _normalize_args(*args, &block) _normalize_options(options) - render_to_body(options) + render_to_body(options).tap { self.response_body = nil } end # Raw rendering of a template to a Rack-compatible body. @@ -114,9 +129,12 @@ module AbstractController view_context.render(options) end - # The prefix used in render "foo" shortcuts. - def _prefix - controller_path + # The prefixes used in render "foo" shortcuts. + def _prefixes + @_prefixes ||= begin + parent_prefixes = self.class.parent_prefixes + parent_prefixes.dup.unshift(controller_path) + end end private @@ -156,7 +174,7 @@ module AbstractController end if (options.keys & [:partial, :file, :template, :once]).empty? - options[:prefix] ||= _prefix + options[:prefixes] ||= _prefixes end options[:template] ||= (options[:action] || action_name).to_s diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 48308cbb60..81c0698fb8 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -24,7 +24,7 @@ module ActionController # # Actions, by default, render a template in the <tt>app/views</tt> directory corresponding to the name of the controller and action # after executing code in the action. For example, the +index+ action of the PostsController would render the - # template <tt>app/views/posts/index.erb</tt> by default after populating the <tt>@posts</tt> instance variable. + # template <tt>app/views/posts/index.html.erb</tt> by default after populating the <tt>@posts</tt> instance variable. # # Unlike index, the create action will not render a template. After performing its main purpose (creating a # new post), it initiates a redirect instead. This redirect works by returning an external diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb index 37c155b9cd..0be04b70a1 100644 --- a/actionpack/lib/action_controller/caching/fragments.rb +++ b/actionpack/lib/action_controller/caching/fragments.rb @@ -1,52 +1,72 @@ module ActionController #:nodoc: module Caching - # Fragment caching is used for caching various blocks within templates without caching the entire action as a whole. This is useful when - # certain elements of an action change frequently or depend on complicated state while other parts rarely change or can be shared amongst multiple - # parties. The caching is done using the cache helper available in the Action View. A template with caching might look something like: + # Fragment caching is used for caching various blocks within + # views without caching the entire action as a whole. This is + # useful when certain elements of an action change frequently or + # depend on complicated state while other parts rarely change or + # can be shared amongst multiple parties. The caching is done using + # the <tt>cache</tt> helper available in the Action View. A + # template with fragment caching might look like: # # <b>Hello <%= @name %></b> + # # <% cache do %> # All the topics in the system: # <%= render :partial => "topic", :collection => Topic.find(:all) %> # <% end %> # - # This cache will bind to the name of the action that called it, so if this code was part of the view for the topics/list action, you would - # be able to invalidate it using <tt>expire_fragment(:controller => "topics", :action => "list")</tt>. + # This cache will bind the name of the action that called it, so if + # this code was part of the view for the topics/list action, you + # would be able to invalidate it using: + # + # expire_fragment(:controller => "topics", :action => "list") # - # This default behavior is of limited use if you need to cache multiple fragments per action or if the action itself is cached using - # <tt>caches_action</tt>, so we also have the option to qualify the name of the cached fragment with something like: + # This default behavior is limited if you need to cache multiple + # fragments per action or if the action itself is cached using + # <tt>caches_action</tt>. To remedy this, there is an option to + # qualify the name of the cached fragment by using the + # <tt>:action_suffix</tt> option: # # <% cache(:action => "list", :action_suffix => "all_topics") do %> # - # That would result in a name such as <tt>/topics/list/all_topics</tt>, avoiding conflicts with the action cache and with any fragments that use a - # different suffix. Note that the URL doesn't have to really exist or be callable - the url_for system is just used to generate unique - # cache names that we can refer to when we need to expire the cache. + # That would result in a name such as + # <tt>/topics/list/all_topics</tt>, avoiding conflicts with the + # action cache and with any fragments that use a different suffix. + # Note that the URL doesn't have to really exist or be callable + # - the url_for system is just used to generate unique cache names + # that we can refer to when we need to expire the cache. # # The expiration call for this example is: # - # expire_fragment(:controller => "topics", :action => "list", :action_suffix => "all_topics") + # expire_fragment(:controller => "topics", + # :action => "list", + # :action_suffix => "all_topics") module Fragments - # Given a key (as described in <tt>expire_fragment</tt>), returns a key suitable for use in reading, - # writing, or expiring a cached fragment. If the key is a hash, the generated key is the return - # value of url_for on that hash (without the protocol). All keys are prefixed with <tt>views/</tt> and uses + # Given a key (as described in <tt>expire_fragment</tt>), returns + # a key suitable for use in reading, writing, or expiring a + # cached fragment. If the key is a hash, the generated key is the + # return value of url_for on that hash (without the protocol). + # All keys are prefixed with <tt>views/</tt> and uses # ActiveSupport::Cache.expand_cache_key for the expansion. def fragment_cache_key(key) ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views) end - # Writes <tt>content</tt> to the location signified by <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats) + # Writes <tt>content</tt> to the location signified by + # <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats). def write_fragment(key, content, options = nil) return content unless cache_configured? key = fragment_cache_key(key) instrument_fragment_cache :write_fragment, key do - content = content.html_safe.to_str if content.respond_to?(:html_safe) + content = content.to_str cache_store.write(key, content, options) end content end - # Reads a cached fragment from the location signified by <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats) + # Reads a cached fragment from the location signified by <tt>key</tt> + # (see <tt>expire_fragment</tt> for acceptable formats). def read_fragment(key, options = nil) return unless cache_configured? @@ -57,7 +77,8 @@ module ActionController #:nodoc: end end - # Check if a cached fragment from the location signified by <tt>key</tt> exists (see <tt>expire_fragment</tt> for acceptable formats) + # Check if a cached fragment from the location signified by + # <tt>key</tt> exists (see <tt>expire_fragment</tt> for acceptable formats) def fragment_exist?(key, options = nil) return unless cache_configured? key = fragment_cache_key(key) @@ -70,6 +91,7 @@ module ActionController #:nodoc: # Removes fragments from the cache. # # +key+ can take one of three forms: + # # * String - This would normally take the form of a path, like # <tt>pages/45/notes</tt>. # * Hash - Treated as an implicit call to +url_for+, like diff --git a/actionpack/lib/action_controller/caching/pages.rb b/actionpack/lib/action_controller/caching/pages.rb index 3e57d2c236..8c583c7ce0 100644 --- a/actionpack/lib/action_controller/caching/pages.rb +++ b/actionpack/lib/action_controller/caching/pages.rb @@ -106,7 +106,7 @@ module ActionController #:nodoc: end def page_cache_path(path, extension = nil) - page_cache_directory + page_cache_file(path, extension) + page_cache_directory.to_s + page_cache_file(path, extension) end def instrument_page_cache(name, path) diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb index 3b19310a69..3fae697cc3 100644 --- a/actionpack/lib/action_controller/log_subscriber.rb +++ b/actionpack/lib/action_controller/log_subscriber.rb @@ -16,7 +16,11 @@ module ActionController payload = event.payload additions = ActionController::Base.log_process_action(payload) - message = "Completed #{payload[:status]} #{Rack::Utils::HTTP_STATUS_CODES[payload[:status]]} in %.0fms" % event.duration + status = payload[:status] + if status.nil? && payload[:exception].present? + status = Rack::Utils.status_code(ActionDispatch::ShowExceptions.rescue_responses[payload[:exception].first]) rescue nil + end + message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in %.0fms" % event.duration message << " (#{additions.join(" | ")})" unless additions.blank? info(message) diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index 329798e84f..b2c8053584 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -43,12 +43,61 @@ module ActionController end end - # Provides a way to get a valid Rack application from a controller. + # <tt>ActionController::Metal</tt> is the simplest possible controller, providing a + # valid Rack interface without the additional niceties provided by + # <tt>ActionController::Base</tt>. + # + # A sample metal controller might look like this: + # + # class HelloController < ActionController::Metal + # def index + # self.response_body = "Hello World!" + # end + # end + # + # And then to route requests to your metal controller, you would add + # something like this to <tt>config/routes.rb</tt>: + # + # match 'hello', :to => HelloController.action(:index) + # + # The +action+ method returns a valid Rack application for the \Rails + # router to dispatch to. + # + # == Rendering Helpers + # + # <tt>ActionController::Metal</tt> by default provides no utilities for rendering + # views, partials, or other responses aside from explicitly calling of + # <tt>response_body=</tt>, <tt>content_type=</tt>, and <tt>status=</tt>. To + # add the render helpers you're used to having in a normal controller, you + # can do the following: + # + # class HelloController < ActionController::Metal + # include ActionController::Rendering + # append_view_path "#{Rails.root}/app/views" + # + # def index + # render "hello/index" + # end + # end + # + # == Redirection Helpers + # + # To add redirection helpers to your metal controller, do the following: + # + # class HelloController < ActionController::Metal + # include ActionController::Redirecting + # include Rails.application.routes.url_helpers + # + # def index + # redirect_to root_url + # end + # end + # + # == Other Helpers + # + # You can refer to the modules included in <tt>ActionController::Base</tt> to see + # other features you can bring into your metal controller. # - # In AbstractController, dispatching is triggered directly by calling #process on a new controller. - # <tt>ActionController::Metal</tt> provides an <tt>action</tt> method that returns a valid Rack application for a - # given action. Other rack builders, such as Rack::Builder, Rack::URLMap, and the \Rails router, - # can dispatch directly to actions returned by controllers in your application. class Metal < AbstractController::Base abstract! @@ -133,7 +182,7 @@ module ActionController end def response_body=(val) - body = val.respond_to?(:each) ? val : [val] + body = val.nil? ? nil : (val.respond_to?(:each) ? val : [val]) super body end diff --git a/actionpack/lib/action_controller/metal/implicit_render.rb b/actionpack/lib/action_controller/metal/implicit_render.rb index 282dcf66b3..cfa7004048 100644 --- a/actionpack/lib/action_controller/metal/implicit_render.rb +++ b/actionpack/lib/action_controller/metal/implicit_render.rb @@ -12,10 +12,10 @@ module ActionController def method_for_action(action_name) super || begin - if template_exists?(action_name.to_s, _prefix) + if template_exists?(action_name.to_s, _prefixes) "default_render" end end end end -end
\ No newline at end of file +end diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb index 9ba37134b8..a2e06fe0a6 100644 --- a/actionpack/lib/action_controller/metal/mime_responds.rb +++ b/actionpack/lib/action_controller/metal/mime_responds.rb @@ -63,13 +63,13 @@ module ActionController #:nodoc: # might look something like this: # # def index - # @people = Person.find(:all) + # @people = Person.all # end # # Here's the same action, with web-service support baked in: # # def index - # @people = Person.find(:all) + # @people = Person.all # # respond_to do |format| # format.html @@ -155,7 +155,7 @@ module ActionController #:nodoc: # Respond to also allows you to specify a common block for different formats by using any: # # def index - # @people = Person.find(:all) + # @people = Person.all # # respond_to do |format| # format.html @@ -178,7 +178,7 @@ module ActionController #:nodoc: # respond_to :html, :xml, :json # # def index - # @people = Person.find(:all) + # @people = Person.all # respond_with(@person) # end # end @@ -208,8 +208,8 @@ module ActionController #:nodoc: # It also accepts a block to be given. It's used to overwrite a default # response: # - # def destroy - # @user = User.find(params[:id]) + # def create + # @user = User.new(params[:user]) # flash[:notice] = "User was successfully created." if @user.save # # respond_with(@user) do |format| diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index 14cc547dd0..32d52c84c4 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -6,7 +6,7 @@ module ActionController # Before processing, set the request formats in current controller formats. def process_action(*) #:nodoc: - self.formats = request.formats.map { |x| x.to_sym } + self.formats = request.formats.map { |x| x.ref } super end diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb index 148efbb081..b89e03bfb6 100644 --- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb @@ -71,25 +71,24 @@ module ActionController #:nodoc: end protected - - def protect_from_forgery(options = {}) - self.request_forgery_protection_token ||= :authenticity_token - before_filter :verify_authenticity_token, options - end - # The actual before_filter that is used. Modify this to change how you handle unverified requests. def verify_authenticity_token - verified_request? || raise(ActionController::InvalidAuthenticityToken) + verified_request? || handle_unverified_request + end + + def handle_unverified_request + reset_session end # Returns true or false if a request is verified. Checks: # - # * is the format restricted? By default, only HTML requests are checked. # * is it a GET request? Gets should be safe and idempotent # * Does the form_authenticity_token match the given token value from the params? + # * Does the X-CSRF-Token header match the form_authenticity_token def verified_request? - !protect_against_forgery? || request.forgery_whitelisted? || - form_authenticity_token == params[request_forgery_protection_token] + !protect_against_forgery? || request.get? || + form_authenticity_token == params[request_forgery_protection_token] || + form_authenticity_token == request.headers['X-CSRF-Token'] end # Sets the token value for the current session. diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb index 38d32211cc..4b45413cf8 100644 --- a/actionpack/lib/action_controller/metal/responder.rb +++ b/actionpack/lib/action_controller/metal/responder.rb @@ -77,8 +77,6 @@ module ActionController #:nodoc: # # respond_with(@project, :manager, @task) # - # Check <code>polymorphic_url</code> documentation for more examples. - # class Responder attr_reader :controller, :request, :format, :resource, :resources, :options @@ -115,7 +113,7 @@ module ActionController #:nodoc: # Main entry point for responder responsible to dispatch to the proper format. # def respond - method = :"to_#{format}" + method = "to_#{format}" respond_to?(method) ? send(method) : to_format end @@ -171,7 +169,7 @@ module ActionController #:nodoc: # Checks whether the resource responds to the current format or not. # def resourceful? - resource.respond_to?(:"to_#{format}") + resource.respond_to?("to_#{format}") end # Returns the resource location by retrieving it from the options or diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb index 3e5d23b5c1..09dd08898c 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb +++ b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb @@ -170,7 +170,7 @@ module HTML def contains_bad_protocols?(attr_name, value) uri_attributes.include?(attr_name) && - (value =~ /(^[^\/:]*):|(�*58)|(p)|(%|%)3A/ && !allowed_protocols.include?(value.split(protocol_separator).first)) + (value =~ /(^[^\/:]*):|(�*58)|(p)|(%|%)3A/ && !allowed_protocols.include?(value.split(protocol_separator).first.downcase)) end end end diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb index 1d2f7e4f19..4f4cb96a74 100644 --- a/actionpack/lib/action_dispatch/http/cache.rb +++ b/actionpack/lib/action_dispatch/http/cache.rb @@ -43,7 +43,7 @@ module ActionDispatch alias :etag? :etag def initialize(*) - status, header, body = super + super @cache_control = {} @etag = self["ETag"] diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 5b87a80c1b..7c9ebe7c7b 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -216,7 +216,11 @@ module Mime end def to_sym - @symbol || @string.to_sym + @symbol + end + + def ref + to_sym || to_s end def ===(list) diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 08f30e068d..f07ac44f7a 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -2,6 +2,7 @@ require 'tempfile' require 'stringio' require 'strscan' +require 'active_support/core_ext/module/deprecation' require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/string/access' require 'active_support/inflector' @@ -133,8 +134,9 @@ module ActionDispatch end def forgery_whitelisted? - get? || xhr? || content_mime_type.nil? || !content_mime_type.verify_request? + get? end + deprecate :forgery_whitelisted? => "it is just an alias for 'get?' now, update your code" def media_type content_mime_type.to_s diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 796cd8c09b..535ff42b90 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -28,8 +28,11 @@ module ActionDispatch rewritten_url = "" unless options[:only_path] - rewritten_url << (options[:protocol] || "http") - rewritten_url << "://" unless rewritten_url.match("://") + unless options[:protocol] == false + rewritten_url << (options[:protocol] || "http") + rewritten_url << ":" unless rewritten_url.match(%r{:|//}) + end + rewritten_url << "//" unless rewritten_url.match("//") rewritten_url << rewrite_authentication(options) rewritten_url << host_or_subdomain_and_domain(options) rewritten_url << ":#{options.delete(:port)}" if options[:port] diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb index 5776a7bb27..1bb2ad7f67 100644 --- a/actionpack/lib/action_dispatch/middleware/callbacks.rb +++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/module/delegation' + module ActionDispatch # Provide callbacks to be executed before and after the request dispatch. class Callbacks @@ -5,10 +7,8 @@ module ActionDispatch define_callbacks :call, :rescuable => true - def self.to_prepare(*args, &block) - ActiveSupport::Deprecation.warn "ActionDispatch::Callbacks.to_prepare is deprecated. " << - "Please use ActionDispatch::Reloader.to_prepare instead." - ActionDispatch::Reloader.to_prepare(*args, &block) + class << self + delegate :to_prepare, :to_cleanup, :to => "ActionDispatch::Reloader" end def self.before(*args, &block) @@ -25,7 +25,7 @@ module ActionDispatch end def call(env) - _run_call_callbacks do + run_callbacks :call do @app.call(env) end end diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index f369d2d3c2..7ac608f0a8 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -90,17 +90,14 @@ module ActionDispatch # **.**, ***.** style TLDs like co.uk or com.au # # www.example.co.uk gives: - # $1 => example - # $2 => co.uk + # $& => example.co.uk # # example.com gives: - # $1 => example - # $2 => com + # $& => example.com # # lots.of.subdomains.example.local gives: - # $1 => example - # $2 => local - DOMAIN_REGEXP = /([^.]*)\.([^.]*|..\...|...\...)$/ + # $& => example.local + DOMAIN_REGEXP = /[^.]*\.([^.]*|..\...|...\...)$/ def self.build(request) secret = request.env[TOKEN_KEY] @@ -131,11 +128,17 @@ module ActionDispatch options[:path] ||= "/" if options[:domain] == :all + # if there is a provided tld length then we use it otherwise default domain regexp + domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP + # if host is not ip and matches domain regexp # (ip confirms to domain regexp so we explicitly check for ip) - options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ DOMAIN_REGEXP) - ".#{$1}.#{$2}" + options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp) + ".#{$&}" end + elsif options[:domain].is_a? Array + # if host matches one of the supplied domains without a dot in front of it + options[:domain] = options[:domain].find {|domain| @host.include? domain[/^\.?(.*)$/, 1] } end end diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index 579b5d8a02..29289a76b4 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -1,9 +1,12 @@ module ActionDispatch - # ActionDispatch::Reloader provides to_prepare and to_cleanup callbacks. - # These are analogs of ActionDispatch::Callback's before and after - # callbacks, with the difference that to_cleanup is not called until the + # ActionDispatch::Reloader provides prepare and cleanup callbacks, + # intended to assist with code reloading during development. + # + # Prepare callbacks are run before each request, and cleanup callbacks + # after each request. In this respect they are analogs of ActionDispatch::Callback's + # before and after callbacks. However, cleanup callbacks are not called until the # request is fully complete -- that is, after #close has been called on - # the request body. This is important for streaming responses such as the + # the response body. This is important for streaming responses such as the # following: # # self.response_body = lambda { |response, output| @@ -15,7 +18,10 @@ module ActionDispatch # classes before they are unloaded. # # By default, ActionDispatch::Reloader is included in the middleware stack - # only in the development environment. + # only in the development environment; specifically, when config.cache_classes + # is false. Callbacks may be registered even when it is not included in the + # middleware stack, but are executed only when +ActionDispatch::Reloader.prepare!+ + # or +ActionDispatch::Reloader.cleanup!+ are called manually. # class Reloader include ActiveSupport::Callbacks @@ -23,8 +29,8 @@ module ActionDispatch define_callbacks :prepare, :scope => :name define_callbacks :cleanup, :scope => :name - # Add a preparation callback. Preparation callbacks are run before each - # request. + # Add a prepare callback. Prepare callbacks are run before each request, prior + # to ActionDispatch::Callback's before callbacks. def self.to_prepare(*args, &block) set_callback(:prepare, *args, &block) end @@ -35,12 +41,14 @@ module ActionDispatch set_callback(:cleanup, *args, &block) end + # Execute all prepare callbacks. def self.prepare! - new(nil).send(:_run_prepare_callbacks) + new(nil).run_callbacks :prepare end + # Execute all cleanup callbacks. def self.cleanup! - new(nil).send(:_run_cleanup_callbacks) + new(nil).run_callbacks :cleanup end def initialize(app) @@ -56,10 +64,13 @@ module ActionDispatch end def call(env) - _run_prepare_callbacks + run_callbacks :prepare response = @app.call(env) response[2].extend(CleanupOnClose) response + rescue Exception + run_callbacks :cleanup + raise end end end diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 71e736ce9f..dbe3206808 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -43,20 +43,20 @@ module ActionDispatch end def call(env) - status, headers, body = @app.call(env) - - # Only this middleware cares about RoutingError. So, let's just raise - # it here. - # TODO: refactor this middleware to handle the X-Cascade scenario without - # having to raise an exception. - if headers['X-Cascade'] == 'pass' - raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect}" + begin + status, headers, body = @app.call(env) + exception = nil + + # Only this middleware cares about RoutingError. So, let's just raise + # it here. + if headers['X-Cascade'] == 'pass' + raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect}" + end + rescue Exception => exception + raise exception if env['action_dispatch.show_exceptions'] == false end - [status, headers, body] - rescue Exception => exception - raise exception if env['action_dispatch.show_exceptions'] == false - render_exception(env, exception) + exception ? render_exception(env, exception) : [status, headers, body] end private diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb index bd6ffbab5d..50d8ca9484 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb @@ -6,5 +6,5 @@ </h1> <pre><%=h @exception.message %></pre> -<%= render :file => "rescues/_trace.erb" %> -<%= render :file => "rescues/_request_and_response.erb" %> +<%= render :template => "rescues/_trace" %> +<%= render :template => "rescues/_request_and_response" %> diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb index 02fa18211d..c658559be9 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb @@ -13,9 +13,5 @@ <p><%=h @exception.sub_template_message %></p> -<% @real_exception = @exception - @exception = @exception.original_exception || @exception %> -<%= render :file => "rescues/_trace.erb" %> -<% @exception = @real_exception %> - -<%= render :file => "rescues/_request_and_response.erb" %> +<%= render :template => "rescues/_trace" %> +<%= render :template => "rescues/_request_and_response" %> diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index 8810227a59..43fd93adf6 100644 --- a/actionpack/lib/action_dispatch/routing.rb +++ b/actionpack/lib/action_dispatch/routing.rb @@ -56,6 +56,18 @@ module ActionDispatch # resources :posts, :comments # end # + # Alternately, you can add prefixes to your path without using a separate + # directory by using +scope+. +scope+ takes additional options which + # apply to all enclosed routes. + # + # scope :path => "/cpanel", :as => 'admin' do + # resources :posts, :comments + # end + # + # For more, see <tt>Routing::Mapper::Resources#resources</tt>, + # <tt>Routing::Mapper::Scoping#namespace</tt>, and + # <tt>Routing::Mapper::Scoping#scope</tt>. + # # == Named routes # # Routes can be named by passing an <tt>:as</tt> option, diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f65a294eca..589df218a8 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -22,18 +22,22 @@ module ActionDispatch @app, @constraints, @request = app, constraints, request end - def call(env) + def matches?(env) req = @request.new(env) @constraints.each { |constraint| if constraint.respond_to?(:matches?) && !constraint.matches?(req) - return [ 404, {'X-Cascade' => 'pass'}, [] ] + return false elsif constraint.respond_to?(:call) && !constraint.call(*constraint_args(constraint, req)) - return [ 404, {'X-Cascade' => 'pass'}, [] ] + return false end } - @app.call(env) + return true + end + + def call(env) + matches?(env) ? @app.call(env) : [ 404, {'X-Cascade' => 'pass'}, [] ] end private @@ -247,7 +251,7 @@ module ActionDispatch # # root :to => 'pages#main' # - # For options, see the +match+ method's documentation, as +root+ uses it internally. + # For options, see +match+, as +root+ uses it internally. # # You should put the root route at the top of <tt>config/routes.rb</tt>, # because this means it will be matched first. As this is the most popular route @@ -256,15 +260,114 @@ module ActionDispatch match '/', options.reverse_merge(:as => :root) end - # When you set up a regular route, you supply a series of symbols that - # Rails maps to parts of an incoming HTTP request. + # Matches a url pattern to one or more routes. Any symbols in a pattern + # are interpreted as url query parameters and thus available as +params+ + # in an action: + # + # # sets :controller, :action and :id in params + # match ':controller/:action/:id' + # + # Two of these symbols are special, +:controller+ maps to the controller + # and +:action+ to the controller's action. A pattern can also map + # wildcard segments (globs) to params: + # + # match 'songs/*category/:title' => 'songs#show' + # + # # 'songs/rock/classic/stairway-to-heaven' sets + # # params[:category] = 'rock/classic' + # # params[:title] = 'stairway-to-heaven' + # + # When a pattern points to an internal route, the route's +:action+ and + # +:controller+ should be set in options or hash shorthand. Examples: + # + # match 'photos/:id' => 'photos#show' + # match 'photos/:id', :to => 'photos#show' + # match 'photos/:id', :controller => 'photos', :action => 'show' + # + # A pattern can also point to a +Rack+ endpoint i.e. anything that + # responds to +call+: + # + # match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon" } + # match 'photos/:id' => PhotoRackApp + # # Yes, controller actions are just rack endpoints + # match 'photos/:id' => PhotosController.action(:show) + # + # === Options + # + # Any options not seen here are passed on as params with the url. + # + # [:controller] + # The route's controller. + # + # [:action] + # The route's action. + # + # [:path] + # The path prefix for the routes. + # + # [:module] + # The namespace for :controller. + # + # match 'path' => 'c#a', :module => 'sekret', :controller => 'posts' + # #=> Sekret::PostsController + # + # See <tt>Scoping#namespace</tt> for its scope equivalent. + # + # [:as] + # The name used to generate routing helpers. + # + # [:via] + # Allowed HTTP verb(s) for route. + # + # match 'path' => 'c#a', :via => :get + # match 'path' => 'c#a', :via => [:get, :post] + # + # [:to] + # Points to a +Rack+ endpoint. Can be an object that responds to + # +call+ or a string representing a controller's action. + # + # match 'path', :to => 'controller#action' + # match 'path', :to => lambda { [200, {}, "Success!"] } + # match 'path', :to => RackApp + # + # [:on] + # Shorthand for wrapping routes in a specific RESTful context. Valid + # values are :member, :collection, and :new. Only use within + # <tt>resource(s)</tt> block. For example: + # + # resource :bar do + # match 'foo' => 'c#a', :on => :member, :via => [:get, :post] + # end + # + # Is equivalent to: # - # match ':controller/:action/:id/:user_id' + # resource :bar do + # member do + # match 'foo' => 'c#a', :via => [:get, :post] + # end + # end + # + # [:constraints] + # Constrains parameters with a hash of regular expressions or an + # object that responds to #matches? + # + # match 'path/:id', :constraints => { :id => /[A-Z]\d{5}/ } + # + # class Blacklist + # def matches?(request) request.remote_ip == '1.2.3.4' end + # end + # match 'path' => 'c#a', :constraints => Blacklist.new # - # Two of these symbols are special: :controller maps to the name of a - # controller in your application, and :action maps to the name of an - # action within that controller. Anything other than :controller or - # :action will be available to the action as part of params. + # See <tt>Scoping#constraints</tt> for more examples with its scope + # equivalent. + # + # [:defaults] + # Sets defaults for parameters + # + # # Sets params[:format] to 'jpg' by default + # match 'path' => 'c#a', :defaults => { :format => 'jpg' } + # + # See <tt>Scoping#defaults</tt> for its scope equivalent. def match(path, options=nil) mapping = Mapping.new(@set, @scope, path, options || {}).to_route @set.add_route(*mapping) @@ -279,6 +382,8 @@ module ActionDispatch # # mount(SomeRackApp => "some_route") # + # For options, see +match+, as +mount+ uses it internally. + # # All mounted applications come with routing helpers to access them. # These are named after the class specified, so for the above example # the helper is either +some_rack_app_path+ or +some_rack_app_url+. @@ -349,7 +454,7 @@ module ActionDispatch module HttpHelpers # Define a route that only recognizes HTTP GET. - # For supported arguments, see +match+. + # For supported arguments, see <tt>Base#match</tt>. # # Example: # @@ -359,7 +464,7 @@ module ActionDispatch end # Define a route that only recognizes HTTP POST. - # For supported arguments, see +match+. + # For supported arguments, see <tt>Base#match</tt>. # # Example: # @@ -369,7 +474,7 @@ module ActionDispatch end # Define a route that only recognizes HTTP PUT. - # For supported arguments, see +match+. + # For supported arguments, see <tt>Base#match</tt>. # # Example: # @@ -379,7 +484,7 @@ module ActionDispatch end # Define a route that only recognizes HTTP PUT. - # For supported arguments, see +match+. + # For supported arguments, see <tt>Base#match</tt>. # # Example: # @@ -458,7 +563,7 @@ module ActionDispatch super end - # Used to scope a set of routes to particular constraints. + # Scopes a set of routes to the given default options. # # Take the following route definition as an example: # @@ -470,51 +575,26 @@ module ActionDispatch # The difference here being that the routes generated are like /rails/projects/2, # rather than /accounts/rails/projects/2. # - # === Supported options - # [:module] - # If you want to route /posts (without the prefix /admin) to - # Admin::PostsController, you could use - # - # scope :module => "admin" do - # resources :posts - # end - # - # [:path] - # If you want to prefix the route, you could use - # - # scope :path => "/admin" do - # resources :posts - # end + # === Options # - # This will prefix all of the +posts+ resource's requests with '/admin' + # Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>. # - # [:as] - # Prefixes the routing helpers in this scope with the specified label. + # === Examples # - # scope :as => "sekret" do - # resources :posts - # end - # - # Helpers such as +posts_path+ will now be +sekret_posts_path+ - # - # [:shallow_path] - # - # Prefixes nested shallow routes with the specified path. - # - # scope :shallow_path => "sekret" do - # resources :posts do - # resources :comments, :shallow => true - # end + # # route /posts (without the prefix /admin) to Admin::PostsController + # scope :module => "admin" do + # resources :posts + # end # - # The +comments+ resource here will have the following routes generated for it: + # # prefix the posts resource's requests with '/admin' + # scope :path => "/admin" do + # resources :posts + # end # - # post_comments GET /sekret/posts/:post_id/comments(.:format) - # post_comments POST /sekret/posts/:post_id/comments(.:format) - # new_post_comment GET /sekret/posts/:post_id/comments/new(.:format) - # edit_comment GET /sekret/comments/:id/edit(.:format) - # comment GET /sekret/comments/:id(.:format) - # comment PUT /sekret/comments/:id(.:format) - # comment DELETE /sekret/comments/:id(.:format) + # # prefix the routing helper name: sekret_posts_path instead of posts_path + # scope :as => "sekret" do + # resources :posts + # end def scope(*args) options = args.extract_options! options = options.dup @@ -577,43 +657,31 @@ module ActionDispatch # admin_post GET /admin/posts/:id(.:format) {:action=>"show", :controller=>"admin/posts"} # admin_post PUT /admin/posts/:id(.:format) {:action=>"update", :controller=>"admin/posts"} # admin_post DELETE /admin/posts/:id(.:format) {:action=>"destroy", :controller=>"admin/posts"} - # === Supported options # - # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ options all default to the name of the namespace. + # === Options # - # [:path] - # The path prefix for the routes. - # - # namespace :admin, :path => "sekret" do - # resources :posts - # end + # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ + # options all default to the name of the namespace. # - # All routes for the above +resources+ will be accessible through +/sekret/posts+, rather than +/admin/posts+ - # - # [:module] - # The namespace for the controllers. - # - # namespace :admin, :module => "sekret" do - # resources :posts - # end + # For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see + # <tt>Resources#resources</tt>. # - # The +PostsController+ here should go in the +Sekret+ namespace and so it should be defined like this: + # === Examples # - # class Sekret::PostsController < ApplicationController - # # code go here - # end - # - # [:as] - # Changes the name used in routing helpers for this namespace. - # - # namespace :admin, :as => "sekret" do - # resources :posts - # end + # # accessible through /sekret/posts rather than /admin/posts + # namespace :admin, :path => "sekret" do + # resources :posts + # end # - # Routing helpers such as +admin_posts_path+ will now be +sekret_posts_path+. + # # maps to Sekret::PostsController rather than Admin::PostsController + # namespace :admin, :module => "sekret" do + # resources :posts + # end # - # [:shallow_path] - # See the +scope+ method. + # # generates sekret_posts_path rather than admin_posts_path + # namespace :admin, :as => "sekret" do + # resources :posts + # end def namespace(path, options = {}) path = path.to_s options = { :path => path, :as => path, :module => path, @@ -680,9 +748,9 @@ module ActionDispatch end # Allows you to set default parameters for a route, such as this: - # defaults :id => 'home' do - # match 'scoped_pages/(:id)', :to => 'pages#show' - # end + # defaults :id => 'home' do + # match 'scoped_pages/(:id)', :to => 'pages#show' + # end # Using this, the +:id+ parameter here will default to 'home'. def defaults(defaults = {}) scope(:defaults => defaults) { yield } @@ -779,6 +847,14 @@ module ActionDispatch # resources :posts, :comments # end # + # By default the :id parameter doesn't accept dots. If you need to + # use dots as part of the :id parameter add a constraint which + # overrides this restriction, e.g: + # + # resources :articles, :id => /[^\/]+/ + # + # This allows any character other than a slash as part of your :id. + # module Resources # CANONICAL_ACTIONS holds all actions that does not need a prefix or # a path appended since they fit properly in their scope level. @@ -827,7 +903,8 @@ module ActionDispatch alias :member_name :singular - # Checks for uncountable plurals, and appends "_index" if they're. + # Checks for uncountable plurals, and appends "_index" if the plural + # and singular form are the same. def collection_name singular == plural ? "#{plural}_index" : plural end @@ -906,6 +983,9 @@ module ActionDispatch # GET /geocoder/edit # PUT /geocoder # DELETE /geocoder + # + # === Options + # Takes same options as +resources+. def resource(*resources, &block) options = resources.extract_options! @@ -967,7 +1047,9 @@ module ActionDispatch # PUT /photos/:id/comments/:id # DELETE /photos/:id/comments/:id # - # === Supported options + # === Options + # Takes same options as <tt>Base#match</tt> as well as: + # # [:path_names] # Allows you to change the paths of the seven default actions. # Paths not specified are not changed. @@ -976,20 +1058,59 @@ module ActionDispatch # # The above example will now change /posts/new to /posts/brand_new # - # [:module] - # Set the module where the controller can be found. Defaults to nothing. + # [:only] + # Only generate routes for the given actions. # - # resources :posts, :module => "admin" + # resources :cows, :only => :show + # resources :cows, :only => [:show, :index] # - # All requests to the posts resources will now go to +Admin::PostsController+. + # [:except] + # Generate all routes except for the given actions. # - # [:path] + # resources :cows, :except => :show + # resources :cows, :except => [:show, :index] + # + # [:shallow] + # Generates shallow routes for nested resource(s). When placed on a parent resource, + # generates shallow routes for all nested resources. + # + # resources :posts, :shallow => true do + # resources :comments + # end + # + # Is the same as: + # + # resources :posts do + # resources :comments + # end + # resources :comments + # + # [:shallow_path] + # Prefixes nested shallow routes with the specified path. + # + # scope :shallow_path => "sekret" do + # resources :posts do + # resources :comments, :shallow => true + # end + # end + # + # The +comments+ resource here will have the following routes generated for it: + # + # post_comments GET /sekret/posts/:post_id/comments(.:format) + # post_comments POST /sekret/posts/:post_id/comments(.:format) + # new_post_comment GET /sekret/posts/:post_id/comments/new(.:format) + # edit_comment GET /sekret/comments/:id/edit(.:format) + # comment GET /sekret/comments/:id(.:format) + # comment PUT /sekret/comments/:id(.:format) + # comment DELETE /sekret/comments/:id(.:format) # - # Set a path prefix for this resource. + # === Examples # - # resources :posts, :path => "admin" + # # routes call Admin::PostsController + # resources :posts, :module => "admin" # - # All actions for this resource will now be at +/admin/posts+. + # # resource actions are at /admin/posts. + # resources :posts, :path => "admin" def resources(*resources, &block) options = resources.extract_options! @@ -1111,7 +1232,7 @@ module ActionDispatch end def shallow - scope(:shallow => true) do + scope(:shallow => true, :shallow_path => @scope[:path]) do yield end end @@ -1321,7 +1442,7 @@ module ActionDispatch name = case @scope[:scope_level] when :nested - [member_name, prefix] + [name_prefix, prefix] when :collection [prefix, name_prefix, collection_name] when :new diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 03bfe178e5..4b4e9da173 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -450,7 +450,7 @@ module ActionDispatch end def raise_routing_error - raise ActionController::RoutingError.new("No route matches #{options.inspect}") + raise ActionController::RoutingError, "No route matches #{options.inspect}" end def different_controller? @@ -540,7 +540,9 @@ module ActionDispatch end dispatcher = route.app - dispatcher = dispatcher.app while dispatcher.is_a?(Mapper::Constraints) + while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do + dispatcher = dispatcher.app + end if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, false) dispatcher.prepare_params!(params) diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb index 1558c3ae05..77a15f3e97 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/response.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb @@ -20,7 +20,7 @@ module ActionDispatch # # You can also pass an explicit status number like <tt>assert_response(501)</tt> # or its symbolic equivalent <tt>assert_response(:not_implemented)</tt>. - # See ActionDispatch::StatusCodes for a full list. + # See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list. # # ==== Examples # diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 1390b74a95..11e8c63fa0 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -37,9 +37,6 @@ module ActionDispatch # # # Test a custom route # assert_recognizes({:controller => 'items', :action => 'show', :id => '1'}, 'view/item1') - # - # # Check a Simply RESTful generated route - # assert_recognizes list_items_url, 'items/list' def assert_recognizes(expected_options, path, extras={}, message=nil) request = recognized_request_for(path) @@ -124,7 +121,8 @@ module ActionDispatch options[:controller] = "/#{controller}" end - assert_generates(path.is_a?(Hash) ? path[:path] : path, options, defaults, extras, message) + generate_options = options.dup.delete_if{ |k,v| defaults.key?(k) } + assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message) end # A helper to make it easier to test different route configurations. diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 92ff3380b0..ab8c6259c5 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -18,7 +18,7 @@ module ActionView #:nodoc: # following loop for names: # # <b>Names of all the people</b> - # <% for person in @people %> + # <% @people.each do |person| %> # Name: <%= person.name %><br/> # <% end %> # @@ -232,8 +232,8 @@ module ActionView #:nodoc: @controller_path ||= controller && controller.controller_path end - def controller_prefix - @controller_prefix ||= controller && controller._prefix + def controller_prefixes + @controller_prefixes ||= controller && controller._prefixes end ActiveSupport.run_load_hooks(:action_view, self) diff --git a/actionpack/lib/action_view/helpers.rb b/actionpack/lib/action_view/helpers.rb index 41013c800c..d338ce616a 100644 --- a/actionpack/lib/action_view/helpers.rb +++ b/actionpack/lib/action_view/helpers.rb @@ -18,7 +18,7 @@ module ActionView #:nodoc: autoload :JavaScriptHelper, "action_view/helpers/javascript_helper" autoload :NumberHelper autoload :PrototypeHelper - autoload :RawOutputHelper + autoload :OutputSafetyHelper autoload :RecordTagHelper autoload :SanitizeHelper autoload :ScriptaculousHelper @@ -48,7 +48,7 @@ module ActionView #:nodoc: include JavaScriptHelper include NumberHelper include PrototypeHelper - include RawOutputHelper + include OutputSafetyHelper include RecordTagHelper include SanitizeHelper include ScriptaculousHelper diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb index e52797042f..52eb43a1cd 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb @@ -11,7 +11,9 @@ module ActionView attr_reader :config, :asset_paths class_attribute :expansions - self.expansions = { } + def self.inherited(base) + base.expansions = { } + end def initialize(config, asset_paths) @config = config @@ -69,9 +71,21 @@ module ActionView if sources.first == :all collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") else - sources.collect do |source| - determine_source(source, expansions) - end.flatten + sources.inject([]) do |list, source| + determined_source = determine_source(source, expansions) + update_source_list(list, determined_source) + end + end + end + + def update_source_list(list, source) + case source + when String + list.delete(source) + list << source + when Array + updated_sources = source - list + list.concat(updated_sources) end end diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb index 6581e1d6f2..b9126af944 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb @@ -33,13 +33,21 @@ module ActionView all_asset_files = (collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") - ['application']) << 'application' ((determine_source(:defaults, expansions).dup & all_asset_files) + all_asset_files).uniq else - expanded_sources = sources.collect do |source| - determine_source(source, expansions) - end.flatten - expanded_sources << "application" if sources.include?(:defaults) && File.exist?(File.join(custom_dir, "application.#{extension}")) + expanded_sources = sources.inject([]) do |list, source| + determined_source = determine_source(source, expansions) + update_source_list(list, determined_source) + end + add_application_js(expanded_sources, sources) expanded_sources end end + + def add_application_js(expanded_sources, sources) + if sources.include?(:defaults) && File.exist?(File.join(custom_dir, "application.#{extension}")) + expanded_sources.delete('application') + expanded_sources << "application" + end + end end @@ -59,7 +67,10 @@ module ActionView # <script type="text/javascript" src="/javascripts/body.js"></script> # <script type="text/javascript" src="/javascripts/tail.js"></script> def register_javascript_expansion(expansions) - JavascriptIncludeTag.expansions.merge!(expansions) + js_expansions = JavascriptIncludeTag.expansions + expansions.each do |key, values| + js_expansions[key] = (js_expansions[key] || []) | Array(values) if values + end end end @@ -170,4 +181,4 @@ module ActionView end end -end
\ No newline at end of file +end diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb index d02b28d7f6..f3e041de95 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb @@ -44,7 +44,10 @@ module ActionView # <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" /> # <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" /> def register_stylesheet_expansion(expansions) - StylesheetIncludeTag.expansions.merge!(expansions) + style_expansions = StylesheetIncludeTag.expansions + expansions.each do |key, values| + style_expansions[key] = (style_expansions[key] || []) | Array(values) if values + end end end @@ -141,4 +144,4 @@ module ActionView end end -end
\ No newline at end of file +end diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb index f544a9d147..385378ea29 100644 --- a/actionpack/lib/action_view/helpers/cache_helper.rb +++ b/actionpack/lib/action_view/helpers/cache_helper.rb @@ -2,31 +2,29 @@ module ActionView # = Action View Cache Helper module Helpers module CacheHelper - # This helper to exposes a method for caching of view fragments. - # See ActionController::Caching::Fragments for usage instructions. + # This helper exposes a method for caching fragments of a view + # rather than an entire action or page. This technique is useful + # caching pieces like menus, lists of newstopics, static HTML + # fragments, and so on. This method takes a block that contains + # the content you wish to cache. # - # A method for caching fragments of a view rather than an entire - # action or page. This technique is useful caching pieces like - # menus, lists of news topics, static HTML fragments, and so on. - # This method takes a block that contains the content you wish - # to cache. See ActionController::Caching::Fragments for more - # information. + # See ActionController::Caching::Fragments for usage instructions. # # ==== Examples - # If you wanted to cache a navigation menu, you could do the - # following. + # If you want to cache a navigation menu, you can do following: # # <% cache do %> # <%= render :partial => "menu" %> # <% end %> # - # You can also cache static content... + # You can also cache static content: # # <% cache do %> # <p>Hello users! Welcome to our website!</p> # <% end %> # - # ...and static content mixed with RHTML content. + # Static content with embedded ruby content can be cached as + # well: # # <% cache do %> # Topics: @@ -46,8 +44,8 @@ module ActionView private # TODO: Create an object that has caching read/write on it def fragment_for(name = {}, options = nil, &block) #:nodoc: - if controller.fragment_exist?(name, options) - controller.read_fragment(name, options) + if fragment = controller.read_fragment(name, options) + fragment else # VIEW TODO: Make #capture usable outside of ERB # This dance is needed because Builder can't use capture diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index 875ec9b77b..dc8e4bc316 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -1,5 +1,6 @@ require 'date' require 'action_view/helpers/tag_helper' +require 'active_support/core_ext/date/conversions' require 'active_support/core_ext/hash/slice' require 'active_support/core_ext/object/with_options' @@ -566,6 +567,27 @@ module ActionView def select_year(date, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_year end + + # Returns an html time tag for the given date or time. + # + # ==== Examples + # time_tag Date.today # => + # <time datetime="2010-11-04">November 04, 2010</time> + # time_tag Time.now # => + # <time datetime="2010-11-04T17:55:45+01:00">November 04, 2010 17:55</time> + # time_tag Date.yesterday, 'Yesterday' # => + # <time datetime="2010-11-03">Yesterday</time> + # time_tag Date.today, :pubdate => true # => + # <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time> + # + def time_tag(date_or_time, *args) + options = args.extract_options! + format = options.delete(:format) || :long + content = args.first || I18n.l(date_or_time, :format => format) + datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.rfc3339 + + content_tag(:time, content, options.reverse_merge(:datetime => datetime)) + end end class DateTimeSelector #:nodoc: diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index 6f0e2c99ba..befaa3e8d9 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -298,6 +298,23 @@ module ActionView # # If you don't need to attach a form to a model instance, then check out # FormTagHelper#form_tag. + # + # === Form to external resources + # + # When you build forms to external resources sometimes you need to set an authenticity token or just render a form + # without it, for example when you submit data to a payment gateway number and types of fields could be limited. + # + # To set an authenticity token you need to pass an <tt>:authenticity_token</tt> parameter + # + # <%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f| + # ... + # <% end %> + # + # If you don't want to an authenticity token field be rendered at all just pass <tt>false</tt>: + # + # <%= form_for @invoice, :url => external_url, :authenticity_token => false do |f| + # ... + # <% end %> def form_for(record, options = {}, &proc) raise ArgumentError, "Missing block" unless block_given? @@ -314,6 +331,8 @@ module ActionView end options[:html][:remote] = options.delete(:remote) + options[:html][:authenticity_token] = options.delete(:authenticity_token) + builder = options[:parent_builder] = instantiate_builder(object_name, object, options, &proc) fields_for = fields_for(object_name, object, options, &proc) default_options = builder.multipart? ? { :multipart => true } : {} @@ -530,8 +549,11 @@ module ActionView # <% end %> # ... # <% end %> - def fields_for(record, record_object = nil, options = nil, &block) - capture(instantiate_builder(record, record_object, options, &block), &block) + def fields_for(record, record_object = nil, options = {}, &block) + builder = instantiate_builder(record, record_object, options, &block) + output = capture(builder, &block) + output.concat builder.hidden_field(:id) if output && options[:hidden_field_id] && !builder.emitted_hidden_id? + output end # Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object @@ -858,8 +880,7 @@ module ActionView end end - module InstanceTagMethods #:nodoc: - extend ActiveSupport::Concern + class InstanceTag include Helpers::CaptureHelper, Context, Helpers::TagHelper, Helpers::FormTagHelper attr_reader :object, :method_name, :object_name @@ -1025,7 +1046,7 @@ module ActionView self.class.value_before_type_cast(object, @method_name) end - module ClassMethods + class << self def value(object, method_name) object.send method_name if object end @@ -1111,10 +1132,6 @@ module ActionView end end - class InstanceTag - include InstanceTagMethods - end - class FormBuilder # The methods which wrap a form helper call. class_attribute :field_helpers @@ -1248,7 +1265,7 @@ module ActionView def submit(value=nil, options={}) value, options = nil, value if value.is_a?(Hash) value ||= submit_default_value - @template.submit_tag(value, options.reverse_merge(:id => "#{object_name}_submit")) + @template.submit_tag(value, options) end def emitted_hidden_id? @@ -1309,14 +1326,8 @@ module ActionView def fields_for_nested_model(name, object, options, block) object = convert_to_model(object) - if object.persisted? - @template.fields_for(name, object, options) do |builder| - block.call(builder) - @template.concat builder.hidden_field(:id) unless builder.emitted_hidden_id? - end - else - @template.fields_for(name, object, options, &block) - end + options[:hidden_field_id] = object.persisted? + @template.fields_for(name, object, options, &block) end def nested_child_index(name) diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index 6ac8577785..7698602022 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -533,7 +533,7 @@ module ActionView else selected = Array.wrap(selected) options = selected.extract_options!.symbolize_keys - [ options[:selected] || selected , options[:disabled] ] + [ options.include?(:selected) ? options[:selected] : selected, options[:disabled] ] end end diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index 9500e85e8b..71f8534cbf 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -25,6 +25,9 @@ module ActionView # * <tt>:method</tt> - The method to use when submitting the form, usually either "get" or "post". # If "put", "delete", or another verb is used, a hidden input with name <tt>_method</tt> # is added to simulate the verb over post. + # * <tt>:authenticity_token</tt> - Authenticity token to use in the form. Use only if you need to + # pass custom authenticity token string, or to not add authenticity_token field at all + # (by passing <tt>false</tt>). # * A list of parameters to feed to the URL the form will be posted to. # * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the # submit behaviour. By default this behaviour is an ajax submit. @@ -47,6 +50,12 @@ module ActionView # <%= form_tag('/posts', :remote => true) %> # # => <form action="/posts" method="post" data-remote="true"> # + # form_tag('http://far.away.com/form', :authenticity_token => false) + # # form without authenticity token + # + # form_tag('http://far.away.com/form', :authenticity_token => "cf50faa3fe97702ca1ae") + # # form with custom authenticity token + # def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block) html_options = html_options_for_form(url_for_options, options, *parameters_for_url) if block_given? @@ -401,6 +410,59 @@ module ActionView tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options.stringify_keys) end + # Creates a button element that defines a <tt>submit</tt> button, + # <tt>reset</tt>button or a generic button which can be used in + # JavaScript, for example. You can use the button tag as a regular + # submit tag but it isn't supported in legacy browsers. However, + # the button tag allows richer labels such as images and emphasis, + # so this helper will also accept a block. + # + # ==== Options + # * <tt>:confirm => 'question?'</tt> - If present, the + # unobtrusive JavaScript drivers will provide a prompt with + # the question specified. If the user accepts, the form is + # processed normally, otherwise no action is taken. + # * <tt>:disabled</tt> - If true, the user will not be able to + # use this input. + # * <tt>:disable_with</tt> - Value of this parameter will be + # used as the value for a disabled version of the submit + # button when the form is submitted. This feature is provided + # by the unobtrusive JavaScript driver. + # * Any other key creates standard HTML options for the tag. + # + # ==== Examples + # button_tag + # # => <button name="button" type="submit">Button</button> + # + # button_tag(:type => 'button') do + # content_tag(:strong, 'Ask me!') + # end + # # => <button name="button" type="button"> + # <strong>Ask me!</strong> + # </button> + # + # button_tag "Checkout", :disable_with => "Please wait..." + # # => <button data-disable-with="Please wait..." name="button" + # type="submit">Checkout</button> + # + def button_tag(content_or_options = nil, options = nil, &block) + options = content_or_options if block_given? && content_or_options.is_a?(Hash) + options ||= {} + options.stringify_keys! + + if disable_with = options.delete("disable_with") + options["data-disable-with"] = disable_with + end + + if confirm = options.delete("confirm") + options["data-confirm"] = confirm + end + + options.reverse_merge! 'name' => 'button', 'type' => 'submit' + + content_tag :button, content_or_options || 'Button', options, &block + end + # Displays an image which when clicked will submit the form. # # <tt>source</tt> is passed to AssetTagHelper#path_to_image @@ -534,6 +596,7 @@ module ActionView html_options["action"] = url_for(url_for_options, *parameters_for_url) html_options["accept-charset"] = "UTF-8" html_options["data-remote"] = true if html_options.delete("remote") + html_options["authenticity_token"] = html_options.delete("authenticity_token") if html_options.has_key?("authenticity_token") end end @@ -541,6 +604,7 @@ module ActionView snowman_tag = tag(:input, :type => "hidden", :name => "utf8", :value => "✓".html_safe) + authenticity_token = html_options.delete("authenticity_token") method = html_options.delete("method").to_s method_tag = case method @@ -549,10 +613,10 @@ module ActionView '' when /^post$/i, "", nil html_options["method"] = "post" - token_tag + token_tag(authenticity_token) else html_options["method"] = "post" - tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag + tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag(authenticity_token) end tags = snowman_tag << method_tag @@ -572,11 +636,12 @@ module ActionView output.safe_concat("</form>") end - def token_tag - unless protect_against_forgery? + def token_tag(token) + if token == false || !protect_against_forgery? '' else - tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) + token = form_authenticity_token if token.nil? + tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => token) end end diff --git a/actionpack/lib/action_view/helpers/output_safety_helper.rb b/actionpack/lib/action_view/helpers/output_safety_helper.rb new file mode 100644 index 0000000000..a035dd70ad --- /dev/null +++ b/actionpack/lib/action_view/helpers/output_safety_helper.rb @@ -0,0 +1,38 @@ +require 'active_support/core_ext/string/output_safety' + +module ActionView #:nodoc: + # = Action View Raw Output Helper + module Helpers #:nodoc: + module OutputSafetyHelper + # This method outputs without escaping a string. Since escaping tags is + # now default, this can be used when you don't want Rails to automatically + # escape tags. This is not recommended if the data is coming from the user's + # input. + # + # For example: + # + # <%=raw @user.name %> + def raw(stringish) + stringish.to_s.html_safe + end + + # This method returns a html safe string similar to what <tt>Array#join</tt> + # would return. All items in the array, including the supplied separator, are + # html escaped unless they are html safe, and the returned string is marked + # as html safe. + # + # safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />") + # # => "<p>foo</p><br /><p>bar</p>" + # + # safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe) + # # => "<p>foo</p><br /><p>bar</p>" + # + def safe_join(array, sep=$,) + sep ||= "".html_safe + sep = ERB::Util.html_escape(sep) + + array.map { |i| ERB::Util.html_escape(i) }.join(sep).html_safe + end + end + end +end
\ No newline at end of file diff --git a/actionpack/lib/action_view/helpers/raw_output_helper.rb b/actionpack/lib/action_view/helpers/raw_output_helper.rb deleted file mode 100644 index 216683a2e0..0000000000 --- a/actionpack/lib/action_view/helpers/raw_output_helper.rb +++ /dev/null @@ -1,18 +0,0 @@ -module ActionView #:nodoc: - # = Action View Raw Output Helper - module Helpers #:nodoc: - module RawOutputHelper - # This method outputs without escaping a string. Since escaping tags is - # now default, this can be used when you don't want Rails to automatically - # escape tags. This is not recommended if the data is coming from the user's - # input. - # - # For example: - # - # <%=raw @user.name %> - def raw(stringish) - stringish.to_s.html_safe - end - end - end -end
\ No newline at end of file diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb index ee51617a2b..786af5ca58 100644 --- a/actionpack/lib/action_view/helpers/tag_helper.rb +++ b/actionpack/lib/action_view/helpers/tag_helper.rb @@ -14,7 +14,7 @@ module ActionView BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked autobuffer autoplay controls loop selected hidden scoped async defer reversed ismap seemless muted required - autofocus novalidate formnovalidate open).to_set + autofocus novalidate formnovalidate open pubdate).to_set BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym }) # Returns an empty HTML tag of type +name+ which by default is XHTML diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index 3d276000a1..4f7f5c454f 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -459,7 +459,7 @@ module ActionView end AUTO_LINK_RE = %r{ - (?: ([\w+.:-]+:)// | www\. ) + (?: ([0-9A-Za-z+.:-]+:)// | www\. ) [^\s<]+ }x diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index c23315b344..2cd2dca711 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -253,8 +253,9 @@ module ActionView # using the +link_to+ method with the <tt>:method</tt> modifier as described in # the +link_to+ documentation. # - # The generated form element has a class name of <tt>button_to</tt> - # to allow styling of the form itself and its children. You can control + # By default, the generated form element has a class name of <tt>button_to</tt> + # to allow styling of the form itself and its children. This can be changed + # using the <tt>:form_class</tt> modifier within +html_options+. You can control # the form submission and input element behavior using +html_options+. # This method accepts the <tt>:method</tt> and <tt>:confirm</tt> modifiers # described in the +link_to+ documentation. If no <tt>:method</tt> modifier @@ -275,6 +276,8 @@ module ActionView # processed normally, otherwise no action is taken. # * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the # submit behaviour. By default this behaviour is an ajax submit. + # * <tt>:form_class</tt> - This controls the class of the form within which the submit button will + # be placed # # ==== Examples # <%= button_to "New", :action => "new" %> @@ -283,6 +286,12 @@ module ActionView # # </form>" # # + # <%= button_to "New", :action => "new", :form_class => "new-thing" %> + # # => "<form method="post" action="/controller/new" class="new-thing"> + # # <div><input value="New" type="submit" /></div> + # # </form>" + # + # # <%= button_to "Delete Image", { :action => "delete", :id => @image.id }, # :confirm => "Are you sure?", :method => :delete %> # # => "<form method="post" action="/images/delete/1" class="button_to"> @@ -312,6 +321,7 @@ module ActionView end form_method = method.to_s == 'get' ? 'get' : 'post' + form_class = html_options.delete('form_class') || 'button_to' remote = html_options.delete('remote') @@ -327,7 +337,7 @@ module ActionView html_options.merge!("type" => "submit", "value" => name) - ("<form method=\"#{form_method}\" action=\"#{ERB::Util.html_escape(url)}\" #{"data-remote=\"true\"" if remote} class=\"button_to\"><div>" + + ("<form method=\"#{form_method}\" action=\"#{ERB::Util.html_escape(url)}\" #{"data-remote=\"true\"" if remote} class=\"#{ERB::Util.html_escape(form_class)}\"><div>" + method_tag + tag("input", html_options) + request_token_tag + "</div></form>").html_safe end @@ -487,13 +497,14 @@ module ActionView email_address_obfuscated = email_address.dup email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.key?("replace_at") email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.key?("replace_dot") - case encode when "javascript" - string = - "document.write('#{content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe))}');".unpack('C*').map { |c| - sprintf("%%%x", c) - }.join + string = '' + html = content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe)) + html = escape_javascript(html) + "document.write('#{html}');".each_byte do |c| + string << sprintf("%%%x", c) + end "<script type=\"#{Mime::JS}\">eval(decodeURIComponent('#{string}'))</script>".html_safe when "hex" email_address_encoded = email_address_obfuscated.unpack('C*').map {|c| diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb index d524c68450..06c607931d 100644 --- a/actionpack/lib/action_view/lookup_context.rb +++ b/actionpack/lib/action_view/lookup_context.rb @@ -78,17 +78,17 @@ module ActionView @view_paths = ActionView::Base.process_view_paths(paths) end - def find(name, prefix = nil, partial = false, keys = []) - @view_paths.find(*args_for_lookup(name, prefix, partial, keys)) + def find(name, prefixes = [], partial = false, keys = []) + @view_paths.find(*args_for_lookup(name, prefixes, partial, keys)) end alias :find_template :find - def find_all(name, prefix = nil, partial = false, keys = []) - @view_paths.find_all(*args_for_lookup(name, prefix, partial, keys)) + def find_all(name, prefixes = [], partial = false, keys = []) + @view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys)) end - def exists?(name, prefix = nil, partial = false, keys = []) - @view_paths.exists?(*args_for_lookup(name, prefix, partial, keys)) + def exists?(name, prefixes = [], partial = false, keys = []) + @view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys)) end alias :template_exists? :exists? @@ -107,18 +107,26 @@ module ActionView protected - def args_for_lookup(name, prefix, partial, keys) #:nodoc: - name, prefix = normalize_name(name, prefix) - [name, prefix, partial || false, @details, details_key, keys] + def args_for_lookup(name, prefixes, partial, keys) #:nodoc: + name, prefixes = normalize_name(name, prefixes) + [name, prefixes, partial || false, @details, details_key, keys] end # Support legacy foo.erb names even though we now ignore .erb # as well as incorrectly putting part of the path in the template # name instead of the prefix. - def normalize_name(name, prefix) #:nodoc: + def normalize_name(name, prefixes) #:nodoc: name = name.to_s.gsub(handlers_regexp, '') parts = name.split('/') - return parts.pop, [prefix, *parts].compact.join("/") + name = parts.pop + + prefixes = if prefixes.blank? + [parts.join('/')] + else + prefixes.map { |prefix| [prefix, *parts].compact.join('/') } + end + + return name, prefixes end def default_handlers #:nodoc: @@ -156,11 +164,11 @@ module ActionView @frozen_formats = true end - # Overload formats= to reject [:"*/*"] values. + # Overload formats= to reject ["*/*"] values. def formats=(values) if values && values.size == 1 value = values.first - values = nil if value == :"*/*" + values = nil if value == "*/*" values << :html if value == :js end super(values) @@ -178,11 +186,11 @@ module ActionView end # Overload locale= to also set the I18n.locale. If the current I18n.config object responds - # to i18n_config, it means that it's has a copy of the original I18n configuration and it's + # to original_config, it means that it's has a copy of the original I18n configuration and it's # acting as proxy, which we need to skip. def locale=(value) if value - config = I18n.config.respond_to?(:i18n_config) ? I18n.config.i18n_config : I18n.config + config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config config.locale = value end @@ -237,4 +245,4 @@ module ActionView include Details include ViewPaths end -end
\ No newline at end of file +end diff --git a/actionpack/lib/action_view/partials.rb b/actionpack/lib/action_view/partials.rb index cd3f130dc4..c181689e62 100644 --- a/actionpack/lib/action_view/partials.rb +++ b/actionpack/lib/action_view/partials.rb @@ -12,19 +12,19 @@ module ActionView # # <%= render :partial => "account" %> # - # This would render "advertiser/_account.erb" and pass the instance variable @account in as a local variable + # This would render "advertiser/_account.html.erb" and pass the instance variable @account in as a local variable # +account+ to the template for display. # # In another template for Advertiser#buy, we could have: # # <%= render :partial => "account", :locals => { :account => @buyer } %> # - # <% for ad in @advertisements %> + # <% @advertisements.each do |ad| %> # <%= render :partial => "ad", :locals => { :ad => ad } %> # <% end %> # - # This would first render "advertiser/_account.erb" with @buyer passed in as the local variable +account+, then - # render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. + # This would first render "advertiser/_account.html.erb" with @buyer passed in as the local variable +account+, then + # render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display. # # == The :as and :object options # @@ -40,16 +40,16 @@ module ActionView # With the <tt>:as</tt> option we can specify a different name for said local variable. For example, if we # wanted it to be +agreement+ instead of +contract+ we'd do: # - # <%= render :partial => "contract", :as => :agreement %> + # <%= render :partial => "contract", :as => 'agreement' %> # # The <tt>:object</tt> option can be used to directly specify which object is rendered into the partial; # useful when the template's object is elsewhere, in a different ivar or in a local variable for instance. - # + # # Revisiting a previous example we could have written this code: - # + # # <%= render :partial => "account", :object => @buyer %> # - # <% for ad in @advertisements %> + # <% @advertisements.each do |ad| %> # <%= render :partial => "ad", :object => ad %> # <% end %> # @@ -64,12 +64,12 @@ module ActionView # # <%= render :partial => "ad", :collection => @advertisements %> # - # This will render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. An + # This will render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display. An # iteration counter will automatically be made available to the template with a name of the form # +partial_name_counter+. In the case of the example above, the template would be fed +ad_counter+. # # The <tt>:as</tt> option may be used when rendering partials. - # + # # You can specify a partial to be rendered between elements via the <tt>:spacer_template</tt> option. # The following example will render <tt>advertiser/_ad_divider.html.erb</tt> between each ad partial: # @@ -89,7 +89,7 @@ module ActionView # # <%= render :partial => "advertisement/ad", :locals => { :ad => @advertisement } %> # - # This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from. + # This will render the partial "advertisement/_ad.html.erb" regardless of which controller this is being called from. # # == Rendering objects with the RecordIdentifier # diff --git a/actionpack/lib/action_view/path_set.rb b/actionpack/lib/action_view/path_set.rb index fa35120a0d..e3de3e1eac 100644 --- a/actionpack/lib/action_view/path_set.rb +++ b/actionpack/lib/action_view/path_set.rb @@ -11,13 +11,15 @@ module ActionView #:nodoc: end def find(*args) - find_all(*args).first || raise(MissingTemplate.new(self, "#{args[1]}/#{args[0]}", args[3], args[2])) + find_all(*args).first || raise(MissingTemplate.new(self, *args)) end - def find_all(*args) - each do |resolver| - templates = resolver.find_all(*args) - return templates unless templates.empty? + def find_all(path, prefixes = [], *args) + prefixes.each do |prefix| + each do |resolver| + templates = resolver.find_all(path, prefix, *args) + return templates unless templates.empty? + end end [] end diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb index 317479ad4c..94c0a8a8fb 100644 --- a/actionpack/lib/action_view/renderer/partial_renderer.rb +++ b/actionpack/lib/action_view/renderer/partial_renderer.rb @@ -108,11 +108,11 @@ module ActionView locals << @variable_counter if @collection find_template(path, locals) end - end + end def find_template(path=@path, locals=@locals.keys) - prefix = @view.controller_prefix unless path.include?(?/) - @lookup_context.find_template(path, prefix, true, locals) + prefixes = path.include?(?/) ? [] : @view.controller_prefixes + @lookup_context.find_template(path, prefixes, true, locals) end def collection_with_template @@ -152,14 +152,14 @@ module ActionView object = object.to_model if object.respond_to?(:to_model) object.class.model_name.partial_path.dup.tap do |partial| - path = @view.controller_prefix + path = @view.controller_prefixes.first partial.insert(0, "#{File.dirname(path)}/") if partial.include?(?/) && path.include?(?/) end end end def retrieve_variable(path) - variable = @options[:as] || path[%r'_?(\w+)(\.\w+)*$', 1].to_sym + variable = @options[:as].try(:to_sym) || path[%r'_?(\w+)(\.\w+)*$', 1].to_sym variable_counter = :"#{variable}_counter" if @collection [variable, variable_counter] end diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb index ece3f621b6..9ae1636131 100644 --- a/actionpack/lib/action_view/renderer/template_renderer.rb +++ b/actionpack/lib/action_view/renderer/template_renderer.rb @@ -22,14 +22,14 @@ module ActionView def render_once(options) paths, locals = options[:once], options[:locals] || {} layout, keys = options[:layout], locals.keys - prefix = options.fetch(:prefix, @view.controller_prefix) + prefixes = options.fetch(:prefixes, @view.controller_prefixes) raise "render :once expects a String or an Array to be given" unless paths render_with_layout(layout, locals) do contents = [] Array.wrap(paths).each do |path| - template = find_template(path, prefix, false, keys) + template = find_template(path, prefixes, false, keys) contents << render_template(template, nil, locals) if @rendered.add?(template) end contents.join("\n") @@ -43,13 +43,13 @@ module ActionView if options.key?(:text) Template::Text.new(options[:text], formats.try(:first)) elsif options.key?(:file) - with_fallbacks { find_template(options[:file], options[:prefix], false, keys) } + with_fallbacks { find_template(options[:file], options[:prefixes], false, keys) } elsif options.key?(:inline) handler = Template.handler_for_extension(options[:type] || "erb") Template.new(options[:inline], "inline template", handler, :locals => keys) elsif options.key?(:template) options[:template].respond_to?(:render) ? - options[:template] : find_template(options[:template], options[:prefix], false, keys) + options[:template] : find_template(options[:template], options[:prefixes], false, keys) end end diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index 0d8373ef14..96d506fac5 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -123,7 +123,7 @@ module ActionView @locals = details[:locals] || [] @virtual_path = details[:virtual_path] @updated_at = details[:updated_at] || Time.now - @formats = Array.wrap(format).map(&:to_sym) + @formats = Array.wrap(format).map { |f| f.is_a?(Mime::Type) ? f.ref : f } end # Render a template. If the template was not compiled yet, it is done @@ -163,7 +163,7 @@ module ActionView name = pieces.pop partial = !!name.sub!(/^_/, "") lookup.disable_cache do - lookup.find_template(name, pieces.join('/'), partial, @locals) + lookup.find_template(name, [ pieces.join('/') ], partial, @locals) end end diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb index ff256738a9..e246646963 100644 --- a/actionpack/lib/action_view/template/error.rb +++ b/actionpack/lib/action_view/template/error.rb @@ -27,7 +27,7 @@ module ActionView class MissingTemplate < ActionViewError #:nodoc: attr_reader :path - def initialize(paths, path, details, partial) + def initialize(paths, path, prefixes, partial, details, *) @path = path display_paths = paths.compact.map{ |p| p.to_s.inspect }.join(", ") template_type = if partial @@ -38,7 +38,11 @@ module ActionView 'template' end - super("Missing #{template_type} #{path} with #{details.inspect} in view paths #{display_paths}") + searched_paths = prefixes.map { |prefix| [prefix, path].join("/") } + + out = "Missing #{template_type} #{searched_paths.join(", ")} with #{details.inspect}. Searched in:\n" + out += paths.compact.map { |p| " * #{p.to_s.inspect}\n" }.join + super out end end @@ -52,6 +56,7 @@ module ActionView attr_reader :original_exception, :backtrace def initialize(template, assigns, original_exception) + super(original_exception.message) @template, @assigns, @original_exception = template, assigns.dup, original_exception @sub_templates = nil @backtrace = original_exception.backtrace @@ -61,10 +66,6 @@ module ActionView @template.identifier end - def message - ActiveSupport::Deprecation.silence { original_exception.message } - end - def sub_template_message if @sub_templates "Trace of template inclusion: " + diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb index 0dccc99d14..4d999fb3b2 100644 --- a/actionpack/lib/action_view/template/resolver.rb +++ b/actionpack/lib/action_view/template/resolver.rb @@ -47,7 +47,7 @@ module ActionView path end - # Hnadles templates caching. If a key is given and caching is on + # Handles templates caching. If a key is given and caching is on # always check the cache before hitting the resolver. Otherwise, # it always hits the resolver but check if the resolver is fresher # before returning it. @@ -109,18 +109,27 @@ module ActionView def query(path, exts, formats) query = File.join(@path, path) - exts.each do |ext| - query << '{' << ext.map {|e| e && ".#{e}" }.join(',') << ',}' - end + query << exts.map { |ext| + "{#{ext.compact.map { |e| ".#{e}" }.join(',')},}" + }.join - Dir[query].reject { |p| File.directory?(p) }.map do |p| - handler, format = extract_handler_and_format(p, formats) + query.gsub!(/\{\.html,/, "{.html,.text.html,") + query.gsub!(/\{\.text,/, "{.text,.text.plain,") + + templates = [] + sanitizer = Hash.new { |h,k| h[k] = Dir["#{File.dirname(k)}/*"] } + Dir[query].each do |p| + next if File.directory?(p) || !sanitizer[p].include?(p) + + handler, format = extract_handler_and_format(p, formats) contents = File.open(p, "rb") {|io| io.read } - Template.new(contents, File.expand_path(p), handler, + templates << Template.new(contents, File.expand_path(p), handler, :virtual_path => path, :format => format, :updated_at => mtime(p)) end + + templates end # Returns the file mtime from the filesystem. diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index 4026f7a40e..2ce109ea99 100644 --- a/actionpack/lib/action_view/test_case.rb +++ b/actionpack/lib/action_view/test_case.rb @@ -156,10 +156,8 @@ module ActionView # The instance of ActionView::Base that is used by +render+. def view @view ||= begin - view = ActionView::Base.new(ActionController::Base.view_paths, {}, @controller) + view = @controller.view_context view.singleton_class.send :include, _helpers - view.singleton_class.send :include, @controller._routes.url_helpers - view.singleton_class.send :delegate, :alert, :notice, :to => "request.flash" view.extend(Locals) view.locals = self.locals view.output_buffer = self.output_buffer @@ -171,6 +169,7 @@ module ActionView INTERNAL_IVARS = %w{ @__name__ + @__io__ @_assertion_wrapped @_assertions @_result diff --git a/actionpack/lib/action_view/testing/resolvers.rb b/actionpack/lib/action_view/testing/resolvers.rb index 55583096e0..5c5cab7c7d 100644 --- a/actionpack/lib/action_view/testing/resolvers.rb +++ b/actionpack/lib/action_view/testing/resolvers.rb @@ -13,7 +13,11 @@ module ActionView #:nodoc: @hash = hash end - private + def to_s + @hash.keys.join(', ') + end + + private def query(path, exts, formats) query = "" diff --git a/actionpack/test/abstract/abstract_controller_test.rb b/actionpack/test/abstract/abstract_controller_test.rb index 19855490b4..981c023d38 100644 --- a/actionpack/test/abstract/abstract_controller_test.rb +++ b/actionpack/test/abstract/abstract_controller_test.rb @@ -30,14 +30,14 @@ module AbstractController class RenderingController < AbstractController::Base include ::AbstractController::Rendering - def _prefix() end + def _prefixes + [] + end def render(options = {}) if options.is_a?(String) options = {:_template_name => options} end - - options[:_prefix] = _prefix super end @@ -116,8 +116,8 @@ module AbstractController name.underscore end - def _prefix - self.class.prefix + def _prefixes + [self.class.prefix] end end @@ -157,10 +157,10 @@ module AbstractController private def self.layout(formats) begin - find_template(name.underscore, {:formats => formats}, :_prefix => "layouts") + find_template(name.underscore, {:formats => formats}, :_prefixes => ["layouts"]) rescue ActionView::MissingTemplate begin - find_template("application", {:formats => formats}, :_prefix => "layouts") + find_template("application", {:formats => formats}, :_prefixes => ["layouts"]) rescue ActionView::MissingTemplate end end diff --git a/actionpack/test/abstract/callbacks_test.rb b/actionpack/test/abstract/callbacks_test.rb index 2d02078020..3bdde86291 100644 --- a/actionpack/test/abstract/callbacks_test.rb +++ b/actionpack/test/abstract/callbacks_test.rb @@ -22,7 +22,7 @@ module AbstractController class TestCallbacks1 < ActiveSupport::TestCase test "basic callbacks work" do controller = Callback1.new - result = controller.process(:index) + controller.process(:index) assert_equal "Hello world", controller.response_body end end @@ -62,7 +62,7 @@ module AbstractController end test "before_filter works" do - result = @controller.process(:index) + @controller.process(:index) assert_equal "Hello world", @controller.response_body end @@ -78,7 +78,7 @@ module AbstractController test "before_filter with overwritten condition" do @controller = Callback2Overwrite.new - result = @controller.process(:index) + @controller.process(:index) assert_equal "", @controller.response_body end end @@ -103,12 +103,12 @@ module AbstractController end test "before_filter works with procs" do - result = @controller.process(:index) + @controller.process(:index) assert_equal "Hello world", @controller.response_body end test "after_filter works with procs" do - result = @controller.process(:index) + @controller.process(:index) assert_equal "Goodbye", @controller.instance_variable_get("@second") end end @@ -152,7 +152,7 @@ module AbstractController end test "when :except is specified, an after filter is not triggered on that action" do - result = @controller.process(:index) + @controller.process(:index) assert !@controller.instance_variable_defined?("@authenticated") end end @@ -186,17 +186,17 @@ module AbstractController end test "when :only is specified with an array, a before filter is triggered on that action" do - result = @controller.process(:index) + @controller.process(:index) assert_equal "Hello, World", @controller.response_body end test "when :only is specified with an array, a before filter is not triggered on other actions" do - result = @controller.process(:sekrit_data) + @controller.process(:sekrit_data) assert_equal "true", @controller.response_body end test "when :except is specified with an array, an after filter is not triggered on that action" do - result = @controller.process(:index) + @controller.process(:index) assert !@controller.instance_variable_defined?("@authenticated") end end @@ -216,12 +216,12 @@ module AbstractController end test "when a callback is modified in a child with :only, it works for the :only action" do - result = @controller.process(:index) + @controller.process(:index) assert_equal "Hello world", @controller.response_body end test "when a callback is modified in a child with :only, it does not work for other actions" do - result = @controller.process(:not_index) + @controller.process(:not_index) assert_equal "", @controller.response_body end end @@ -246,5 +246,26 @@ module AbstractController end end + class CallbacksWithArgs < ControllerWithCallbacks + set_callback :process_action, :before, :first + + def first + @text = "Hello world" + end + + def index(text) + self.response_body = @text + text + end + end + + class TestCallbacksWithArgs < ActiveSupport::TestCase + test "callbacks still work when invoking process with multiple args" do + controller = CallbacksWithArgs.new + controller.process(:index, " Howdy!") + assert_equal "Hello world Howdy!", controller.response_body + end + end + + end end diff --git a/actionpack/test/abstract/render_test.rb b/actionpack/test/abstract/render_test.rb index 25dc8bd804..b9293d1241 100644 --- a/actionpack/test/abstract/render_test.rb +++ b/actionpack/test/abstract/render_test.rb @@ -6,8 +6,8 @@ module AbstractController class ControllerRenderer < AbstractController::Base include AbstractController::Rendering - def _prefix - "renderer" + def _prefixes + %w[renderer] end self.view_paths = [ActionView::FixtureResolver.new( diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index c7b54eb0ba..cc393d3ef4 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -156,6 +156,17 @@ class PageCachingTest < ActionController::TestCase assert_page_not_cached :ok end + def test_page_caching_directory_set_as_pathname + begin + ActionController::Base.page_cache_directory = Pathname.new(FILE_STORE_PATH) + get :ok + assert_response :ok + assert_page_cached :ok + ensure + ActionController::Base.page_cache_directory = FILE_STORE_PATH + end + end + private def assert_page_cached(action, message = "#{action} should have been cached") assert page_cached?(action), message @@ -257,7 +268,6 @@ class ActionCachingMockController end def request - mocked_path = @mock_path Object.new.instance_eval(<<-EVAL) def path; '#{@mock_path}' end def format; 'all' end @@ -416,7 +426,6 @@ class ActionCacheTest < ActionController::TestCase get :index assert_response :success - new_cached_time = content_to_cache assert_not_equal cached_time, @response.body end diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb index 68febf425d..330fa276d0 100644 --- a/actionpack/test/controller/filters_test.rb +++ b/actionpack/test/controller/filters_test.rb @@ -664,7 +664,7 @@ class FilterTest < ActionController::TestCase end def test_prepending_and_appending_around_filter - controller = test_process(MixedFilterController) + test_process(MixedFilterController) assert_equal " before aroundfilter before procfilter before appended aroundfilter " + " after appended aroundfilter after procfilter after aroundfilter ", MixedFilterController.execution_log @@ -677,26 +677,26 @@ class FilterTest < ActionController::TestCase end def test_before_filter_rendering_breaks_filtering_chain_for_after_filter - response = test_process(RenderingController) + test_process(RenderingController) assert_equal %w( before_filter_rendering ), assigns["ran_filter"] assert !assigns["ran_action"] end def test_before_filter_redirects_breaks_filtering_chain_for_after_filter - response = test_process(BeforeFilterRedirectionController) + test_process(BeforeFilterRedirectionController) assert_response :redirect assert_equal "http://test.host/filter_test/before_filter_redirection/target_of_redirection", redirect_to_url assert_equal %w( before_filter_redirects ), assigns["ran_filter"] end def test_before_filter_rendering_breaks_filtering_chain_for_preprend_after_filter - response = test_process(RenderingForPrependAfterFilterController) + test_process(RenderingForPrependAfterFilterController) assert_equal %w( before_filter_rendering ), assigns["ran_filter"] assert !assigns["ran_action"] end def test_before_filter_redirects_breaks_filtering_chain_for_preprend_after_filter - response = test_process(BeforeFilterRedirectionForPrependAfterFilterController) + test_process(BeforeFilterRedirectionForPrependAfterFilterController) assert_response :redirect assert_equal "http://test.host/filter_test/before_filter_redirection_for_prepend_after_filter/target_of_redirection", redirect_to_url assert_equal %w( before_filter_redirects ), assigns["ran_filter"] diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb index e6fe0b1f04..ddfa3df552 100644 --- a/actionpack/test/controller/log_subscriber_test.rb +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -32,6 +32,11 @@ module Another cache_page("Super soaker", "/index.html") render :nothing => true end + + def with_exception + raise Exception + end + end end @@ -139,20 +144,20 @@ class ACLogSubscriberTest < ActionController::TestCase wait assert_equal 4, logs.size - assert_match(/Exist fragment\? views\/foo/, logs[1]) + assert_match(/Read fragment views\/foo/, logs[1]) assert_match(/Write fragment views\/foo/, logs[2]) ensure @controller.config.perform_caching = true end - + def test_with_fragment_cache_and_percent_in_key @controller.config.perform_caching = true get :with_fragment_cache_and_percent_in_key wait assert_equal 4, logs.size - assert_match(/Exist fragment\? views\/foo%bar/, logs[1]) - assert_match(/Write fragment views\/foo%bar/, logs[2]) + assert_match(/Read fragment views\/foo/, logs[1]) + assert_match(/Write fragment views\/foo/, logs[2]) ensure @controller.config.perform_caching = true end @@ -169,6 +174,16 @@ class ACLogSubscriberTest < ActionController::TestCase @controller.config.perform_caching = true end + def test_process_action_with_exception_includes_http_status_code + begin + get :with_exception + wait + rescue Exception + end + assert_equal 2, logs.size + assert_match(/Completed 500/, logs.last) + end + def logs @logs ||= @logger.logged(:info) end diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index 98c9d43b93..5debf96232 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -565,7 +565,7 @@ class RespondWithController < ActionController::Base def using_resource_with_action respond_with(resource, :action => :foo) do |format| - format.html { raise ActionView::MissingTemplate.new([], "foo/bar", {}, false) } + format.html { raise ActionView::MissingTemplate.new([], "bar", ["foo"], {}, false) } end end @@ -658,7 +658,7 @@ class RespondWithControllerTest < ActionController::TestCase @request.accept = "application/json" get :using_hash_resource assert_equal "application/json", @response.content_type - assert_equal %Q[{"result":["david",13]}], @response.body + assert_equal %Q[{"result":{"name":"david","id":13}}], @response.body end def test_using_resource_with_block diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb index 543c02b2c5..3ca29f1bcf 100644 --- a/actionpack/test/controller/new_base/bare_metal_test.rb +++ b/actionpack/test/controller/new_base/bare_metal_test.rb @@ -35,7 +35,7 @@ module BareMetalTest class HeadTest < ActiveSupport::TestCase test "head works on its own" do - status, headers, body = HeadController.action(:index).call(Rack::MockRequest.env_for("/")) + status = HeadController.action(:index).call(Rack::MockRequest.env_for("/")).first assert_equal 404, status end end diff --git a/actionpack/test/controller/new_base/content_negotiation_test.rb b/actionpack/test/controller/new_base/content_negotiation_test.rb index b98a22dfcc..5fd5946619 100644 --- a/actionpack/test/controller/new_base/content_negotiation_test.rb +++ b/actionpack/test/controller/new_base/content_negotiation_test.rb @@ -7,6 +7,10 @@ module ContentNegotiation self.view_paths = [ActionView::FixtureResolver.new( "content_negotiation/basic/hello.html.erb" => "Hello world <%= request.formats.first.to_s %>!" )] + + def all + render :text => self.formats.inspect + end end class TestContentNegotiation < Rack::TestCase @@ -14,5 +18,10 @@ module ContentNegotiation get "/content_negotiation/basic/hello", {}, "HTTP_ACCEPT" => "*/*" assert_body "Hello world */*!" end + + test "Not all mimes are converted to symbol" do + get "/content_negotiation/basic/all", {}, "HTTP_ACCEPT" => "text/plain, mime/another" + assert_body '[:text, "mime/another"]' + end end end diff --git a/actionpack/test/controller/new_base/render_once_test.rb b/actionpack/test/controller/new_base/render_once_test.rb index 3035ed4ff2..175abf8a7e 100644 --- a/actionpack/test/controller/new_base/render_once_test.rb +++ b/actionpack/test/controller/new_base/render_once_test.rb @@ -18,8 +18,8 @@ module RenderTemplate self.view_paths = [RESOLVER] - def _prefix - "test" + def _prefixes + %w(test) end def multiple @@ -39,11 +39,11 @@ module RenderTemplate end def with_prefix - render :once => "result", :prefix => "other" + render :once => "result", :prefixes => %w(other) end def with_nil_prefix - render :once => "test/result", :prefix => nil + render :once => "test/result", :prefixes => [] end end diff --git a/actionpack/test/controller/new_base/render_partial_test.rb b/actionpack/test/controller/new_base/render_partial_test.rb index d800ea264d..83b0d039ad 100644 --- a/actionpack/test/controller/new_base/render_partial_test.rb +++ b/actionpack/test/controller/new_base/render_partial_test.rb @@ -9,7 +9,10 @@ module RenderPartial "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>", "render_partial/basic/with_json.html.erb" => "<%= render 'with_json.json' %>", "render_partial/basic/_with_json.json.erb" => "<%= render 'final' %>", - "render_partial/basic/_final.json.erb" => "{ final: json }" + "render_partial/basic/_final.json.erb" => "{ final: json }", + "render_partial/basic/overriden.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'overriden' %><%= @test_unchanged %>", + "render_partial/basic/_overriden.html.erb" => "ParentPartial!", + "render_partial/child/_overriden.html.erb" => "OverridenPartial!" )] def html_with_json_inside_json @@ -20,7 +23,13 @@ module RenderPartial @test_unchanged = 'hello' render :action => "basic" end + + def overriden + @test_unchanged = 'hello' + end end + + class ChildController < BasicController; end class TestPartial < Rack::TestCase testing BasicController @@ -37,4 +46,18 @@ module RenderPartial end end + class TestInheritedPartial < Rack::TestCase + testing ChildController + + test "partial from parent controller gets picked if missing in child one" do + get :changing + assert_response("goodbyeBasicPartial!goodbye") + end + + test "partial from child controller gets picked" do + get :overriden + assert_response("goodbyeOverridenPartial!goodbye") + end + end + end diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb index df97a2725b..d6062bfa8c 100644 --- a/actionpack/test/controller/new_base/render_test.rb +++ b/actionpack/test/controller/new_base/render_test.rb @@ -6,7 +6,11 @@ module Render "render/blank_render/index.html.erb" => "Hello world!", "render/blank_render/access_request.html.erb" => "The request: <%= request.method.to_s.upcase %>", "render/blank_render/access_action_name.html.erb" => "Action Name: <%= action_name %>", - "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>" + "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>", + "render/blank_render/overriden_with_own_view_paths_appended.html.erb" => "parent content", + "render/blank_render/overriden_with_own_view_paths_prepended.html.erb" => "parent content", + "render/blank_render/overriden.html.erb" => "parent content", + "render/child_render/overriden.html.erb" => "child content" )] def index @@ -21,6 +25,15 @@ module Render render :action => "access_action_name" end + def overriden_with_own_view_paths_appended + end + + def overriden_with_own_view_paths_prepended + end + + def overriden + end + private def secretz @@ -35,6 +48,11 @@ module Render end end + class ChildRenderController < BlankRenderController + append_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_appended.html.erb" => "child content") + prepend_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_prepended.html.erb" => "child content") + end + class RenderTest < Rack::TestCase test "render with blank" do with_routing do |set| @@ -94,4 +112,26 @@ module Render assert_body "Controller Name: blank_render" end end + + class TestViewInheritance < Rack::TestCase + test "Template from child controller gets picked over parent one" do + get "/render/child_render/overriden" + assert_body "child content" + end + + test "Template from child controller with custom view_paths prepended gets picked over parent one" do + get "/render/child_render/overriden_with_own_view_paths_prepended" + assert_body "child content" + end + + test "Template from child controller with custom view_paths appended gets picked over parent one" do + get "/render/child_render/overriden_with_own_view_paths_appended" + assert_body "child content" + end + + test "Template from parent controller gets picked if missing in child controller" do + get "/render/child_render/index" + assert_body "Hello world!" + end + end end diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb index 6dd2a9f23d..fc604a2db3 100644 --- a/actionpack/test/controller/render_json_test.rb +++ b/actionpack/test/controller/render_json_test.rb @@ -26,6 +26,10 @@ class RenderJsonTest < ActionController::TestCase render :json => nil end + def render_json_render_to_string + render :text => render_to_string(:json => '[]') + end + def render_json_hello_world render :json => ActiveSupport::JSON.encode(:hello => 'world') end @@ -76,6 +80,12 @@ class RenderJsonTest < ActionController::TestCase assert_equal 'application/json', @response.content_type end + def test_render_json_render_to_string + get :render_json_render_to_string + assert_equal '[]', @response.body + end + + def test_render_json get :render_json_hello_world assert_equal '{"hello":"world"}', @response.body diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index fca8de60bc..be492152f2 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -125,6 +125,10 @@ class TestController < ActionController::Base render :action => "hello_world" end + def render_action_upcased_hello_world + render :action => "Hello_world" + end + def render_action_hello_world_as_string render "hello_world" end @@ -742,6 +746,12 @@ class RenderTest < ActionController::TestCase assert_template "test/hello_world" end + def test_render_action_upcased + assert_raise ActionView::MissingTemplate do + get :render_action_upcased_hello_world + end + end + # :ported: def test_render_action_hello_world_as_string get :render_action_hello_world_as_string diff --git a/actionpack/test/controller/request/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb index 0a39feb7fe..e624f11773 100644 --- a/actionpack/test/controller/request/test_request_test.rb +++ b/actionpack/test/controller/request/test_request_test.rb @@ -29,8 +29,7 @@ class ActionController::TestRequestTest < ActiveSupport::TestCase end def test_session_id_different_on_each_call - prev_id = assert_not_equal(@request.session_options[:id], ActionController::TestRequest.new.session_options[:id]) end -end
\ No newline at end of file +end diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index 2c9aa6187b..d520b5e512 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -12,6 +12,14 @@ module RequestForgeryProtectionActions render :inline => "<%= button_to('New', '/') {} %>" end + def external_form + render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => 'external_token') {} %>" + end + + def external_form_without_protection + render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => false) {} %>" + end + def unsafe render :text => 'pwn' end @@ -20,6 +28,14 @@ module RequestForgeryProtectionActions render :inline => "<%= csrf_meta_tags %>" end + def external_form_for + render :inline => "<%= form_for(:some_resource, :authenticity_token => 'external_token') {} %>" + end + + def form_for_without_protection + render :inline => "<%= form_for(:some_resource, :authenticity_token => false ) {} %>" + end + def rescue_action(e) raise e end end @@ -29,6 +45,16 @@ class RequestForgeryProtectionController < ActionController::Base protect_from_forgery :only => %w(index meta) end +class RequestForgeryProtectionControllerUsingOldBehaviour < ActionController::Base + include RequestForgeryProtectionActions + protect_from_forgery :only => %w(index meta) + + def handle_unverified_request + raise(ActionController::InvalidAuthenticityToken) + end +end + + class FreeCookieController < RequestForgeryProtectionController self.allow_forgery_protection = false @@ -51,152 +77,92 @@ end # common test methods module RequestForgeryProtectionTests - def teardown - ActionController::Base.request_forgery_protection_token = nil + def setup + @token = "cf50faa3fe97702ca1ae" + + ActiveSupport::SecureRandom.stubs(:base64).returns(@token) + ActionController::Base.request_forgery_protection_token = :authenticity_token end + def test_should_render_form_with_token_tag - get :index + assert_not_blocked do + get :index + end assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token end def test_should_render_button_to_with_token_tag - get :show_button + assert_not_blocked do + get :show_button + end assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token end def test_should_allow_get - get :index - assert_response :success + assert_not_blocked { get :index } end def test_should_allow_post_without_token_on_unsafe_action - post :unsafe - assert_response :success - end - - def test_should_not_allow_html_post_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raise(ActionController::InvalidAuthenticityToken) { post :index, :format => :html } - end - - def test_should_not_allow_html_put_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raise(ActionController::InvalidAuthenticityToken) { put :index, :format => :html } - end - - def test_should_not_allow_html_delete_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raise(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html } - end - - def test_should_allow_api_formatted_post_without_token - assert_nothing_raised do - post :index, :format => 'xml' - end - end - - def test_should_not_allow_api_formatted_put_without_token - assert_nothing_raised do - put :index, :format => 'xml' - end - end - - def test_should_allow_api_formatted_delete_without_token - assert_nothing_raised do - delete :index, :format => 'xml' - end + assert_not_blocked { post :unsafe } end - def test_should_not_allow_api_formatted_post_sent_as_url_encoded_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - post :index, :format => 'xml' - end + def test_should_not_allow_post_without_token + assert_blocked { post :index } end - def test_should_not_allow_api_formatted_put_sent_as_url_encoded_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - put :index, :format => 'xml' - end + def test_should_not_allow_post_without_token_irrespective_of_format + assert_blocked { post :index, :format=>'xml' } end - def test_should_not_allow_api_formatted_delete_sent_as_url_encoded_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - delete :index, :format => 'xml' - end + def test_should_not_allow_put_without_token + assert_blocked { put :index } end - def test_should_not_allow_api_formatted_post_sent_as_multipart_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s - post :index, :format => 'xml' - end - end - - def test_should_not_allow_api_formatted_put_sent_as_multipart_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s - put :index, :format => 'xml' - end - end - - def test_should_not_allow_api_formatted_delete_sent_as_multipart_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s - delete :index, :format => 'xml' - end + def test_should_not_allow_delete_without_token + assert_blocked { delete :index } end - def test_should_allow_xhr_post_without_token - assert_nothing_raised { xhr :post, :index } + def test_should_not_allow_xhr_post_without_token + assert_blocked { xhr :post, :index } end - def test_should_allow_xhr_put_without_token - assert_nothing_raised { xhr :put, :index } + def test_should_allow_post_with_token + assert_not_blocked { post :index, :authenticity_token => @token } end - def test_should_allow_xhr_delete_without_token - assert_nothing_raised { xhr :delete, :index } + def test_should_allow_put_with_token + assert_not_blocked { put :index, :authenticity_token => @token } end - def test_should_allow_xhr_post_with_encoded_form_content_type_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_nothing_raised { xhr :post, :index } + def test_should_allow_delete_with_token + assert_not_blocked { delete :index, :authenticity_token => @token } end - def test_should_allow_post_with_token - post :index, :authenticity_token => @token - assert_response :success + def test_should_allow_post_with_token_in_header + @request.env['HTTP_X_CSRF_TOKEN'] = @token + assert_not_blocked { post :index } end - def test_should_allow_put_with_token - put :index, :authenticity_token => @token - assert_response :success + def test_should_allow_delete_with_token_in_header + @request.env['HTTP_X_CSRF_TOKEN'] = @token + assert_not_blocked { delete :index } end - def test_should_allow_delete_with_token - delete :index, :authenticity_token => @token - assert_response :success + def test_should_allow_put_with_token_in_header + @request.env['HTTP_X_CSRF_TOKEN'] = @token + assert_not_blocked { put :index } end - def test_should_allow_post_with_xml - @request.env['CONTENT_TYPE'] = Mime::XML.to_s - post :index, :format => 'xml' + def assert_blocked + session[:something_like_user_id] = 1 + yield + assert_nil session[:something_like_user_id], "session values are still present" assert_response :success end - def test_should_allow_put_with_xml - @request.env['CONTENT_TYPE'] = Mime::XML.to_s - put :index, :format => 'xml' - assert_response :success - end - - def test_should_allow_delete_with_xml - @request.env['CONTENT_TYPE'] = Mime::XML.to_s - delete :index, :format => 'xml' + def assert_not_blocked + assert_nothing_raised { yield } assert_response :success end end @@ -205,16 +171,6 @@ end class RequestForgeryProtectionControllerTest < ActionController::TestCase include RequestForgeryProtectionTests - def setup - @controller = RequestForgeryProtectionController.new - @request = ActionController::TestRequest.new - @request.format = :html - @response = ActionController::TestResponse.new - @token = "cf50faa3fe97702ca1ae" - - ActiveSupport::SecureRandom.stubs(:base64).returns(@token) - ActionController::Base.request_forgery_protection_token = :authenticity_token - end test 'should emit a csrf-token meta tag' do ActiveSupport::SecureRandom.stubs(:base64).returns(@token + '<=?') @@ -226,6 +182,15 @@ class RequestForgeryProtectionControllerTest < ActionController::TestCase end end +class RequestForgeryProtectionControllerUsingOldBehaviourTest < ActionController::TestCase + include RequestForgeryProtectionTests + def assert_blocked + assert_raises(ActionController::InvalidAuthenticityToken) do + yield + end + end +end + class FreeCookieControllerTest < ActionController::TestCase def setup @controller = FreeCookieController.new @@ -258,13 +223,23 @@ class FreeCookieControllerTest < ActionController::TestCase end end + + + + class CustomAuthenticityParamControllerTest < ActionController::TestCase def setup + ActionController::Base.request_forgery_protection_token = :custom_token_name + super + end + + def teardown ActionController::Base.request_forgery_protection_token = :authenticity_token + super end def test_should_allow_custom_token - post :index, :authenticity_token => 'foobar' + post :index, :custom_token_name => 'foobar' assert_response :ok end end diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 89f0d03c56..5f6f1b61c0 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -701,7 +701,7 @@ class RouteSetTest < ActiveSupport::TestCase set.draw do match '/users/index' => 'users#index' end - params = set.recognize_path('/users/index', :method => :get) + set.recognize_path('/users/index', :method => :get) assert_equal 1, set.routes.size end @@ -980,7 +980,7 @@ class RouteSetTest < ActiveSupport::TestCase match '/profile' => 'profile#index' end - params = set.recognize_path("/profile") rescue nil + set.recognize_path("/profile") rescue nil assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded" end diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index 1f62d29e80..1c28da33bd 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -95,16 +95,29 @@ module AbstractController ) end - def test_protocol_with_and_without_separator + def test_protocol_with_and_without_separators add_host! assert_equal('https://www.basecamphq.com/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https') ) assert_equal('https://www.basecamphq.com/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https:') + ) + assert_equal('https://www.basecamphq.com/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https://') ) end + def test_without_protocol + add_host! + assert_equal('//www.basecamphq.com/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => '//') + ) + assert_equal('//www.basecamphq.com/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => false) + ) + end + def test_trailing_slash add_host! options = {:controller => 'foo', :trailing_slash => true, :action => 'bar', :id => '33'} diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb index 6ba4c6c48d..621fb79915 100644 --- a/actionpack/test/controller/webservice_test.rb +++ b/actionpack/test/controller/webservice_test.rb @@ -216,7 +216,7 @@ class WebServiceTest < ActionDispatch::IntegrationTest def test_typecast_as_yaml with_test_route_set do with_params_parsers Mime::YAML => :yaml do - yaml = <<-YAML + yaml = (<<-YAML).strip --- data: a: 15 diff --git a/actionpack/test/dispatch/callbacks_test.rb b/actionpack/test/dispatch/callbacks_test.rb index 5becb621de..eed2eca2ab 100644 --- a/actionpack/test/dispatch/callbacks_test.rb +++ b/actionpack/test/dispatch/callbacks_test.rb @@ -29,14 +29,16 @@ class DispatcherTest < ActiveSupport::TestCase assert_equal 4, Foo.b end - def test_to_prepare_deprecation - prepared = false - assert_deprecated do - ActionDispatch::Callbacks.to_prepare { prepared = true } - end + def test_to_prepare_and_cleanup_delegation + prepared = cleaned = false + ActionDispatch::Callbacks.to_prepare { prepared = true } + ActionDispatch::Callbacks.to_prepare { cleaned = true } ActionDispatch::Reloader.prepare! assert prepared + + ActionDispatch::Reloader.cleanup! + assert cleaned end private diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb index e2040401c7..1cfea6aa12 100644 --- a/actionpack/test/dispatch/cookies_test.rb +++ b/actionpack/test/dispatch/cookies_test.rb @@ -95,6 +95,26 @@ class CookiesTest < ActionController::TestCase head :ok end + def set_cookie_with_domain_and_tld + cookies[:user_name] = {:value => "rizwanreza", :domain => :all, :tld_length => 2} + head :ok + end + + def delete_cookie_with_domain_and_tld + cookies.delete(:user_name, :domain => :all, :tld_length => 2) + head :ok + end + + def set_cookie_with_domains + cookies[:user_name] = {:value => "rizwanreza", :domain => %w(example1.com example2.com .example3.com)} + head :ok + end + + def delete_cookie_with_domains + cookies.delete(:user_name, :domain => %w(example1.com example2.com .example3.com)) + head :ok + end + def symbol_key cookies[:user_name] = "david" head :ok @@ -322,6 +342,67 @@ class CookiesTest < ActionController::TestCase assert_cookie_header "user_name=; domain=.nextangle.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" end + def test_cookie_with_all_domain_option_and_tld_length + get :set_cookie_with_domain_and_tld + assert_response :success + assert_cookie_header "user_name=rizwanreza; domain=.nextangle.com; path=/" + end + + def test_cookie_with_all_domain_option_using_a_non_standard_tld_and_tld_length + @request.host = "two.subdomains.nextangle.local" + get :set_cookie_with_domain_and_tld + assert_response :success + assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/" + end + + def test_cookie_with_all_domain_option_using_host_with_port_and_tld_length + @request.host = "nextangle.local:3000" + get :set_cookie_with_domain_and_tld + assert_response :success + assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/" + end + + def test_deleting_cookie_with_all_domain_option_and_tld_length + get :delete_cookie_with_domain_and_tld + assert_response :success + assert_cookie_header "user_name=; domain=.nextangle.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" + end + + def test_cookie_with_several_preset_domains_using_one_of_these_domains + @request.host = "example1.com" + get :set_cookie_with_domains + assert_response :success + assert_cookie_header "user_name=rizwanreza; domain=example1.com; path=/" + end + + def test_cookie_with_several_preset_domains_using_other_domain + @request.host = "other-domain.com" + get :set_cookie_with_domains + assert_response :success + assert_cookie_header "user_name=rizwanreza; path=/" + end + + def test_cookie_with_several_preset_domains_using_shared_domain + @request.host = "example3.com" + get :set_cookie_with_domains + assert_response :success + assert_cookie_header "user_name=rizwanreza; domain=.example3.com; path=/" + end + + def test_deletings_cookie_with_several_preset_domains_using_one_of_these_domains + @request.host = "example2.com" + get :delete_cookie_with_domains + assert_response :success + assert_cookie_header "user_name=; domain=example2.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" + end + + def test_deletings_cookie_with_several_preset_domains_using_other_domain + @request.host = "other-domain.com" + get :delete_cookie_with_domains + assert_response :success + assert_cookie_header "user_name=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" + end + def test_cookies_hash_is_indifferent_access [:symbol_key, :string_key].each do |cookie_key| get cookie_key diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb index 9782f328fc..11cf68fdb3 100644 --- a/actionpack/test/dispatch/mime_type_test.rb +++ b/actionpack/test/dispatch/mime_type_test.rb @@ -131,6 +131,13 @@ class MimeTypeTest < ActiveSupport::TestCase assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" } end + test "references gives preference to symbols before strings" do + assert_equal :html, Mime::HTML.ref + another = Mime::Type.lookup("foo/bar") + assert_nil another.to_sym + assert_equal "foo/bar", another.ref + end + test "regexp matcher" do assert Mime::JS =~ "text/javascript" assert Mime::JS =~ "application/javascript" diff --git a/actionpack/test/dispatch/reloader_test.rb b/actionpack/test/dispatch/reloader_test.rb index 995b19030c..eaabc1feb3 100644 --- a/actionpack/test/dispatch/reloader_test.rb +++ b/actionpack/test/dispatch/reloader_test.rb @@ -116,6 +116,20 @@ class ReloaderTest < Test::Unit::TestCase assert cleaned end + def test_cleanup_callbacks_are_called_on_exceptions + cleaned = false + Reloader.to_cleanup { cleaned = true } + + begin + call_and_return_body do + raise "error" + end + rescue + end + + assert cleaned + end + private def call_and_return_body(&block) @reloader ||= Reloader.new(block || proc {[200, {}, 'response']}) diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index 75b674ec1a..dd5bf5ec2d 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -427,7 +427,7 @@ class RequestTest < ActiveSupport::TestCase begin request = stub_request(mock_rack_env) request.parameters - rescue TypeError => e + rescue TypeError # rack will raise a TypeError when parsing this query string end assert_equal({}, request.parameters) diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb index ab26d1a645..6f38714b2e 100644 --- a/actionpack/test/dispatch/response_test.rb +++ b/actionpack/test/dispatch/response_test.rb @@ -18,7 +18,7 @@ class ResponseTest < ActiveSupport::TestCase body.each { |part| parts << part } assert_equal ["Hello, World!"], parts end - + test "status handled properly in initialize" do assert_equal 200, ActionDispatch::Response.new('200 OK').status end @@ -26,7 +26,7 @@ class ResponseTest < ActiveSupport::TestCase test "utf8 output" do @response.body = [1090, 1077, 1089, 1090].pack("U*") - status, headers, body = @response.to_a + status, headers, _ = @response.to_a assert_equal 200, status assert_equal({ "Content-Type" => "text/html; charset=utf-8" @@ -52,20 +52,20 @@ class ResponseTest < ActiveSupport::TestCase test "content type" do [204, 304].each do |c| @response.status = c.to_s - status, headers, body = @response.to_a + _, headers, _ = @response.to_a assert !headers.has_key?("Content-Type"), "#{c} should not have Content-Type header" end [200, 302, 404, 500].each do |c| @response.status = c.to_s - status, headers, body = @response.to_a + _, headers, _ = @response.to_a assert headers.has_key?("Content-Type"), "#{c} did not have Content-Type header" end end test "does not include Status header" do @response.status = "200 OK" - status, headers, body = @response.to_a + _, headers, _ = @response.to_a assert !headers.has_key?('Status') end diff --git a/actionpack/test/dispatch/routing_assertions_test.rb b/actionpack/test/dispatch/routing_assertions_test.rb new file mode 100644 index 0000000000..9f95d82129 --- /dev/null +++ b/actionpack/test/dispatch/routing_assertions_test.rb @@ -0,0 +1,103 @@ +require 'abstract_unit' +require 'controller/fake_controllers' + +class SecureArticlesController < ArticlesController; end +class BlockArticlesController < ArticlesController; end + +class RoutingAssertionsTest < ActionController::TestCase + + def setup + @routes = ActionDispatch::Routing::RouteSet.new + @routes.draw do + resources :articles + + scope 'secure', :constraints => { :protocol => 'https://' } do + resources :articles, :controller => 'secure_articles' + end + + scope 'block', :constraints => lambda { |r| r.ssl? } do + resources :articles, :controller => 'block_articles' + end + end + end + + def test_assert_generates + assert_generates('/articles', { :controller => 'articles', :action => 'index' }) + assert_generates('/articles/1', { :controller => 'articles', :action => 'show', :id => '1' }) + end + + def test_assert_generates_with_defaults + assert_generates('/articles/1/edit', { :controller => 'articles', :action => 'edit' }, { :id => '1' }) + end + + def test_assert_generates_with_extras + assert_generates('/articles', { :controller => 'articles', :action => 'index', :page => '1' }, {}, { :page => '1' }) + end + + def test_assert_recognizes + assert_recognizes({ :controller => 'articles', :action => 'index' }, '/articles') + assert_recognizes({ :controller => 'articles', :action => 'show', :id => '1' }, '/articles/1') + end + + def test_assert_recognizes_with_extras + assert_recognizes({ :controller => 'articles', :action => 'index', :page => '1' }, '/articles', { :page => '1' }) + end + + def test_assert_recognizes_with_method + assert_recognizes({ :controller => 'articles', :action => 'create' }, { :path => '/articles', :method => :post }) + assert_recognizes({ :controller => 'articles', :action => 'update', :id => '1' }, { :path => '/articles/1', :method => :put }) + end + + def test_assert_recognizes_with_hash_constraint + assert_raise(ActionController::RoutingError) do + assert_recognizes({ :controller => 'secure_articles', :action => 'index' }, 'http://test.host/secure/articles') + end + assert_recognizes({ :controller => 'secure_articles', :action => 'index' }, 'https://test.host/secure/articles') + end + + def test_assert_recognizes_with_block_constraint + assert_raise(ActionController::RoutingError) do + assert_recognizes({ :controller => 'block_articles', :action => 'index' }, 'http://test.host/block/articles') + end + assert_recognizes({ :controller => 'block_articles', :action => 'index' }, 'https://test.host/block/articles') + end + + def test_assert_routing + assert_routing('/articles', :controller => 'articles', :action => 'index') + end + + def test_assert_routing_with_defaults + assert_routing('/articles/1/edit', { :controller => 'articles', :action => 'edit', :id => '1' }, { :id => '1' }) + end + + def test_assert_routing_with_extras + assert_routing('/articles', { :controller => 'articles', :action => 'index', :page => '1' }, { }, { :page => '1' }) + end + + def test_assert_routing_with_hash_constraint + assert_raise(ActionController::RoutingError) do + assert_routing('http://test.host/secure/articles', { :controller => 'secure_articles', :action => 'index' }) + end + assert_routing('https://test.host/secure/articles', { :controller => 'secure_articles', :action => 'index' }) + end + + def test_assert_routing_with_block_constraint + assert_raise(ActionController::RoutingError) do + assert_routing('http://test.host/block/articles', { :controller => 'block_articles', :action => 'index' }) + end + assert_routing('https://test.host/block/articles', { :controller => 'block_articles', :action => 'index' }) + end + + def test_with_routing + with_routing do |routes| + routes.draw do + resources :articles, :path => 'artikel' + end + + assert_routing('/artikel', :controller => 'articles', :action => 'index') + assert_raise(ActionController::RoutingError) do + assert_routing('/articles', { :controller => 'articles', :action => 'index' }) + end + end + end +end diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 4bf7880294..1a96587836 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -187,7 +187,12 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end resources :posts, :only => [:index, :show] do - resources :comments, :except => :destroy + namespace :admin do + root :to => "index#index" + end + resources :comments, :except => :destroy do + get "views" => "comments#views", :as => :views + end end resource :past, :only => :destroy @@ -205,6 +210,14 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end + scope '/hello' do + shallow do + resources :notes do + resources :trackbacks + end + end + end + resources :threads, :shallow => true do resource :owner resources :messages do @@ -1676,6 +1689,60 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end + def test_shallow_nested_resources_within_scope + with_test_routes do + + get '/hello/notes/1/trackbacks' + assert_equal 'trackbacks#index', @response.body + assert_equal '/hello/notes/1/trackbacks', note_trackbacks_path(:note_id => 1) + + get '/hello/notes/1/edit' + assert_equal 'notes#edit', @response.body + assert_equal '/hello/notes/1/edit', edit_note_path(:id => '1') + + get '/hello/notes/1/trackbacks/new' + assert_equal 'trackbacks#new', @response.body + assert_equal '/hello/notes/1/trackbacks/new', new_note_trackback_path(:note_id => 1) + + get '/hello/trackbacks/1' + assert_equal 'trackbacks#show', @response.body + assert_equal '/hello/trackbacks/1', trackback_path(:id => '1') + + get '/hello/trackbacks/1/edit' + assert_equal 'trackbacks#edit', @response.body + assert_equal '/hello/trackbacks/1/edit', edit_trackback_path(:id => '1') + + put '/hello/trackbacks/1' + assert_equal 'trackbacks#update', @response.body + + post '/hello/notes/1/trackbacks' + assert_equal 'trackbacks#create', @response.body + + delete '/hello/trackbacks/1' + assert_equal 'trackbacks#destroy', @response.body + + get '/hello/notes' + assert_equal 'notes#index', @response.body + + post '/hello/notes' + assert_equal 'notes#create', @response.body + + get '/hello/notes/new' + assert_equal 'notes#new', @response.body + assert_equal '/hello/notes/new', new_note_path + + get '/hello/notes/1' + assert_equal 'notes#show', @response.body + assert_equal '/hello/notes/1', note_path(:id => 1) + + put '/hello/notes/1' + assert_equal 'notes#update', @response.body + + delete '/hello/notes/1' + assert_equal 'notes#destroy', @response.body + end + end + def test_custom_resource_routes_are_scoped with_test_routes do assert_equal '/customers/recent', recent_customers_path @@ -2246,6 +2313,18 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end end + def test_nested_route_in_nested_resource + get "/posts/1/comments/2/views" + assert_equal "comments#views", @response.body + assert_equal "/posts/1/comments/2/views", post_comment_views_path(:post_id => '1', :comment_id => '2') + end + + def test_root_in_deeply_nested_scope + get "/posts/1/admin" + assert_equal "admin/index#index", @response.body + assert_equal "/posts/1/admin", post_admin_root_path(:post_id => '1') + end + private def with_test_routes yield diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb index 256d0781c7..27f55fd7ab 100644 --- a/actionpack/test/dispatch/session/cookie_store_test.rb +++ b/actionpack/test/dispatch/session/cookie_store_test.rb @@ -194,7 +194,6 @@ class CookieStoreTest < ActionDispatch::IntegrationTest with_test_route_set do get '/set_session_value' assert_response :success - session_payload = response.body assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly", headers['Set-Cookie'] diff --git a/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb new file mode 100644 index 0000000000..5db0822f07 --- /dev/null +++ b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb @@ -0,0 +1,4 @@ +Before +<%= render :partial => "test/partial.html.erb" %> +<%= yield %> +After diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index fbcc99a17a..a1a6b5f1d0 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -54,6 +54,9 @@ class AssetTagHelperTest < ActionView::TestCase def teardown config.perform_caching = false ENV.delete('RAILS_ASSET_ID') + + JavascriptIncludeTag.expansions.clear + StylesheetIncludeTag.expansions.clear end AutoDiscoveryToTag = { @@ -92,6 +95,7 @@ class AssetTagHelperTest < ActionView::TestCase %(javascript_include_tag(:all)) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), %(javascript_include_tag(:all, :recursive => true)) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/subdir/subdir.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), %(javascript_include_tag(:defaults, "bank")) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), + %(javascript_include_tag(:defaults, "application")) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), %(javascript_include_tag("bank", :defaults)) => %(<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), %(javascript_include_tag("http://example.com/all")) => %(<script src="http://example.com/all" type="text/javascript"></script>), @@ -262,10 +266,40 @@ class AssetTagHelperTest < ActionView::TestCase assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>), javascript_include_tag('controls', :robbery, 'effects') end + def test_custom_javascript_expansions_return_unique_set + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_javascript_expansion :defaults => %w(prototype effects dragdrop controls rails application) + assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag(:defaults) + end + def test_custom_javascript_expansions_and_defaults_puts_application_js_at_the_end ENV["RAILS_ASSET_ID"] = "" ActionView::Helpers::AssetTagHelper::register_javascript_expansion :robbery => ["bank", "robber"] - assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls',:defaults, :robbery, 'effects') + assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls',:defaults, :robbery, 'effects') + end + + def test_javascript_include_tag_should_not_output_the_same_asset_twice + ENV["RAILS_ASSET_ID"] = "" + assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('prototype', 'effects', :defaults) + end + + def test_javascript_include_tag_should_not_output_the_same_expansion_twice + ENV["RAILS_ASSET_ID"] = "" + assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag(:defaults, :defaults) + end + + def test_single_javascript_asset_keys_should_take_precedence_over_expansions + ENV["RAILS_ASSET_ID"] = "" + assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls', :defaults, 'effects') + assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls', 'effects', :defaults) + end + + def test_registering_javascript_expansions_merges_with_existing_expansions + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['bank'] + ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['robber'] + ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['bank'] + assert_dom_equal %(<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>), javascript_include_tag(:can_merge) end def test_custom_javascript_expansions_with_undefined_symbol @@ -273,6 +307,14 @@ class AssetTagHelperTest < ActionView::TestCase assert_raise(ArgumentError) { javascript_include_tag('first', :monkey, 'last') } end + def test_custom_javascript_and_stylesheet_expansion_with_same_name + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_javascript_expansion :robbery => ["bank", "robber"] + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :robbery => ["money", "security"] + assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>), javascript_include_tag('controls', :robbery, 'effects') + assert_dom_equal %(<link href="/stylesheets/style.css" rel="stylesheet" type="text/css" media="screen" />\n<link href="/stylesheets/money.css" rel="stylesheet" type="text/css" media="screen" />\n<link href="/stylesheets/security.css" rel="stylesheet" type="text/css" media="screen" />\n<link href="/stylesheets/print.css" rel="stylesheet" type="text/css" media="screen" />), stylesheet_link_tag('style', :robbery, 'print') + end + def test_reset_javascript_expansions JavascriptIncludeTag.expansions.clear assert_raise(ArgumentError) { javascript_include_tag(:defaults) } @@ -314,11 +356,42 @@ class AssetTagHelperTest < ActionView::TestCase assert_dom_equal %(<link href="/stylesheets/version.1.0.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/bank.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/robber.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/subdir/subdir.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag('version.1.0', :robbery, 'subdir/subdir') end + def test_custom_stylesheet_expansions_return_unique_set + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london) + assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/london.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag(:cities) + end + + def test_stylesheet_link_tag_should_not_output_the_same_asset_twice + ENV["RAILS_ASSET_ID"] = "" + assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag('wellington', 'wellington', 'amsterdam') + end + + def test_stylesheet_link_tag_should_not_output_the_same_expansion_twice + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london) + assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/london.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag(:cities, :cities) + end + + def test_single_stylesheet_asset_keys_should_take_precedence_over_expansions + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london) + assert_dom_equal %(<link href="/stylesheets/london.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag('london', :cities) + end + def test_custom_stylesheet_expansions_with_undefined_symbol ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :monkey => nil assert_raise(ArgumentError) { stylesheet_link_tag('first', :monkey, 'last') } end + def test_registering_stylesheet_expansions_merges_with_existing_expansions + ENV["RAILS_ASSET_ID"] = "" + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['bank'] + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['robber'] + ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['bank'] + assert_dom_equal %(<link href="/stylesheets/bank.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/robber.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag(:can_merge) + end + def test_image_path ImagePathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } end diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb index 55c384e68f..3334f4ffb0 100644 --- a/actionpack/test/template/date_helper_test.rb +++ b/actionpack/test/template/date_helper_test.rb @@ -2700,6 +2700,32 @@ class DateHelperTest < ActionView::TestCase assert time_select("post", "written_on", :ignore_date => true).html_safe? end + def test_time_tag_with_date + date = Date.today + expected = "<time datetime=\"#{date.rfc3339}\">#{I18n.l(date, :format => :long)}</time>" + assert_equal expected, time_tag(date) + end + + def test_time_tag_with_time + time = Time.now + expected = "<time datetime=\"#{time.xmlschema}\">#{I18n.l(time, :format => :long)}</time>" + assert_equal expected, time_tag(time) + end + + def test_time_tag_pubdate_option + assert_match /<time.*pubdate="pubdate">.*<\/time>/, time_tag(Time.now, :pubdate => true) + end + + def test_time_tag_with_given_text + assert_match /<time.*>Right now<\/time>/, time_tag(Time.now, 'Right now') + end + + def test_time_tag_with_different_format + time = Time.now + expected = "<time datetime=\"#{time.xmlschema}\">#{I18n.l(time, :format => :short)}</time>" + assert_equal expected, time_tag(time, :format => :short) + end + protected def with_env_tz(new_tz = 'US/Eastern') old_tz, ENV['TZ'] = ENV['TZ'], new_tz diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index 2c60096475..31da26de7f 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -630,7 +630,7 @@ class FormHelperTest < ActionView::TestCase "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "<input name='commit' id='post_submit' type='submit' value='Create post' />" + "<input name='commit' type='submit' value='Create post' />" end assert_dom_equal expected, output_buffer @@ -709,7 +709,7 @@ class FormHelperTest < ActionView::TestCase "<textarea name='other_name[body]' id='other_name_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + "<input name='other_name[secret]' value='0' type='hidden' />" + "<input name='other_name[secret]' checked='checked' id='other_name_secret' value='1' type='checkbox' />" + - "<input name='commit' id='other_name_submit' value='Create post' type='submit' />" + "<input name='commit' value='Create post' type='submit' />" end assert_dom_equal expected, output_buffer @@ -731,7 +731,7 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end - + def test_form_for_with_search_field # Test case for bug which would emit an "object" attribute # when used with form_for using a search_field form helper @@ -843,7 +843,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts', 'new_post', 'new_post') do - "<input name='commit' id='post_submit' type='submit' value='Create Post' />" + "<input name='commit' type='submit' value='Create Post' />" end assert_dom_equal expected, output_buffer @@ -859,7 +859,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do - "<input name='commit' id='post_submit' type='submit' value='Confirm Post changes' />" + "<input name='commit' type='submit' value='Confirm Post changes' />" end assert_dom_equal expected, output_buffer @@ -875,7 +875,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form do - "<input name='commit' class='extra' id='post_submit' type='submit' value='Save changes' />" + "<input name='commit' class='extra' type='submit' value='Save changes' />" end assert_dom_equal expected, output_buffer @@ -891,7 +891,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'another_post_edit', 'another_post_edit', :method => 'put') do - "<input name='commit' id='another_post_submit' type='submit' value='Update your Post' />" + "<input name='commit' type='submit' value='Update your Post' />" end assert_dom_equal expected, output_buffer @@ -1084,6 +1084,25 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association_using_erb_and_inline_block + @post.author = Author.new(321) + + form_for(@post) do |f| + concat f.text_field(:title) + concat f.fields_for(:author) { |af| + af.text_field(:name) + } + end + + expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do + '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + + '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + end + + assert_dom_equal expected, output_buffer + end + def test_nested_fields_for_with_existing_records_on_a_nested_attributes_one_to_one_association_with_explicit_hidden_field_placement @post.author = Author.new(321) @@ -1127,6 +1146,29 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_using_erb_and_inline_block + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + + form_for(@post) do |f| + concat f.text_field(:title) + @post.comments.each do |comment| + concat f.fields_for(:comments, comment) { |cf| + cf.text_field(:name) + } + end + end + + expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do + '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + + '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' + end + + assert_dom_equal expected, output_buffer + end + def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_explicit_hidden_field_placement @post.comments = Array.new(2) { |id| Comment.new(id + 1) } diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb index bc04398afa..69b1d4ff7b 100644 --- a/actionpack/test/template/form_options_helper_test.rb +++ b/actionpack/test/template/form_options_helper_test.rb @@ -7,7 +7,7 @@ class FormOptionsHelperTest < ActionView::TestCase tests ActionView::Helpers::FormOptionsHelper silence_warnings do - Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin) + Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin, :allow_comments) Continent = Struct.new('Continent', :continent_name, :countries) Country = Struct.new('Country', :country_id, :country_name) Firm = Struct.new('Firm', :time_zone) @@ -130,6 +130,13 @@ class FormOptionsHelperTest < ActionView::TestCase ) end + def test_boolean_array_options_for_select_with_selection_and_disabled_value + assert_dom_equal( + "<option value=\"true\">true</option>\n<option value=\"false\" selected=\"selected\">false</option>", + options_for_select([ true, false ], :selected => false, :disabled => nil) + ) + end + def test_array_options_for_string_include_in_other_string_bug_fix assert_dom_equal( "<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>", @@ -177,7 +184,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_value_as_string_and_option_value_is_integer - albums = [ Album.new(1, "first","rap"), Album.new(2, "second","pop")] + albums = [ Album.new(1, "first","rap"), Album.new(2, "second","pop")] assert_dom_equal( %(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>), options_from_collection_for_select(albums, "id", "genre", :selected => "1") @@ -185,7 +192,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_value_as_integer_and_option_value_is_string - albums = [ Album.new("1", "first","rap"), Album.new("2", "second","pop")] + albums = [ Album.new("1", "first","rap"), Album.new("2", "second","pop")] assert_dom_equal( %(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>), @@ -194,7 +201,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_value_as_string_and_option_value_is_float - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] assert_dom_equal( %(<option value="1.0">rap</option>\n<option value="2.0" selected="selected">pop</option>), @@ -203,7 +210,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_value_as_nil - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] assert_dom_equal( %(<option value="1.0">rap</option>\n<option value="2.0">pop</option>), @@ -212,7 +219,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_disabled_value_as_nil - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] assert_dom_equal( %(<option value="1.0">rap</option>\n<option value="2.0">pop</option>), @@ -221,7 +228,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_disabled_value_as_array - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] assert_dom_equal( %(<option disabled="disabled" value="1.0">rap</option>\n<option disabled="disabled" value="2.0">pop</option>), @@ -230,7 +237,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_values_as_string_array_and_option_value_is_float - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop"), Album.new(3.0, "third","country") ] + albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop"), Album.new(3.0, "third","country") ] assert_dom_equal( %(<option value="1.0" selected="selected">rap</option>\n<option value="2.0">pop</option>\n<option value="3.0" selected="selected">country</option>), @@ -364,6 +371,15 @@ class FormOptionsHelperTest < ActionView::TestCase ) end + def test_select_with_boolean_method + @post = Post.new + @post.allow_comments = false + assert_dom_equal( + "<select id=\"post_allow_comments\" name=\"post[allow_comments]\"><option value=\"true\">true</option>\n<option value=\"false\" selected=\"selected\">false</option></select>", + select("post", "allow_comments", %w( true false )) + ) + end + def test_select_under_fields_for @post = Post.new @post.category = "<mus>" diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index f3933a25b9..f8671f2980 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -385,6 +385,57 @@ class FormTagHelperTest < ActionView::TestCase ) end + def test_button_tag + assert_dom_equal( + %(<button name="button" type="submit">Button</button>), + button_tag + ) + end + + def test_button_tag_with_submit_type + assert_dom_equal( + %(<button name="button" type="submit">Save</button>), + button_tag("Save", :type => "submit") + ) + end + + def test_button_tag_with_button_type + assert_dom_equal( + %(<button name="button" type="button">Button</button>), + button_tag("Button", :type => "button") + ) + end + + def test_button_tag_with_reset_type + assert_dom_equal( + %(<button name="button" type="reset">Reset</button>), + button_tag("Reset", :type => "reset") + ) + end + + def test_button_tag_with_disabled_option + assert_dom_equal( + %(<button name="button" type="reset" disabled="disabled">Reset</button>), + button_tag("Reset", :type => "reset", :disabled => true) + ) + end + + def test_button_tag_escape_content + assert_dom_equal( + %(<button name="button" type="reset" disabled="disabled"><b>Reset</b></button>), + button_tag("<b>Reset</b>", :type => "reset", :disabled => true) + ) + end + + def test_button_tag_with_block + assert_dom_equal('<button name="button" type="submit">Content</button>', button_tag { 'Content' }) + end + + def test_button_tag_with_block_and_options + output = button_tag(:name => 'temptation', :type => 'button') { content_tag(:strong, 'Do not press me') } + assert_dom_equal('<button name="temptation" type="button"><strong>Do not press me</strong></button>', output) + end + def test_image_submit_tag_with_confirmation assert_dom_equal( %(<input type="image" src="/images/save.gif" data-confirm="Are you sure?" />), diff --git a/actionpack/test/template/html-scanner/sanitizer_test.rb b/actionpack/test/template/html-scanner/sanitizer_test.rb index 3e80317b30..fcc3782f04 100644 --- a/actionpack/test/template/html-scanner/sanitizer_test.rb +++ b/actionpack/test/template/html-scanner/sanitizer_test.rb @@ -130,6 +130,13 @@ class SanitizerTest < ActionController::TestCase assert sanitizer.send(:contains_bad_protocols?, 'src', "#{proto}://bad") end end + + def test_should_accept_good_protocols_ignoring_case + sanitizer = HTML::WhiteListSanitizer.new + HTML::WhiteListSanitizer.allowed_protocols.each do |proto| + assert !sanitizer.send(:contains_bad_protocols?, 'src', "#{proto.capitalize}://good") + end + end def test_should_accept_good_protocols sanitizer = HTML::WhiteListSanitizer.new diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb index 435936b19f..8b8b005a1d 100644 --- a/actionpack/test/template/log_subscriber_test.rb +++ b/actionpack/test/template/log_subscriber_test.rb @@ -57,7 +57,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase end def test_render_partial_with_implicit_path - @view.stubs(:controller_prefix).returns("test") + @view.stubs(:controller_prefixes).returns(%w(test)) @view.render(Customer.new("david"), :greeting => "hi") wait @@ -74,7 +74,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase end def test_render_collection_with_implicit_path - @view.stubs(:controller_prefix).returns("test") + @view.stubs(:controller_prefixes).returns(%w(test)) @view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi") wait @@ -83,7 +83,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase end def test_render_collection_template_without_path - @view.stubs(:controller_prefix).returns("test") + @view.stubs(:controller_prefixes).returns(%w(test)) @view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi") wait diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb index c9dd27cf2a..8d063e66b0 100644 --- a/actionpack/test/template/lookup_context_test.rb +++ b/actionpack/test/template/lookup_context_test.rb @@ -47,7 +47,7 @@ class LookupContextTest < ActiveSupport::TestCase end test "handles */* formats" do - @lookup_context.formats = [:"*/*"] + @lookup_context.formats = ["*/*"] assert_equal Mime::SET, @lookup_context.formats end @@ -73,25 +73,25 @@ class LookupContextTest < ActiveSupport::TestCase assert_equal :pt, I18n.locale assert_equal :pt, @lookup_context.locale ensure - I18n.config = I18n.config.i18n_config + I18n.config = I18n.config.original_config end assert_equal :pt, I18n.locale end test "find templates using the given view paths and configured details" do - template = @lookup_context.find("hello_world", "test") + template = @lookup_context.find("hello_world", %w(test)) assert_equal "Hello world!", template.source @lookup_context.locale = :da - template = @lookup_context.find("hello_world", "test") + template = @lookup_context.find("hello_world", %w(test)) assert_equal "Hey verden", template.source end test "found templates respects given formats if one cannot be found from template or handler" do ActionView::Template::Handlers::ERB.expects(:default_format).returns(nil) @lookup_context.formats = [:text] - template = @lookup_context.find("hello_world", "test") + template = @lookup_context.find("hello_world", %w(test)) assert_equal [:text], template.formats end @@ -137,44 +137,44 @@ class LookupContextTest < ActiveSupport::TestCase test "gives the key forward to the resolver, so it can be used as cache key" do @lookup_context.view_paths = ActionView::FixtureResolver.new("test/_foo.erb" => "Foo") - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source # Now we are going to change the template, but it won't change the returned template # since we will hit the cache. @lookup_context.view_paths.first.hash["test/_foo.erb"] = "Bar" - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source # This time we will change the locale. The updated template should be picked since # lookup_context generated a new key after we changed the locale. @lookup_context.locale = :da - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Bar", template.source # Now we will change back the locale and it will still pick the old template. # This is expected because lookup_context will reuse the previous key for :en locale. @lookup_context.locale = :en - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source # Finally, we can expire the cache. And the expected template will be used. @lookup_context.view_paths.first.clear_cache - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Bar", template.source end test "can disable the cache on demand" do @lookup_context.view_paths = ActionView::FixtureResolver.new("test/_foo.erb" => "Foo") - old_template = @lookup_context.find("foo", "test", true) + old_template = @lookup_context.find("foo", %w(test), true) - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal template, old_template assert @lookup_context.cache template = @lookup_context.disable_cache do assert !@lookup_context.cache - @lookup_context.find("foo", "test", true) + @lookup_context.find("foo", %w(test), true) end assert @lookup_context.cache @@ -182,11 +182,11 @@ class LookupContextTest < ActiveSupport::TestCase end test "data can be stored in cached templates" do - template = @lookup_context.find("hello_world", "test") + template = @lookup_context.find("hello_world", %w(test)) template.data["cached"] = "data" assert_equal "Hello world!", template.source - template = @lookup_context.find("hello_world", "test") + template = @lookup_context.find("hello_world", %w(test)) assert_equal "data", template.data["cached"] assert_equal "Hello world!", template.source end @@ -200,54 +200,74 @@ class LookupContextWithFalseCaching < ActiveSupport::TestCase end test "templates are always found in the resolver but timestamp is checked before being compiled" do - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source # Now we are going to change the template, but it won't change the returned template # since the timestamp is the same. @resolver.hash["test/_foo.erb"][0] = "Bar" - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source # Now update the timestamp. @resolver.hash["test/_foo.erb"][1] = Time.now.utc - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Bar", template.source end test "if no template was found in the second lookup, with no cache, raise error" do - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source @resolver.hash.clear assert_raise ActionView::MissingTemplate do - @lookup_context.find("foo", "test", true) + @lookup_context.find("foo", %w(test), true) end end test "if no template was cached in the first lookup, retrieval should work in the second call" do @resolver.hash.clear assert_raise ActionView::MissingTemplate do - @lookup_context.find("foo", "test", true) + @lookup_context.find("foo", %w(test), true) end @resolver.hash["test/_foo.erb"] = ["Foo", Time.utc(2000)] - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "Foo", template.source end test "data can be stored as long as template was not updated" do - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) template.data["cached"] = "data" assert_equal "Foo", template.source - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_equal "data", template.data["cached"] assert_equal "Foo", template.source @resolver.hash["test/_foo.erb"][1] = Time.now.utc - template = @lookup_context.find("foo", "test", true) + template = @lookup_context.find("foo", %w(test), true) assert_nil template.data["cached"] assert_equal "Foo", template.source end -end
\ No newline at end of file +end + +class TestMissingTemplate < ActiveSupport::TestCase + def setup + @lookup_context = ActionView::LookupContext.new("/Path/to/views", {}) + end + + test "if no template was found we get a helpful error message including the inheritance chain" do + e = assert_raise ActionView::MissingTemplate do + @lookup_context.find("foo", %w(parent child)) + end + assert_match %r{Missing template parent/foo, child/foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message + end + + test "if no partial was found we get a helpful error message including the inheritance chain" do + e = assert_raise ActionView::MissingTemplate do + @lookup_context.find("foo", %w(parent child), true) + end + assert_match %r{Missing partial parent/foo, child/foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message + end +end diff --git a/actionpack/test/template/output_safety_helper_test.rb b/actionpack/test/template/output_safety_helper_test.rb new file mode 100644 index 0000000000..fc127c24e9 --- /dev/null +++ b/actionpack/test/template/output_safety_helper_test.rb @@ -0,0 +1,30 @@ +require 'abstract_unit' +require 'testing_sandbox' + +class OutputSafetyHelperTest < ActionView::TestCase + tests ActionView::Helpers::OutputSafetyHelper + include TestingSandbox + + def setup + @string = "hello" + end + + test "raw returns the safe string" do + result = raw(@string) + assert_equal @string, result + assert result.html_safe? + end + + test "raw handles nil values correctly" do + assert_equal "", raw(nil) + end + + test "safe_join should html_escape any items, including the separator, if they are not html_safe" do + joined = safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />") + assert_equal "<p>foo</p><br /><p>bar</p>", joined + + joined = safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe) + assert_equal "<p>foo</p><br /><p>bar</p>", joined + end + +end
\ No newline at end of file diff --git a/actionpack/test/template/raw_output_helper_test.rb b/actionpack/test/template/raw_output_helper_test.rb deleted file mode 100644 index 598aa5b1d8..0000000000 --- a/actionpack/test/template/raw_output_helper_test.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'abstract_unit' -require 'testing_sandbox' - -class RawOutputHelperTest < ActionView::TestCase - tests ActionView::Helpers::RawOutputHelper - include TestingSandbox - - def setup - @string = "hello" - end - - test "raw returns the safe string" do - result = raw(@string) - assert_equal @string, result - assert result.html_safe? - end - - test "raw handles nil values correctly" do - assert_equal "", raw(nil) - end -end
\ No newline at end of file diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index 38bedd2e4e..034fb6c210 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -146,7 +146,12 @@ module RenderTestCases assert_equal "Hello: davidHello: mary", @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ]) end - def test_render_partial_collection_as + def test_render_partial_collection_as_by_string + assert_equal "david david davidmary mary mary", + @view.render(:partial => "test/customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => 'customer') + end + + def test_render_partial_collection_as_by_symbol assert_equal "david david davidmary mary mary", @view.render(:partial => "test/customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :customer) end @@ -204,6 +209,11 @@ module RenderTestCases @view.formats = nil end + def test_render_layout_with_block_and_other_partial_inside + render = @view.render(:layout => "test/layout_with_partial_and_yield.html.erb") { "Yield!" } + assert_equal "Before\npartial html\nYield!\nAfter\n", render + end + def test_render_inline assert_equal "Hello, World!", @view.render(:inline => "Hello, World!") end diff --git a/actionpack/test/template/template_error_test.rb b/actionpack/test/template/template_error_test.rb new file mode 100644 index 0000000000..3a874082d9 --- /dev/null +++ b/actionpack/test/template/template_error_test.rb @@ -0,0 +1,13 @@ +require "abstract_unit" + +class TemplateErrorTest < ActiveSupport::TestCase + def test_provides_original_message + error = ActionView::Template::Error.new("test", {}, Exception.new("original")) + assert_equal "original", error.message + end + + def test_provides_useful_inspect + error = ActionView::Template::Error.new("test", {}, Exception.new("original")) + assert_equal "#<ActionView::Template::Error: original>", error.inspect + end +end diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb index 2ec640c84c..3432a02c3c 100644 --- a/actionpack/test/template/template_test.rb +++ b/actionpack/test/template/template_test.rb @@ -95,14 +95,14 @@ class TestERBTemplate < ActiveSupport::TestCase def test_refresh_with_templates @template = new_template("Hello", :virtual_path => "test/foo/bar") @template.locals = [:key] - @context.lookup_context.expects(:find_template).with("bar", "test/foo", false, [:key]).returns("template") + @context.lookup_context.expects(:find_template).with("bar", %w(test/foo), false, [:key]).returns("template") assert_equal "template", @template.refresh(@context) end def test_refresh_with_partials @template = new_template("Hello", :virtual_path => "test/_foo") @template.locals = [:key] - @context.lookup_context.expects(:find_template).with("foo", "test", true, [:key]).returns("partial") + @context.lookup_context.expects(:find_template).with("foo", %w(test), true, [:key]).returns("partial") assert_equal "partial", @template.refresh(@context) end diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb index a745999622..11c355dc6d 100644 --- a/actionpack/test/template/test_case_test.rb +++ b/actionpack/test/template/test_case_test.rb @@ -116,6 +116,27 @@ module ActionView end end + class ControllerHelperMethod < ActionView::TestCase + module SomeHelper + def some_method + render :partial => 'test/from_helper' + end + end + + helper SomeHelper + + test "can call a helper method defined on the current controller from a helper" do + @controller.singleton_class.class_eval <<-EOF, __FILE__, __LINE__ + 1 + def render_from_helper + 'controller_helper_method' + end + EOF + @controller.class.helper_method :render_from_helper + + assert_equal 'controller_helper_method', some_method + end + end + class AssignsTest < ActionView::TestCase setup do ActiveSupport::Deprecation.stubs(:warn) @@ -146,7 +167,7 @@ module ActionView end end end - + class HelperExposureTest < ActionView::TestCase helper(Module.new do def render_from_helper diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index 9e9ed9120d..d0d4286393 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -1,4 +1,4 @@ -# encoding: us-ascii +# encoding: utf-8 require 'abstract_unit' require 'testing_sandbox' @@ -415,6 +415,12 @@ class TextHelperTest < ActionView::TestCase link10_raw = 'http://www.mail-archive.com/ruby-talk@ruby-lang.org/' link10_result = generate_result(link10_raw) assert_equal %(<p>#{link10_result} Link</p>), auto_link("<p>#{link10_raw} Link</p>") + + link11_raw = 'http://asakusa.rubyist.net/' + link11_result = generate_result(link11_raw) + with_kcode 'u' do + assert_equal %(浅草.rbの公式サイトはこちら#{link11_result}), auto_link("浅草.rbの公式サイトはこちら#{link11_raw}") + end end def test_auto_link_should_sanitize_input_when_sanitize_option_is_not_false diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index 4a8cea36d4..fc330f7a73 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -20,6 +20,7 @@ class UrlHelperTest < ActiveSupport::TestCase include routes.url_helpers include ActionView::Helpers::UrlHelper + include ActionView::Helpers::JavaScriptHelper include ActionDispatch::Assertions::DomAssertions include ActionView::Context include RenderERBUtils @@ -50,6 +51,14 @@ class UrlHelperTest < ActiveSupport::TestCase assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com") end + def test_button_to_with_form_class + assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"custom-class\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com", :form_class => 'custom-class') + end + + def test_button_to_with_form_class_escapes + assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"<script>evil_js</script>\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com", :form_class => '<script>evil_js</script>') + end + def test_button_to_with_query assert_dom_equal "<form method=\"post\" action=\"http://www.example.com/q1=v1&q2=v2\" class=\"button_to\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com/q1=v1&q2=v2") end @@ -359,13 +368,13 @@ class UrlHelperTest < ActiveSupport::TestCase def test_mail_to_with_javascript snippet = mail_to("me@domain.com", "My email", :encode => "javascript") - assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b'))</script>", snippet + assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>", snippet assert snippet.html_safe? end def test_mail_to_with_javascript_unicode snippet = mail_to("unicode@example.com", "únicode", :encode => "javascript") - assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%75%6e%69%63%6f%64%65%40%65%78%61%6d%70%6c%65%2e%63%6f%6d%22%3e%c3%ba%6e%69%63%6f%64%65%3c%2f%61%3e%27%29%3b'))</script>", snippet + assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%75%6e%69%63%6f%64%65%40%65%78%61%6d%70%6c%65%2e%63%6f%6d%5c%22%3e%c3%ba%6e%69%63%6f%64%65%3c%5c%2f%61%3e%27%29%3b'))</script>", snippet assert snippet.html_safe end @@ -391,8 +400,8 @@ class UrlHelperTest < ActiveSupport::TestCase assert_dom_equal "<a href=\"mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d\">me(at)domain.com</a>", mail_to("me@domain.com", nil, :encode => "hex", :replace_at => "(at)") assert_dom_equal "<a href=\"mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d\">My email</a>", mail_to("me@domain.com", "My email", :encode => "hex", :replace_at => "(at)") assert_dom_equal "<a href=\"mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d\">me(at)domain(dot)com</a>", mail_to("me@domain.com", nil, :encode => "hex", :replace_at => "(at)", :replace_dot => "(dot)") - assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", "My email", :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)") - assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", nil, :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)") + assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", "My email", :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)") + assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%5c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", nil, :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)") end # TODO: button_to looks at this ... why? |