From 1ee3593d65feacf88d2b9171dada85dbdeae65e5 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Wed, 11 Aug 2010 23:54:15 +0200 Subject: no need to assign if we are gonna return --- actionpack/lib/action_dispatch/http/cache.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb index e9fdf75cc8..047fab006e 100644 --- a/actionpack/lib/action_dispatch/http/cache.rb +++ b/actionpack/lib/action_dispatch/http/cache.rb @@ -113,10 +113,10 @@ module ActionDispatch DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate" def set_conditional_cache_control! - control = @cache_control - return if self["Cache-Control"].present? + control = @cache_control + if control.empty? headers["Cache-Control"] = DEFAULT_CACHE_CONTROL elsif @cache_control[:no_cache] -- cgit v1.2.3 From 919888503d481c3bd21a33acd3cd1018fc48f500 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 13 Aug 2010 17:34:20 -0300 Subject: Moves local_request? to require.local? [#5361 state:committed] --- actionpack/lib/action_dispatch/http/request.rb | 7 +++++++ actionpack/lib/action_dispatch/middleware/show_exceptions.rb | 9 +-------- 2 files changed, 8 insertions(+), 8 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index fd23b1df79..5606d6abfe 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -15,6 +15,8 @@ module ActionDispatch include ActionDispatch::Http::Upload include ActionDispatch::Http::URL + LOCALHOST = [/^127\.0\.0\.\d{1,3}$/, "::1", /^0:0:0:0:0:0:0:1(%.*)?$/].freeze + %w[ AUTH_TYPE GATEWAY_INTERFACE PATH_TRANSLATED REMOTE_HOST REMOTE_IDENT REMOTE_USER REMOTE_ADDR @@ -231,5 +233,10 @@ module ActionDispatch @env['X_HTTP_AUTHORIZATION'] || @env['REDIRECT_X_HTTP_AUTHORIZATION'] end + + # True if the request came from localhost, 127.0.0.1. + def local? + LOCALHOST.any? { |local_ip| local_ip === remote_addr && local_ip === remote_ip } + end end end diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index e095b51342..a7d3cb473f 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -6,8 +6,6 @@ module ActionDispatch # This middleware rescues any exception returned by the application and renders # nice exception pages if it's being rescued locally. class ShowExceptions - LOCALHOST = [/^127\.0\.0\.\d{1,3}$/, "::1", /^0:0:0:0:0:0:0:1(%.*)?$/].freeze - RESCUES_TEMPLATE_PATH = File.join(File.dirname(__FILE__), 'templates') cattr_accessor :rescue_responses @@ -66,7 +64,7 @@ module ActionDispatch log_error(exception) request = Request.new(env) - if @consider_all_requests_local || local_request?(request) + if @consider_all_requests_local || request.local? rescue_action_locally(request, exception) else rescue_action_in_public(exception) @@ -112,11 +110,6 @@ module ActionDispatch end end - # True if the request came from localhost, 127.0.0.1. - def local_request?(request) - LOCALHOST.any? { |local_ip| local_ip === request.remote_addr && local_ip === request.remote_ip } - end - def status_code(exception) Rack::Utils.status_code(@@rescue_responses[exception.class.name]) end -- cgit v1.2.3 From b451de0d6de4df6bc66b274cec73b919f823d5ae Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 14 Aug 2010 02:13:00 -0300 Subject: Deletes trailing whitespaces (over text files only find * -type f -exec sed 's/[ \t]*$//' -i {} \;) --- actionpack/lib/action_dispatch/http/mime_type.rb | 20 ++++++++++---------- actionpack/lib/action_dispatch/middleware/stack.rb | 2 +- actionpack/lib/action_dispatch/routing.rb | 8 ++++---- 3 files changed, 15 insertions(+), 15 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index c6fc582851..8f1c9b6691 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -109,10 +109,10 @@ module Mime else # keep track of creation order to keep the subsequent sort stable list = [] - accept_header.split(/,/).each_with_index do |header, index| - params, q = header.split(/;\s*q=/) + accept_header.split(/,/).each_with_index do |header, index| + params, q = header.split(/;\s*q=/) if params - params.strip! + params.strip! list << AcceptItem.new(index, params, q) unless params.empty? end end @@ -161,20 +161,20 @@ module Mime end end end - + def initialize(string, symbol = nil, synonyms = []) @symbol, @synonyms = symbol, synonyms @string = string end - + def to_s @string end - + def to_str to_s end - + def to_sym @symbol || @string.to_sym end @@ -186,11 +186,11 @@ module Mime super end end - + def ==(mime_type) return false if mime_type.blank? - (@synonyms + [ self ]).any? do |synonym| - synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym + (@synonyms + [ self ]).any? do |synonym| + synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym end end diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 41078eced7..5a029a60d1 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -69,7 +69,7 @@ module ActionDispatch end def active - ActiveSupport::Deprecation.warn "All middlewares in the chain are active since the laziness " << + ActiveSupport::Deprecation.warn "All middlewares in the chain are active since the laziness " << "was removed from the middleware stack", caller end diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index 683dd72555..df1b53016d 100644 --- a/actionpack/lib/action_dispatch/routing.rb +++ b/actionpack/lib/action_dispatch/routing.rb @@ -15,7 +15,7 @@ module ActionDispatch # match ':controller(/:action(/:id(.:format)))' # # This route states that it expects requests to consist of a - # :controller followed optionally by an :action that in + # :controller followed optionally by an :action that in # turn is followed optionally by an :id, which in turn is followed # optionally by a :format # @@ -134,8 +134,8 @@ module ActionDispatch # == HTTP Methods # # Using the :via option when specifying a route allows you to restrict it to a specific HTTP method. - # Possible values are :post, :get, :put, :delete and :any. - # If your route needs to respond to more than one method you can use an array, e.g. [ :get, :post ]. + # Possible values are :post, :get, :put, :delete and :any. + # If your route needs to respond to more than one method you can use an array, e.g. [ :get, :post ]. # The default value is :any which means that the route will respond to any of the HTTP methods. # # Examples: @@ -144,7 +144,7 @@ module ActionDispatch # match 'post/:id' => "posts#create_comment', :via => :post # # Now, if you POST to /posts/:id, it will route to the create_comment action. A GET on the same - # URL will route to the show action. + # URL will route to the show action. # # === HTTP helper methods # -- cgit v1.2.3 From fd78bb727045547371179428886c9b262d66091d Mon Sep 17 00:00:00 2001 From: Bryce Thornton Date: Sat, 14 Aug 2010 15:35:01 -0400 Subject: Allow for any possible TLD when using the :all option with the cookie session store. This works for subdomain.mysite.local, google.co.uk, google.com.au, etc. [#5147 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- .../lib/action_dispatch/middleware/cookies.rb | 26 +++++++++++++++------- 1 file changed, 18 insertions(+), 8 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index 4d33cd3b0c..c281e323e5 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -69,16 +69,26 @@ module ActionDispatch class CookieJar < Hash #:nodoc: - # This regular expression is used to split the levels of a domain - # So www.example.co.uk gives: - # $1 => www. - # $2 => example - # $3 => co.uk - DOMAIN_REGEXP = /^(.*\.)*(.*)\.(...|...\...|....|..\...|..)$/ + # This regular expression is used to split the levels of a domain. + # The top level domain can be any string without a period or + # **.**, ***.** style TLDs like co.uk or com.au + # + # www.example.co.uk gives: + # $1 => example + # $2 => co.uk + # + # example.com gives: + # $1 => example + # $2 => com + # + # lots.of.subdomains.example.local gives: + # $1 => example + # $2 => local + DOMAIN_REGEXP = /([^.]*)\.([^.]*|..\...|...\...)$/ def self.build(request) secret = request.env[TOKEN_KEY] - host = request.env["HTTP_HOST"] + host = request.host new(secret, host).tap do |hash| hash.update(request.cookies) @@ -104,7 +114,7 @@ module ActionDispatch if options[:domain] == :all @host =~ DOMAIN_REGEXP - options[:domain] = ".#{$2}.#{$3}" + options[:domain] = ".#{$1}.#{$2}" end end -- cgit v1.2.3 From 6e41cfb4e997842dd165b7c8cd2c0f3dc78c6af2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 16 Aug 2010 14:08:59 -0300 Subject: annoted_source_code may return nil if an error happens during template compiling. --- actionpack/lib/action_dispatch/middleware/show_exceptions.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index a7d3cb473f..ef0c9c51f5 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -127,7 +127,7 @@ module ActionDispatch ActiveSupport::Deprecation.silence do message = "\n#{exception.class} (#{exception.message}):\n" - message << exception.annoted_source_code if exception.respond_to?(:annoted_source_code) + message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code) message << " " << application_trace(exception).join("\n ") logger.fatal("#{message}\n\n") end -- cgit v1.2.3 From fca617af143dd8598502bdbaa617e7fe124d595e Mon Sep 17 00:00:00 2001 From: Andre Arko Date: Wed, 18 Aug 2010 07:31:52 +0800 Subject: Allow member actions (get, etc) to accept strings, with test --- actionpack/lib/action_dispatch/routing/mapper.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index c118c72440..c27f06c686 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -731,6 +731,7 @@ module ActionDispatch end elsif resource_method_scope? path = path_for_custom_action + options[:action] ||= action options[:as] = name_for_action(options[:as]) if options[:as] args.push(options) -- cgit v1.2.3 From 3e871eee8048c0e11e270ae4fbcbe40226148c33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Mart=C3=ADn?= Date: Wed, 18 Aug 2010 13:35:05 +0100 Subject: Don't pluralize resource methods [#4704 state:resolved] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/routing/mapper.rb | 28 ++++++++++++------------ 1 file changed, 14 insertions(+), 14 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index c27f06c686..c6bbfdb441 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -498,16 +498,14 @@ module ActionDispatch end def plural - name.to_s.pluralize + @plural ||= name.to_s end def singular - name.to_s.singularize + @singular ||= name.to_s.singularize end - def member_name - singular - end + alias :member_name :singular # Checks for uncountable plurals, and appends "_index" if they're. def collection_name @@ -518,9 +516,7 @@ module ActionDispatch { :controller => controller } end - def collection_scope - path - end + alias :collection_scope :path def member_scope "#{path}/:id" @@ -547,15 +543,19 @@ module ActionDispatch @options = options end - def member_name - name + def plural + @plural ||= name.to_s.pluralize end - alias :collection_name :member_name - def member_scope - path + def singular + @singular ||= name.to_s end - alias :nested_scope :member_scope + + alias :member_name :singular + alias :collection_name :singular + + alias :member_scope :path + alias :nested_scope :path end def initialize(*args) #:nodoc: -- cgit v1.2.3 From 0cc483aa14d79b2d07fdc71dbd935d1af8361d71 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Thu, 19 Aug 2010 14:42:14 +0100 Subject: Move edit route before show route so that it will have precedence if the :id parameter allows slashes [#5409 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/routing/mapper.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index c6bbfdb441..26ca2ca818 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -586,10 +586,10 @@ module ActionDispatch end if parent_resource.actions.include?(:new) member_scope do + get :edit if parent_resource.actions.include?(:edit) get :show if parent_resource.actions.include?(:show) put :update if parent_resource.actions.include?(:update) delete :destroy if parent_resource.actions.include?(:destroy) - get :edit if parent_resource.actions.include?(:edit) end end @@ -616,10 +616,10 @@ module ActionDispatch end if parent_resource.actions.include?(:new) member_scope do + get :edit if parent_resource.actions.include?(:edit) get :show if parent_resource.actions.include?(:show) put :update if parent_resource.actions.include?(:update) delete :destroy if parent_resource.actions.include?(:destroy) - get :edit if parent_resource.actions.include?(:edit) end end -- cgit v1.2.3 From c019db8ca1c5639fdae80915cc7520eaad7dcd65 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Wed, 18 Aug 2010 11:50:15 +0100 Subject: Move regexps in options hash to :constraints hash so that they are pushed into the scope [#5208 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/routing/mapper.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 26ca2ca818..b9e097e5d1 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -774,6 +774,10 @@ module ActionDispatch return true end + options.each do |k,v| + (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp) + end + scope_options = options.slice!(*RESOURCE_OPTIONS) unless scope_options.empty? scope(scope_options) do -- cgit v1.2.3 From 771d2f918fc87bdd4f83e6666fd816e9f0dcedfb Mon Sep 17 00:00:00 2001 From: Andrew White Date: Fri, 20 Aug 2010 08:33:48 +0100 Subject: Allow symbols for :path resource(s) option [#5306 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/routing/mapper.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index b9e097e5d1..5c5e7ed612 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -473,7 +473,7 @@ module ActionDispatch def initialize(entities, options = {}) @name = entities.to_s - @path = options.delete(:path) || @name + @path = (options.delete(:path) || @name).to_s @controller = (options.delete(:controller) || @name).to_s @as = options.delete(:as) @options = options @@ -537,7 +537,7 @@ module ActionDispatch def initialize(entities, options) @name = entities.to_s - @path = options.delete(:path) || @name + @path = (options.delete(:path) || @name).to_s @controller = (options.delete(:controller) || plural).to_s @as = options.delete(:as) @options = options -- cgit v1.2.3 From 0d0fbf1e648606c9499e332bad412da005a4e37f Mon Sep 17 00:00:00 2001 From: Andrew White Date: Thu, 19 Aug 2010 15:29:54 +0100 Subject: Don't add the standard https port when using redirect in routes.rb and ensure that request.scheme returns https when using a reverse proxy. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [#5408 state:resolved] Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/url.rb | 10 ++++++++++ actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index b64a83c62e..ffb7bdd586 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -6,6 +6,11 @@ module ActionDispatch protocol + host_with_port + fullpath end + # Returns 'https' if this is an SSL request and 'http' otherwise. + def scheme + ssl? ? 'https' : 'http' + end + # Returns 'https://' if this is an SSL request and 'http://' otherwise. def protocol ssl? ? 'https://' : 'http://' @@ -53,6 +58,11 @@ module ActionDispatch end end + # Returns whether this request is using the standard port + def standard_port? + port == standard_port + end + # Returns a \port suffix like ":8080" if the \port number of this request # is not the default HTTP \port 80 or HTTPS \port 443. def port_string diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 5c5e7ed612..800c6b469e 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -288,7 +288,7 @@ module ActionDispatch uri = URI.parse(path_proc.call(*params)) uri.scheme ||= req.scheme uri.host ||= req.host - uri.port ||= req.port unless req.port == 80 + uri.port ||= req.port unless req.standard_port? body = %(You are being redirected.) -- cgit v1.2.3 From 7c9bf45b0dd7ad7a1d99a14566bfaeadc77b4665 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Fri, 20 Aug 2010 17:33:33 +0100 Subject: Support routing constraints in functional tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extend assert_recognizes and assert_generates to support passing full urls as the path argument. This allows testing of routing constraints such as subdomain and host within functional tests. [#5005 state:resolved] Signed-off-by: José Valim --- .../lib/action_dispatch/routing/route_set.rb | 4 +- .../action_dispatch/testing/assertions/routing.rb | 51 ++++++++++++++++------ 2 files changed, 39 insertions(+), 16 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index d23b580d97..b531cc1a8e 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -494,7 +494,7 @@ module ActionDispatch def recognize_path(path, environment = {}) method = (environment[:method] || "GET").to_s.upcase - path = Rack::Mount::Utils.normalize_path(path) + path = Rack::Mount::Utils.normalize_path(path) unless path =~ %r{://} begin env = Rack::MockRequest.env_for(path, {:method => method}) @@ -502,7 +502,7 @@ module ActionDispatch raise ActionController::RoutingError, e.message end - req = Rack::Request.new(env) + req = @request_class.new(env) @set.recognize(req) do |route, matches, params| params.each do |key, value| if value.is_a?(String) diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 9338fa9e70..5a3ffda255 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -1,3 +1,4 @@ +require 'uri' require 'active_support/core_ext/hash/diff' require 'active_support/core_ext/hash/indifferent_access' @@ -40,14 +41,7 @@ module ActionDispatch # # Check a Simply RESTful generated route # assert_recognizes list_items_url, 'items/list' def assert_recognizes(expected_options, path, extras={}, message=nil) - if path.is_a? Hash - request_method = path[:method] - path = path[:path] - else - request_method = nil - end - - request = recognized_request_for(path, request_method) + request = recognized_request_for(path) expected_options = expected_options.clone extras.each_key { |key| expected_options.delete key } unless extras.nil? @@ -77,7 +71,16 @@ module ActionDispatch # # Asserts that the generated route gives us our custom route # assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" } def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil) - expected_path = "/#{expected_path}" unless expected_path[0] == ?/ + if expected_path =~ %r{://} + begin + uri = URI.parse(expected_path) + expected_path = uri.path.to_s.empty? ? "/" : uri.path + rescue URI::InvalidURIError => e + raise ActionController::RoutingError, e.message + end + else + expected_path = "/#{expected_path}" unless expected_path.first == '/' + end # Load routes.rb if it hasn't been loaded. generated_path, extra_keys = @routes.generate_extras(options, defaults) @@ -177,15 +180,35 @@ module ActionDispatch private # Recognizes the route for a given path. - def recognized_request_for(path, request_method = nil) - path = "/#{path}" unless path.first == '/' + def recognized_request_for(path) + if path.is_a?(Hash) + method = path[:method] + path = path[:path] + else + method = :get + end # Assume given controller request = ActionController::TestRequest.new - request.env["REQUEST_METHOD"] = request_method.to_s.upcase if request_method - request.path = path - params = @routes.recognize_path(path, { :method => request.method }) + if path =~ %r{://} + begin + uri = URI.parse(path) + request.env["rack.url_scheme"] = uri.scheme || "http" + request.host = uri.host if uri.host + request.port = uri.port if uri.port + request.path = uri.path.to_s.empty? ? "/" : uri.path + rescue URI::InvalidURIError => e + raise ActionController::RoutingError, e.message + end + else + path = "/#{path}" unless path.first == "/" + request.path = path + end + + request.request_method = method if method + + params = @routes.recognize_path(path, { :method => method }) request.path_parameters = params.with_indifferent_access request -- cgit v1.2.3 From 2277c51555249cc8b0478e175bcb744841634db5 Mon Sep 17 00:00:00 2001 From: Nick Sieger Date: Fri, 20 Aug 2010 15:58:23 -0500 Subject: Fix hash modification during iteration in Mapper [#5420] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 800c6b469e..00f8fb99bb 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -774,7 +774,7 @@ module ActionDispatch return true end - options.each do |k,v| + options.keys.each do |k| (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp) end -- cgit v1.2.3 From ae2c60734a0f71593709608710a0c7507bb8699e Mon Sep 17 00:00:00 2001 From: Andrew White Date: Sun, 22 Aug 2010 18:48:26 +0100 Subject: Cache the symbolized path parameters using a instance variable in the request object rather than the environment hash. This it to prevent stale parameters in later routing constraints/redirects as only the normal path parameters are set by Rack::Mount. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also if a constraint proc arity is more than one, pass the symbolized path parameters as the first argument to match redirect proc args and provide easier access. [#5157 state:resolved] Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/parameters.rb | 4 ++-- actionpack/lib/action_dispatch/routing/mapper.rb | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb index add8cab2ab..5e1a2405f7 100644 --- a/actionpack/lib/action_dispatch/http/parameters.rb +++ b/actionpack/lib/action_dispatch/http/parameters.rb @@ -15,14 +15,14 @@ module ActionDispatch alias :params :parameters def path_parameters=(parameters) #:nodoc: - @env.delete("action_dispatch.request.symbolized_path_parameters") + @_symbolized_path_params = nil @env.delete("action_dispatch.request.parameters") @env["action_dispatch.request.path_parameters"] = parameters end # The same as path_parameters with explicitly symbolized keys. def symbolized_path_parameters - @env["action_dispatch.request.symbolized_path_parameters"] ||= path_parameters.symbolize_keys + @_symbolized_path_params ||= path_parameters.symbolize_keys end # Returns a hash with the \parameters used to form the \path of the request. diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 00f8fb99bb..23b13d1d5d 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -26,13 +26,18 @@ module ActionDispatch @constraints.each { |constraint| if constraint.respond_to?(:matches?) && !constraint.matches?(req) return [ 404, {'X-Cascade' => 'pass'}, [] ] - elsif constraint.respond_to?(:call) && !constraint.call(req) + elsif constraint.respond_to?(:call) && !constraint.call(*constraint_args(constraint, req)) return [ 404, {'X-Cascade' => 'pass'}, [] ] end } @app.call(env) end + + private + def constraint_args(constraint, request) + constraint.arity == 1 ? [request] : [request.symbolized_path_parameters, request] + end end class Mapping #:nodoc: -- cgit v1.2.3 From 2fb0cbec024c5b51451deab7e390e2d4f712cf8f Mon Sep 17 00:00:00 2001 From: Andrew White Date: Tue, 24 Aug 2010 07:27:54 +0100 Subject: When custom resource actions are specified using strings add the default name and action if the string is a valid ruby method name. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [#5431 state:resolved] Signed-off-by: José Valim --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 23b13d1d5d..0a6cd63b56 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -736,8 +736,12 @@ module ActionDispatch end elsif resource_method_scope? path = path_for_custom_action - options[:action] ||= action - options[:as] = name_for_action(options[:as]) if options[:as] + if action =~ /^[a-zA-Z][_a-zA-Z0-9]*$/ + options[:action] ||= action + options[:as] = name_for_action(action, options[:as]) + else + options[:as] = name_for_action(options[:as]) if options[:as] + end args.push(options) with_exclusive_scope do -- cgit v1.2.3 From b4f304b7b68e0b4fd780cc6d0944edefc362669d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 24 Aug 2010 10:09:06 -0300 Subject: Fix a bug where symbols and strings were not behaving the same in the router. [#5431 state:resolved] --- actionpack/lib/action_dispatch/routing/mapper.rb | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 0a6cd63b56..4dc2fc086e 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -726,22 +726,17 @@ module ActionDispatch path = options.delete(:path) action = args.first - if action.is_a?(Symbol) + if action && action.to_s =~ /^[\w_]+$/ path = path_for_action(action, path) - options[:to] ||= action - options[:as] = name_for_action(action, options[:as]) + options[:action] ||= action + options[:as] = name_for_action(action, options[:as]) with_exclusive_scope do return super(path, options) end elsif resource_method_scope? path = path_for_custom_action - if action =~ /^[a-zA-Z][_a-zA-Z0-9]*$/ - options[:action] ||= action - options[:as] = name_for_action(action, options[:as]) - else - options[:as] = name_for_action(options[:as]) if options[:as] - end + options[:as] = name_for_action(options[:as]) if options[:as] args.push(options) with_exclusive_scope do -- cgit v1.2.3 From 542878304dd53bb8bd8962c61dd9404f2ba57ec7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 24 Aug 2010 11:22:51 -0300 Subject: Ensure prefix in routes are generated properly. --- actionpack/lib/action_dispatch/routing/mapper.rb | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 4dc2fc086e..0c77183dc1 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -926,11 +926,11 @@ module ActionDispatch def prefix_name_for_action(action, as) if as.present? - "#{as}_" + as.to_s elsif as - "" + nil elsif !canonical_action?(action, @scope[:scope_level]) - "#{action}_" + action.to_s end end @@ -941,22 +941,19 @@ module ActionDispatch if parent_resource collection_name = parent_resource.collection_name member_name = parent_resource.member_name - name_prefix = "#{name_prefix}_" if name_prefix.present? end - case @scope[:scope_level] + name = case @scope[:scope_level] when :collection - "#{prefix}#{name_prefix}#{collection_name}" + [name_prefix, collection_name] when :new - "#{prefix}new_#{name_prefix}#{member_name}" + [:new, name_prefix, member_name] else - if shallow_scoping? - shallow_prefix = "#{@scope[:shallow_prefix]}_" if @scope[:shallow_prefix].present? - "#{prefix}#{shallow_prefix}#{member_name}" - else - "#{prefix}#{name_prefix}#{member_name}" - end + [shallow_scoping? ? @scope[:shallow_prefix] : name_prefix, member_name] end + + name.unshift(prefix) + name.select(&:present?).join("_") end end -- cgit v1.2.3 From 11f6179f55d38dd54b69aeeb5bee9053194f0e84 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Tue, 24 Aug 2010 15:05:26 +0100 Subject: Reset symbolized path parameters when a test request is recycled [#5437 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/parameters.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb index 5e1a2405f7..ef5d207b26 100644 --- a/actionpack/lib/action_dispatch/http/parameters.rb +++ b/actionpack/lib/action_dispatch/http/parameters.rb @@ -15,14 +15,14 @@ module ActionDispatch alias :params :parameters def path_parameters=(parameters) #:nodoc: - @_symbolized_path_params = nil + @symbolized_path_params = nil @env.delete("action_dispatch.request.parameters") @env["action_dispatch.request.path_parameters"] = parameters end # The same as path_parameters with explicitly symbolized keys. def symbolized_path_parameters - @_symbolized_path_params ||= path_parameters.symbolize_keys + @symbolized_path_params ||= path_parameters.symbolize_keys end # Returns a hash with the \parameters used to form the \path of the request. -- cgit v1.2.3 From 4df19b3f27c93e0a3091c176536fa119ea03ebb7 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Tue, 24 Aug 2010 12:43:43 -0300 Subject: Allow actions which start with A-Za-z_ only --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 0c77183dc1..76c7ec35b9 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -726,7 +726,7 @@ module ActionDispatch path = options.delete(:path) action = args.first - if action && action.to_s =~ /^[\w_]+$/ + if action && action.to_s =~ /^[A-Za-z_]\w*$/ path = path_for_action(action, path) options[:action] ||= action options[:as] = name_for_action(action, options[:as]) -- cgit v1.2.3 From 2916521da825d5a0b93eb1cb86f12946e9345e29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 24 Aug 2010 13:05:29 -0300 Subject: Fix how routes inside namespaces are generated. --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 76c7ec35b9..c83d714dbc 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -726,7 +726,7 @@ module ActionDispatch path = options.delete(:path) action = args.first - if action && action.to_s =~ /^[A-Za-z_]\w*$/ + if action.is_a?(Symbol) || (resource_method_scope? && action.to_s =~ /^[A-Za-z_]\w*$/) path = path_for_action(action, path) options[:action] ||= action options[:as] = name_for_action(action, options[:as]) -- cgit v1.2.3 From 4a90ecb3adff8426aeddee0594c2b68f408e4af1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 24 Aug 2010 14:54:23 -0300 Subject: Ensure shortcuts inside resources also generates helpers. --- actionpack/lib/action_dispatch/routing/mapper.rb | 87 +++++++++++------------- 1 file changed, 39 insertions(+), 48 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index c83d714dbc..234e34a24f 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -43,9 +43,9 @@ module ActionDispatch class Mapping #:nodoc: IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix] - def initialize(set, scope, args) - @set, @scope = set, scope - @path, @options = extract_path_and_options(args) + def initialize(set, scope, path, options) + @set, @scope, @options = set, scope, options + @path = normalize_path(path) normalize_options! end @@ -54,31 +54,16 @@ module ActionDispatch end private - def extract_path_and_options(args) - options = args.extract_options! - - if using_to_shorthand?(args, options) - path, to = options.find { |name, value| name.is_a?(String) } - options.merge!(:to => to).delete(path) if path - else - path = args.first - end - - if path.match(':controller') - raise ArgumentError, ":controller segment is not allowed within a namespace block" if @scope[:module] - - # Add a default constraint for :controller path segments that matches namespaced - # controllers with default routes like :controller/:action/:id(.:format), e.g: - # GET /admin/products/show/1 - # => { :controller => 'admin/products', :action => 'show', :id => '1' } - options.reverse_merge!(:controller => /.+?/) - end - - [ normalize_path(path), options ] - end def normalize_options! path_without_format = @path.sub(/\(\.:format\)$/, '') + @options = (@scope[:options] || {}).merge(@options) + + if @scope[:as] && !@options[:as].blank? + @options[:as] = "#{@scope[:as]}_#{@options[:as]}" + elsif @scope[:as] && @options[:as] == "" + @options[:as] = @scope[:as].to_s + end if using_match_shorthand?(path_without_format, @options) to_shorthand = @options[:to].blank? @@ -89,11 +74,6 @@ module ActionDispatch @options.merge!(default_controller_and_action(to_shorthand)) end - # match "account" => "account#index" - def using_to_shorthand?(args, options) - args.empty? && options.present? - end - # match "account/overview" def using_match_shorthand?(path, options) path && options.except(:via, :anchor, :to, :as).empty? && path =~ %r{^/[\w\/]+$} @@ -101,7 +81,19 @@ module ActionDispatch def normalize_path(path) raise ArgumentError, "path is required" if @scope[:path].blank? && path.blank? - Mapper.normalize_path("#{@scope[:path]}/#{path}") + path = Mapper.normalize_path("#{@scope[:path]}/#{path}") + + if path.match(':controller') + raise ArgumentError, ":controller segment is not allowed within a namespace block" if @scope[:module] + + # Add a default constraint for :controller path segments that matches namespaced + # controllers with default routes like :controller/:action/:id(.:format), e.g: + # GET /admin/products/show/1 + # => { :controller => 'admin/products', :action => 'show', :id => '1' } + @options.reverse_merge!(:controller => /.+?/) + end + + path end def app @@ -233,8 +225,8 @@ module ActionDispatch match '/', options.reverse_merge(:as => :root) end - def match(*args) - mapping = Mapping.new(@set, @scope, args).to_route + def match(path, options=nil) + mapping = Mapping.new(@set, @scope, path, options || {}).to_route @set.add_route(*mapping) self end @@ -389,21 +381,6 @@ module ActionDispatch scope(:defaults => defaults) { yield } end - def match(*args) - options = args.extract_options! - - options = (@scope[:options] || {}).merge(options) - - if @scope[:as] && !options[:as].blank? - options[:as] = "#{@scope[:as]}_#{options[:as]}" - elsif @scope[:as] && options[:as] == "" - options[:as] = @scope[:as].to_s - end - - args.push(options) - super(*args) - end - private def scope_options @scope_options ||= private_methods.grep(/^merge_(.+)_scope$/) { $1.to_sym } @@ -957,10 +934,24 @@ module ActionDispatch end end + module Shorthand + def match(*args) + if args.size == 1 && args.last.is_a?(Hash) + options = args.pop + path, to = options.find { |name, value| name.is_a?(String) } + options.merge!(:to => to).delete(path) + super(path, options) + else + super + end + end + end + include Base include HttpHelpers include Scoping include Resources + include Shorthand end end end -- cgit v1.2.3 From e197d6f34b72cd96ffc5c6680ed8d433f1b1c4db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 24 Aug 2010 16:42:14 -0300 Subject: Finally fix the bug where symbols and strings were not having the same behavior in the router. If you were using symbols before for methods like match/get/post/put/delete, it is likely that this commit will break your routes. Everything should behave the same if you are using strings, if not, please open up a ticket. --- actionpack/lib/action_dispatch/routing/mapper.rb | 113 +++++++++-------------- 1 file changed, 46 insertions(+), 67 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 234e34a24f..f3cbba243c 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -44,7 +44,8 @@ module ActionDispatch IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix] def initialize(set, scope, path, options) - @set, @scope, @options = set, scope, options + @set, @scope = set, scope + @options = (@scope[:options] || {}).merge(options) @path = normalize_path(path) normalize_options! end @@ -57,18 +58,11 @@ module ActionDispatch def normalize_options! path_without_format = @path.sub(/\(\.:format\)$/, '') - @options = (@scope[:options] || {}).merge(@options) - - if @scope[:as] && !@options[:as].blank? - @options[:as] = "#{@scope[:as]}_#{@options[:as]}" - elsif @scope[:as] && @options[:as] == "" - @options[:as] = @scope[:as].to_s - end if using_match_shorthand?(path_without_format, @options) to_shorthand = @options[:to].blank? @options[:to] ||= path_without_format[1..-1].sub(%r{/([^/]*)$}, '#\1') - @options[:as] ||= path_without_format[1..-1].gsub("/", "_") + @options[:as] ||= Mapper.normalize_name(path_without_format) end @options.merge!(default_controller_and_action(to_shorthand)) @@ -80,8 +74,8 @@ module ActionDispatch end def normalize_path(path) - raise ArgumentError, "path is required" if @scope[:path].blank? && path.blank? - path = Mapper.normalize_path("#{@scope[:path]}/#{path}") + raise ArgumentError, "path is required" if path.blank? + path = Mapper.normalize_path(path) if path.match(':controller') raise ArgumentError, ":controller segment is not allowed within a namespace block" if @scope[:module] @@ -93,7 +87,11 @@ module ActionDispatch @options.reverse_merge!(:controller => /.+?/) end - path + if path.include?(":format") + path + else + "#{path}(.:format)" + end end def app @@ -216,6 +214,10 @@ module ActionDispatch path end + def self.normalize_name(name) + normalize_path(name)[1..-1].gsub("/", "_") + end + module Base def initialize(set) #:nodoc: @set = set @@ -324,13 +326,7 @@ module ActionDispatch ActiveSupport::Deprecation.warn ":name_prefix was deprecated in the new router syntax. Use :as instead.", caller end - case args.first - when String - options[:path] = args.first - when Symbol - options[:controller] = args.first - end - + options[:path] = args.first if args.first.is_a?(String) recover = {} options[:constraints] ||= {} @@ -362,8 +358,9 @@ module ActionDispatch @scope[:blocks] = recover[:block] end - def controller(controller) - scope(controller.to_sym) { yield } + def controller(controller, options={}) + options[:controller] = controller + scope(options) { yield } end def namespace(path, options = {}) @@ -444,9 +441,9 @@ module ActionDispatch 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. - VALID_ON_OPTIONS = [:new, :collection, :member] - CANONICAL_ACTIONS = [:index, :create, :new, :show, :update, :destroy] - RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except] + VALID_ON_OPTIONS = [:new, :collection, :member] + RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except] + CANONICAL_ACTIONS = %w(index create new show update destroy) class Resource #:nodoc: DEFAULT_ACTIONS = [:index, :create, :new, :show, :update, :destroy, :edit] @@ -700,41 +697,27 @@ module ActionDispatch return member { match(*args) } end - path = options.delete(:path) + if resource_scope? + raise ArgumentError, "can't define route directly in resource(s) scope" + end + action = args.first + path = path_for_action(action, options.delete(:path)) - if action.is_a?(Symbol) || (resource_method_scope? && action.to_s =~ /^[A-Za-z_]\w*$/) - path = path_for_action(action, path) - options[:action] ||= action + if action.to_s =~ /^[\w\/]+$/ + options[:action] ||= action unless action.to_s.include?("/") options[:as] = name_for_action(action, options[:as]) - - with_exclusive_scope do - return super(path, options) - end - elsif resource_method_scope? - path = path_for_custom_action - options[:as] = name_for_action(options[:as]) if options[:as] - args.push(options) - - with_exclusive_scope do - scope(path) do - return super - end - end - end - - if resource_scope? - raise ArgumentError, "can't define route directly in resource(s) scope" + else + options[:as] = name_for_action(options[:as]) end - args.push(options) - super + super(path, options) end def root(options={}) if @scope[:scope_level] == :resources - with_scope_level(:nested) do - scope(parent_resource.path, :as => parent_resource.collection_name) do + with_scope_level(:root) do + scope(parent_resource.path) do super(options) end end @@ -871,7 +854,7 @@ module ActionDispatch end def canonical_action?(action, flag) - flag && CANONICAL_ACTIONS.include?(action) + flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s) end def shallow_scoping? @@ -882,18 +865,10 @@ module ActionDispatch prefix = shallow_scoping? ? "#{@scope[:shallow_path]}/#{parent_resource.path}/:id" : @scope[:path] - if canonical_action?(action, path.blank?) - "#{prefix}(.:format)" - else - "#{prefix}/#{action_path(action, path)}(.:format)" - end - end - - def path_for_custom_action - if shallow_scoping? - "#{@scope[:shallow_path]}/#{parent_resource.path}/:id" + path = if canonical_action?(action, path.blank?) + prefix.to_s else - @scope[:path] + "#{prefix}/#{action_path(action, path)}" end end @@ -913,6 +888,7 @@ module ActionDispatch def name_for_action(action, as=nil) prefix = prefix_name_for_action(action, as) + prefix = Mapper.normalize_name(prefix) if prefix name_prefix = @scope[:as] if parent_resource @@ -922,15 +898,18 @@ module ActionDispatch name = case @scope[:scope_level] when :collection - [name_prefix, collection_name] + [prefix, name_prefix, collection_name] when :new - [:new, name_prefix, member_name] + [prefix, :new, name_prefix, member_name] + when :member + [prefix, shallow_scoping? ? @scope[:shallow_prefix] : name_prefix, member_name] + when :root + [name_prefix, collection_name, prefix] else - [shallow_scoping? ? @scope[:shallow_prefix] : name_prefix, member_name] + [name_prefix, member_name, prefix] end - name.unshift(prefix) - name.select(&:present?).join("_") + name.select(&:present?).join("_").presence end end -- cgit v1.2.3 From 80e1f730a264a1875e2866cdff4b70b440f36159 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 24 Aug 2010 16:56:51 -0300 Subject: Allow format to be skipped. This is used internally by mount. --- actionpack/lib/action_dispatch/routing/mapper.rb | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f3cbba243c..9aa34e7ba5 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -87,7 +87,10 @@ module ActionDispatch @options.reverse_merge!(:controller => /.+?/) end - if path.include?(":format") + if @options[:format] == false + @options.delete(:format) + path + elsif path.include?(":format") path else "#{path}(.:format)" @@ -244,7 +247,7 @@ module ActionDispatch raise "A rack application must be specified" unless path - match(path, options.merge(:to => app, :anchor => false)) + match(path, options.merge(:to => app, :anchor => false, :format => false)) self end -- cgit v1.2.3 From 1847d33b4bc776fbd4746c06db41965744377ed6 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Tue, 24 Aug 2010 22:16:34 +0100 Subject: Use nested scope for routes defined at the :resources scope level (as in Rails 2.3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/routing/mapper.rb | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 9aa34e7ba5..9a92ed0b62 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -695,15 +695,14 @@ module ActionDispatch raise ArgumentError, "Unknown scope #{on.inspect} given to :on" end - if @scope[:scope_level] == :resource + if @scope[:scope_level] == :resources + args.push(options) + return nested { match(*args) } + elsif @scope[:scope_level] == :resource args.push(options) return member { match(*args) } end - if resource_scope? - raise ArgumentError, "can't define route directly in resource(s) scope" - end - action = args.first path = path_for_action(action, options.delete(:path)) @@ -900,6 +899,8 @@ module ActionDispatch end name = case @scope[:scope_level] + when :nested + [member_name, prefix] when :collection [prefix, name_prefix, collection_name] when :new -- cgit v1.2.3 From 60de0e56b7f57f0052d7e4f43bd2ef9e363c6a1a Mon Sep 17 00:00:00 2001 From: Joost Baaij Date: Fri, 27 Aug 2010 22:20:53 +0200 Subject: call-seq directive makes rdoc cry and replaces method names with a curly brace; besides it doesn't add anything when you only list one call example since this is obviously documented already --- .../action_dispatch/testing/assertions/selector.rb | 37 ++++++---------------- 1 file changed, 9 insertions(+), 28 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb index 2fc9e2b7d6..21985369cc 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -9,7 +9,7 @@ module ActionDispatch module Assertions NO_STRIP = %w{pre script style textarea} - # Adds the +assert_select+ method for use in Rails functional + # Adds the +assert_select+ method for use in \Rails functional # test cases, which can be used to make assertions on the response HTML of a controller # action. You can also call +assert_select+ within another +assert_select+ to # make assertions on elements selected by the enclosing assertion. @@ -18,16 +18,12 @@ module ActionDispatch # from the response HTML or elements selected by the enclosing assertion. # # In addition to HTML responses, you can make the following assertions: - # * +assert_select_rjs+ - Assertions on HTML content of RJS update and insertion operations. - # * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions. - # * +assert_select_email+ - Assertions on the HTML body of an e-mail. + # * +assert_select_rjs+ - \Assertions on HTML content of RJS update and insertion operations. + # * +assert_select_encoded+ - \Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions. + # * +assert_select_email+ - \Assertions on the HTML body of an e-mail. # # Also see HTML::Selector to learn how to use selectors. module SelectorAssertions - # :call-seq: - # css_select(selector) => array - # css_select(element, selector) => array - # # Select and return all matching elements. # # If called with a single argument, uses that argument as a selector @@ -39,7 +35,7 @@ module ActionDispatch # base element and any of its children. Returns an empty array if no # match is found. # - # The selector may be a CSS selector expression (String), an expression + # The selector may be a CSS selector expression (string), an expression # with substitution values (Array) or an HTML::Selector object. # # ==== Examples @@ -99,10 +95,6 @@ module ActionDispatch selector.select(root) end - # :call-seq: - # assert_select(selector, equality?, message?) - # assert_select(element, selector, equality?, message?) - # # An assertion that selects elements and makes one or more equality tests. # # If the first argument is an element, selects all matching elements @@ -132,7 +124,7 @@ module ActionDispatch # assert_select "li", 8 # end # - # The selector may be a CSS selector expression (String), an expression + # The selector may be a CSS selector expression (string), an expression # with substitution values, or an HTML::Selector object. # # === Equality Tests @@ -140,11 +132,11 @@ module ActionDispatch # The equality test may be one of the following: # * true - Assertion is true if at least one element selected. # * false - Assertion is true if no element selected. - # * String/Regexp - Assertion is true if the text value of at least + # * string/Regexp - Assertion is true if the text value of at least # one element matches the string or regular expression. - # * Integer - Assertion is true if exactly that number of + # * integer - Assertion is true if exactly that number of # elements are selected. - # * Range - Assertion is true if the number of selected + # * range - Assertion is true if the number of selected # elements fit the range. # If no equality test specified, the assertion is true if at least one # element selected. @@ -332,11 +324,6 @@ module ActionDispatch end end - # :call-seq: - # assert_select_rjs(id?) { |elements| ... } - # assert_select_rjs(statement, id?) { |elements| ... } - # assert_select_rjs(:insert, position, id?) { |elements| ... } - # # Selects content from the RJS response. # # === Narrowing down @@ -474,9 +461,6 @@ module ActionDispatch end end - # :call-seq: - # assert_select_encoded(element?) { |elements| ... } - # # Extracts the content of an element, treats it as encoded HTML and runs # nested assertion on it. # @@ -543,9 +527,6 @@ module ActionDispatch end end - # :call-seq: - # assert_select_email { } - # # Extracts the body of an email and runs nested assertions on it. # # You must enable deliveries for this assertion to work, use: -- cgit v1.2.3 From 9f4d3a1ebe29c484d550355e98d9adff2d60dfd4 Mon Sep 17 00:00:00 2001 From: Joost Baaij Date: Fri, 27 Aug 2010 22:31:02 +0200 Subject: expand cookie examples with signed and permanent methods --- actionpack/lib/action_dispatch/middleware/cookies.rb | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index c281e323e5..75c8cc3dd0 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -7,7 +7,7 @@ module ActionDispatch end end - # Cookies are read and written through ActionController#cookies. + # \Cookies are read and written through ActionController#cookies. # # The cookies being read are the ones received along with the request, the cookies # being written will be sent out with the response. Reading a cookie does not get @@ -21,6 +21,15 @@ module ActionDispatch # # Sets a cookie that expires in 1 hour. # cookies[:login] = { :value => "XJ-122", :expires => 1.hour.from_now } # + # # Sets a signed cookie, which prevents a user from tampering with its value. + # # You must specify a value in ActionController::Base.cookie_verifier_secret. + # cookies.signed[:remember_me] = [current_user.id, current_user.salt] + # + # # Sets a "permanent" cookie (which expires in 20 years from now). + # cookies.permanent[:login] = "XJ-122" + # # You can also chain these methods: + # cookies.permanent.signed[:login] = "XJ-122" + # # Examples for reading: # # cookies[:user_name] # => "david" @@ -55,7 +64,7 @@ module ActionDispatch # :domain => :all # Allow the cookie for the top most level # domain and subdomains. # - # * :expires - The time at which this cookie expires, as a Time object. + # * :expires - The time at which this cookie expires, as a \Time object. # * :secure - Whether this cookie is a only transmitted to HTTPS servers. # Default is +false+. # * :httponly - Whether this cookie is accessible via scripting or -- cgit v1.2.3 From 76c569344be9afbc9a6cf5471c2996ecdbd100f6 Mon Sep 17 00:00:00 2001 From: Joost Baaij Date: Fri, 27 Aug 2010 22:45:35 +0200 Subject: mention the alert and notice accessors on the flash --- actionpack/lib/action_dispatch/middleware/flash.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index bfa30cf5af..f36eee7626 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -30,6 +30,11 @@ module ActionDispatch #
<%= flash[:notice] %>
# <% end %> # + # Since the +notice+ and +alert+ keys are a common idiom, convenience accessors are available: + # + # flash.alert = "You must be logged in" + # flash.notice = "Successfully created post" + # # This example just places a string in the flash, but you can put any object in there. And of course, you can put as # many as you like at a time too. Just remember: They'll be gone by the time the next action has been performed. # -- cgit v1.2.3 From 4a56f8f3145e396c9932be83d563fd75219c1f4d Mon Sep 17 00:00:00 2001 From: Joost Baaij Date: Fri, 27 Aug 2010 22:47:11 +0200 Subject: escape constants that should not be linked to --- actionpack/lib/action_dispatch/http/mime_negotiation.rb | 2 +- actionpack/lib/action_dispatch/http/url.rb | 4 ++-- actionpack/lib/action_dispatch/testing/assertions/dom.rb | 2 +- actionpack/lib/action_dispatch/testing/assertions/response.rb | 10 +++++----- actionpack/lib/action_dispatch/testing/assertions/routing.rb | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb index 4082770b85..b959aa258e 100644 --- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb +++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb @@ -32,7 +32,7 @@ module ActionDispatch end end - # Returns the Mime type for the \format used in the request. + # Returns the MIME type for the \format used in the request. # # GET /posts/5.xml | request.format => Mime::XML # GET /posts/5.xhtml | request.format => Mime::HTML diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index ffb7bdd586..f6375902f6 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -1,7 +1,7 @@ module ActionDispatch module Http module URL - # Returns the complete URL used for this request. + # Returns the complete \URL used for this request. def url protocol + host_with_port + fullpath end @@ -96,7 +96,7 @@ module ActionDispatch end # Returns the request URI, accounting for server idiosyncrasies. - # WEBrick includes the full URL. IIS leaves REQUEST_URI blank. + # WEBrick includes the full \URL. IIS leaves REQUEST_URI blank. def request_uri ActiveSupport::Deprecation.warn "Using #request_uri is deprecated. Use fullpath instead.", caller fullpath diff --git a/actionpack/lib/action_dispatch/testing/assertions/dom.rb b/actionpack/lib/action_dispatch/testing/assertions/dom.rb index 9c215de743..47c84742aa 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/dom.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/dom.rb @@ -3,7 +3,7 @@ require 'action_controller/vendor/html-scanner' module ActionDispatch module Assertions module DomAssertions - # Test two HTML strings for equivalency (e.g., identical up to reordering of attributes) + # \Test two HTML strings for equivalency (e.g., identical up to reordering of attributes) # # ==== Examples # diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb index ec5e9efe44..10b122557a 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/response.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb @@ -1,6 +1,6 @@ module ActionDispatch module Assertions - # A small suite of assertions that test responses from Rails applications. + # A small suite of assertions that test responses from \Rails applications. module ResponseAssertions extend ActiveSupport::Concern @@ -18,8 +18,8 @@ module ActionDispatch # * :missing - Status code was 404 # * :error - Status code was in the 500-599 range # - # You can also pass an explicit status number like assert_response(501) - # or its symbolic equivalent assert_response(:not_implemented). + # You can also pass an explicit status number like assert_response(501) + # or its symbolic equivalent assert_response(:not_implemented). # See ActionDispatch::StatusCodes for a full list. # # ==== Examples @@ -45,8 +45,8 @@ module ActionDispatch end # Assert that the redirection options passed in match those of the redirect called in the latest action. - # This match can be partial, such that assert_redirected_to(:controller => "weblog") will also - # match the redirection of redirect_to(:controller => "weblog", :action => "show") and so on. + # This match can be partial, such that assert_redirected_to(:controller => "weblog") will also + # match the redirection of redirect_to(:controller => "weblog", :action => "show") and so on. # # ==== Examples # diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 5a3ffda255..c5fed1fc8f 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -4,10 +4,10 @@ require 'active_support/core_ext/hash/indifferent_access' module ActionDispatch module Assertions - # Suite of assertions to test routes generated by Rails and the handling of requests made to them. + # Suite of assertions to test routes generated by \Rails and the handling of requests made to them. module RoutingAssertions # Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash) - # match +path+. Basically, it asserts that Rails recognizes the route given by +expected_options+. + # match +path+. Basically, it asserts that \Rails recognizes the route given by +expected_options+. # # Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes # requiring a specific HTTP method. The hash should contain a :path with the incoming request path -- cgit v1.2.3 From 27d42a56b9b28ab9966fa73971e1a5b7a9c8cdff Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Fri, 27 Aug 2010 23:30:52 +0200 Subject: Revert "call-seq directive makes rdoc cry and replaces method names with a curly brace; besides it doesn't add anything when you only list one call example since this is obviously documented already" Reason: Part of this commit touches vendorized stuff, the rest is fine, could you please repatch? This reverts commit 60de0e56b7f57f0052d7e4f43bd2ef9e363c6a1a. --- .../action_dispatch/testing/assertions/selector.rb | 37 ++++++++++++++++------ 1 file changed, 28 insertions(+), 9 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb index 21985369cc..2fc9e2b7d6 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -9,7 +9,7 @@ module ActionDispatch module Assertions NO_STRIP = %w{pre script style textarea} - # Adds the +assert_select+ method for use in \Rails functional + # Adds the +assert_select+ method for use in Rails functional # test cases, which can be used to make assertions on the response HTML of a controller # action. You can also call +assert_select+ within another +assert_select+ to # make assertions on elements selected by the enclosing assertion. @@ -18,12 +18,16 @@ module ActionDispatch # from the response HTML or elements selected by the enclosing assertion. # # In addition to HTML responses, you can make the following assertions: - # * +assert_select_rjs+ - \Assertions on HTML content of RJS update and insertion operations. - # * +assert_select_encoded+ - \Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions. - # * +assert_select_email+ - \Assertions on the HTML body of an e-mail. + # * +assert_select_rjs+ - Assertions on HTML content of RJS update and insertion operations. + # * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions. + # * +assert_select_email+ - Assertions on the HTML body of an e-mail. # # Also see HTML::Selector to learn how to use selectors. module SelectorAssertions + # :call-seq: + # css_select(selector) => array + # css_select(element, selector) => array + # # Select and return all matching elements. # # If called with a single argument, uses that argument as a selector @@ -35,7 +39,7 @@ module ActionDispatch # base element and any of its children. Returns an empty array if no # match is found. # - # The selector may be a CSS selector expression (string), an expression + # The selector may be a CSS selector expression (String), an expression # with substitution values (Array) or an HTML::Selector object. # # ==== Examples @@ -95,6 +99,10 @@ module ActionDispatch selector.select(root) end + # :call-seq: + # assert_select(selector, equality?, message?) + # assert_select(element, selector, equality?, message?) + # # An assertion that selects elements and makes one or more equality tests. # # If the first argument is an element, selects all matching elements @@ -124,7 +132,7 @@ module ActionDispatch # assert_select "li", 8 # end # - # The selector may be a CSS selector expression (string), an expression + # The selector may be a CSS selector expression (String), an expression # with substitution values, or an HTML::Selector object. # # === Equality Tests @@ -132,11 +140,11 @@ module ActionDispatch # The equality test may be one of the following: # * true - Assertion is true if at least one element selected. # * false - Assertion is true if no element selected. - # * string/Regexp - Assertion is true if the text value of at least + # * String/Regexp - Assertion is true if the text value of at least # one element matches the string or regular expression. - # * integer - Assertion is true if exactly that number of + # * Integer - Assertion is true if exactly that number of # elements are selected. - # * range - Assertion is true if the number of selected + # * Range - Assertion is true if the number of selected # elements fit the range. # If no equality test specified, the assertion is true if at least one # element selected. @@ -324,6 +332,11 @@ module ActionDispatch end end + # :call-seq: + # assert_select_rjs(id?) { |elements| ... } + # assert_select_rjs(statement, id?) { |elements| ... } + # assert_select_rjs(:insert, position, id?) { |elements| ... } + # # Selects content from the RJS response. # # === Narrowing down @@ -461,6 +474,9 @@ module ActionDispatch end end + # :call-seq: + # assert_select_encoded(element?) { |elements| ... } + # # Extracts the content of an element, treats it as encoded HTML and runs # nested assertion on it. # @@ -527,6 +543,9 @@ module ActionDispatch end end + # :call-seq: + # assert_select_email { } + # # Extracts the body of an email and runs nested assertions on it. # # You must enable deliveries for this assertion to work, use: -- cgit v1.2.3 From 279c3957237b049dead8d95db81ea1ff665ee78c Mon Sep 17 00:00:00 2001 From: Joost Baaij Date: Fri, 27 Aug 2010 23:50:23 +0200 Subject: Use common terminology --- actionpack/lib/action_dispatch/middleware/flash.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index f36eee7626..21aeeb217a 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -10,13 +10,13 @@ module ActionDispatch # The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed # to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create - # action that sets flash[:notice] = "Successfully created" before redirecting to a display action that can + # action that sets flash[:notice] = "Post successfully created" before redirecting to a display action that can # then expose the flash to its template. Actually, that exposure is automatically done. Example: # # class PostsController < ActionController::Base # def create # # save post - # flash[:notice] = "Successfully created post" + # flash[:notice] = "Post successfully created" # redirect_to posts_path(@post) # end # @@ -33,7 +33,7 @@ module ActionDispatch # Since the +notice+ and +alert+ keys are a common idiom, convenience accessors are available: # # flash.alert = "You must be logged in" - # flash.notice = "Successfully created post" + # flash.notice = "Post successfully created" # # This example just places a string in the flash, but you can put any object in there. And of course, you can put as # many as you like at a time too. Just remember: They'll be gone by the time the next action has been performed. -- cgit v1.2.3 From 4b14de72e1fe9788958143c70cae0c3fef8e8ecb Mon Sep 17 00:00:00 2001 From: Joost Baaij Date: Sat, 28 Aug 2010 00:50:50 +0200 Subject: The call-seq directive has no useful effect on our documentation and is not used anywhere else. Worse still, its use breaks some rdoc, replacing method names with a curly brace. Having just one call-seq directive doesn't add anything since this is covered by regular rdoc. Having multiple might make sense, but these are already documented with examples. This partly re-reverts 60de0e56b7f57f0052d7e4f43bd2ef9e363c6a1a but does not touch the vendorized code in html-scanner. --- .../action_dispatch/testing/assertions/selector.rb | 19 ------------------- 1 file changed, 19 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb index 2fc9e2b7d6..e1015c62cd 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -24,10 +24,6 @@ module ActionDispatch # # Also see HTML::Selector to learn how to use selectors. module SelectorAssertions - # :call-seq: - # css_select(selector) => array - # css_select(element, selector) => array - # # Select and return all matching elements. # # If called with a single argument, uses that argument as a selector @@ -99,10 +95,6 @@ module ActionDispatch selector.select(root) end - # :call-seq: - # assert_select(selector, equality?, message?) - # assert_select(element, selector, equality?, message?) - # # An assertion that selects elements and makes one or more equality tests. # # If the first argument is an element, selects all matching elements @@ -332,11 +324,6 @@ module ActionDispatch end end - # :call-seq: - # assert_select_rjs(id?) { |elements| ... } - # assert_select_rjs(statement, id?) { |elements| ... } - # assert_select_rjs(:insert, position, id?) { |elements| ... } - # # Selects content from the RJS response. # # === Narrowing down @@ -474,9 +461,6 @@ module ActionDispatch end end - # :call-seq: - # assert_select_encoded(element?) { |elements| ... } - # # Extracts the content of an element, treats it as encoded HTML and runs # nested assertion on it. # @@ -543,9 +527,6 @@ module ActionDispatch end end - # :call-seq: - # assert_select_email { } - # # Extracts the body of an email and runs nested assertions on it. # # You must enable deliveries for this assertion to work, use: -- cgit v1.2.3 From 3e22e0b0250e1386f68ebbdb7f23ae10888f5da6 Mon Sep 17 00:00:00 2001 From: yury Date: Tue, 24 Aug 2010 23:31:48 +0400 Subject: Micro optimization for build_named_route_call in PolymorphicRoutes: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. use map instead of inject 2. use [].join("_") instead of '<<'. It is a little bit faster for ruby 1.9.2 and x2 faster for ruby 1.8.7. http://gist.github.com/548143 [#5450 state:resolved] Signed-off-by: José Valim --- .../action_dispatch/routing/polymorphic_routes.rb | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index 31dba835ac..142cd08eac 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -148,29 +148,29 @@ module ActionDispatch def build_named_route_call(records, inflection, options = {}) unless records.is_a?(Array) record = extract_record(records) - route = '' + route = [] else record = records.pop - route = records.inject("") do |string, parent| + route = records.map do |parent| if parent.is_a?(Symbol) || parent.is_a?(String) - string << "#{parent}_" + parent else - string << ActiveModel::Naming.plural(parent).singularize - string << "_" + ActiveModel::Naming.plural(parent).singularize end end end if record.is_a?(Symbol) || record.is_a?(String) - route << "#{record}_" + route << record else route << ActiveModel::Naming.plural(record) - route = route.singularize if inflection == :singular - route << "_" - route << "index_" if ActiveModel::Naming.uncountable?(record) && inflection == :plural + route = [route.join("_").singularize] if inflection == :singular + route << "index" if ActiveModel::Naming.uncountable?(record) && inflection == :plural end - action_prefix(options) + route + routing_type(options).to_s + route << routing_type(options) + + action_prefix(options) + route.join("_") end def extract_record(record_or_hash_or_array) -- cgit v1.2.3 From 5ead15b07597e9cdb887cfe6aa74de4a14140bb1 Mon Sep 17 00:00:00 2001 From: Joost Baaij Date: Sat, 28 Aug 2010 23:24:02 +0200 Subject: Rework the routing documentation. Move the default route to the bottom, as this practise should be discouraged. Add documentation for resources, external redirects and Rack applications. --- actionpack/lib/action_dispatch/routing.rb | 97 ++++++++++++++++++++++++------- 1 file changed, 75 insertions(+), 22 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index df1b53016d..0b9689dc88 100644 --- a/actionpack/lib/action_dispatch/routing.rb +++ b/actionpack/lib/action_dispatch/routing.rb @@ -2,31 +2,11 @@ require 'active_support/core_ext/object/to_param' require 'active_support/core_ext/regexp' module ActionDispatch - # = Routing - # # The routing module provides URL rewriting in native Ruby. It's a way to # redirect incoming requests to controllers and actions. This replaces - # mod_rewrite rules. Best of all, Rails' Routing works with any web server. + # mod_rewrite rules. Best of all, Rails' \Routing works with any web server. # Routes are defined in config/routes.rb. # - # Consider the following route, which you will find commented out at the - # bottom of your generated config/routes.rb: - # - # match ':controller(/:action(/:id(.:format)))' - # - # This route states that it expects requests to consist of a - # :controller followed optionally by an :action that in - # turn is followed optionally by an :id, which in turn is followed - # optionally by a :format - # - # Suppose you get an incoming request for /blog/edit/22, you'll end - # up with: - # - # params = { :controller => 'blog', - # :action => 'edit', - # :id => '22' - # } - # # Think of creating routes as drawing a map for your requests. The map tells # them where to go based on some predefined pattern: # @@ -43,6 +23,39 @@ module ActionDispatch # # Other names simply map to a parameter as in the case of :id. # + # == Resources + # + # Resource routing allows you to quickly declare all of the common routes + # for a given resourceful controller. Instead of declaring separate routes + # for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+ + # actions, a resourceful route declares them in a single line of code: + # + # resources :photos + # + # Sometimes, you have a resource that clients always look up without + # referencing an ID. A common example, /profile always shows the profile of + # the currently logged in user. In this case, you can use a singular resource + # to map /profile (rather than /profile/:id) to the show action. + # + # resource :profile + # + # It's common to have resources that are logically children of other + # resources: + # + # resources :magazines do + # resources :ads + # end + # + # You may wish to organize groups of controllers under a namespace. Most + # commonly, you might group a number of administrative controllers under + # an +admin+ namespace. You would place these controllers under the + # app/controllers/admin directory, and you can group them together in your + # router: + # + # namespace "admin" do + # resources :posts, :comments + # end + # # == Named routes # # Routes can be named by passing an :as option, @@ -131,6 +144,30 @@ module ActionDispatch # Encoding regular expression modifiers are silently ignored. The # match will always use the default encoding or ASCII. # + # == Default route + # + # Consider the following route, which you will find commented out at the + # bottom of your generated config/routes.rb: + # + # match ':controller(/:action(/:id(.:format)))' + # + # This route states that it expects requests to consist of a + # :controller followed optionally by an :action that in + # turn is followed optionally by an :id, which in turn is followed + # optionally by a :format. + # + # Suppose you get an incoming request for /blog/edit/22, you'll end + # up with: + # + # params = { :controller => 'blog', + # :action => 'edit', + # :id => '22' + # } + # + # By not relying on default routes, you improve the security of your + # application since not all controller actions, which includes actions you + # might add at a later time, are exposed by default. + # # == HTTP Methods # # Using the :via option when specifying a route allows you to restrict it to a specific HTTP method. @@ -160,6 +197,20 @@ module ActionDispatch # however if your route needs to respond to more than one HTTP method (or all methods) then using the # :via option on match is preferable. # + # == External redirects + # + # You can redirect any path to another path using the redirect helper in your router: + # + # match "/stories" => redirect("/posts") + # + # == Routing to Rack Applications + # + # Instead of a String, like posts#index, which corresponds to the + # index action in the PostsController, you can specify any Rack application + # as the endpoint for a matcher: + # + # match "/application.js" => Sprockets + # # == Reloading routes # # You can reload routes if you feel you must: @@ -208,7 +259,9 @@ module ActionDispatch # # == View a list of all your routes # - # Run rake routes. + # rake routes + # + # Target specific controllers by prefixing the command with CONTROLLER=x. # module Routing autoload :DeprecatedMapper, 'action_dispatch/routing/deprecated_mapper' -- cgit v1.2.3 From 591e87fe7b10ed4c90f65ff25bb39520cdad0f87 Mon Sep 17 00:00:00 2001 From: Joost Baaij Date: Sun, 29 Aug 2010 00:04:14 +0200 Subject: Expanded routing documentation with current best practices --- actionpack/lib/action_dispatch/http/response.rb | 19 ++- actionpack/lib/action_dispatch/routing/mapper.rb | 169 +++++++++++++++++++++ .../action_dispatch/routing/polymorphic_routes.rb | 2 +- actionpack/lib/action_dispatch/routing/url_for.rb | 9 +- .../lib/action_dispatch/testing/integration.rb | 10 +- 5 files changed, 188 insertions(+), 21 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index 3b85a98576..ff5e96fdf7 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -4,27 +4,26 @@ require 'active_support/core_ext/object/blank' require 'active_support/core_ext/class/attribute_accessors' module ActionDispatch # :nodoc: - # Represents an HTTP response generated by a controller action. One can use - # an ActionDispatch::Response object to retrieve the current state - # of the response, or customize the response. An Response object can - # either represent a "real" HTTP response (i.e. one that is meant to be sent - # back to the web browser) or a test response (i.e. one that is generated - # from integration tests). See CgiResponse and TestResponse, respectively. + # Represents an HTTP response generated by a controller action. Use it to + # retrieve the current state of the response, or customize the response. It can + # either represent a real HTTP response (i.e. one that is meant to be sent + # back to the web browser) or a TestResponse (i.e. one that is generated + # from integration tests). # - # Response is mostly a Ruby on Rails framework implement detail, and + # \Response is mostly a Ruby on \Rails framework implementation detail, and # should never be used directly in controllers. Controllers should use the # methods defined in ActionController::Base instead. For example, if you want # to set the HTTP response's content MIME type, then use # ActionControllerBase#headers instead of Response#headers. # # Nevertheless, integration tests may want to inspect controller responses in - # more detail, and that's when Response can be useful for application + # more detail, and that's when \Response can be useful for application # developers. Integration test methods such as # ActionDispatch::Integration::Session#get and # ActionDispatch::Integration::Session#post return objects of type - # TestResponse (which are of course also of type Response). + # TestResponse (which are of course also of type \Response). # - # For example, the following demo integration "test" prints the body of the + # For example, the following demo integration test prints the body of the # controller response to the console: # # class DemoControllerTest < ActionDispatch::IntegrationTest diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 9a92ed0b62..a3bd4771c2 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -226,10 +226,24 @@ module ActionDispatch @set = set end + # You can specify what Rails should route "/" to with the root method: + # + # root :to => 'pages#main' + # + # You should put the root route at the end of config/routes.rb. def root(options = {}) 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. + # + # match ':controller/:action/:id/:user_id' + # + # 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. def match(path, options=nil) mapping = Mapping.new(@set, @scope, path, options || {}).to_route @set.add_route(*mapping) @@ -258,22 +272,29 @@ module ActionDispatch end module HttpHelpers + # Define a route that only recognizes HTTP GET. def get(*args, &block) map_method(:get, *args, &block) end + # Define a route that only recognizes HTTP POST. def post(*args, &block) map_method(:post, *args, &block) end + # Define a route that only recognizes HTTP PUT. def put(*args, &block) map_method(:put, *args, &block) end + # Define a route that only recognizes HTTP DELETE. def delete(*args, &block) map_method(:delete, *args, &block) end + # Redirect any path to another path: + # + # match "/stories" => redirect("/posts") def redirect(*args, &block) options = args.last.is_a?(Hash) ? args.pop : {} @@ -314,12 +335,72 @@ module ActionDispatch end end + # You may wish to organize groups of controllers under a namespace. + # Most commonly, you might group a number of administrative controllers + # under an +admin+ namespace. You would place these controllers under + # the app/controllers/admin directory, and you can group them together + # in your router: + # + # namespace "admin" do + # resources :posts, :comments + # end + # + # This will create a number of routes for each of the posts and comments + # controller. For Admin::PostsController, Rails will create: + # + # GET /admin/photos + # GET /admin/photos/new + # POST /admin/photos + # GET /admin/photos/1 + # GET /admin/photos/1/edit + # PUT /admin/photos/1 + # DELETE /admin/photos/1 + # + # If you want to route /photos (without the prefix /admin) to + # Admin::PostsController, you could use + # + # scope :module => "admin" do + # resources :posts, :comments + # end + # + # or, for a single case + # + # resources :posts, :module => "admin" + # + # If you want to route /admin/photos to PostsController + # (without the Admin:: module prefix), you could use + # + # scope "/admin" do + # resources :posts, :comments + # end + # + # or, for a single case + # + # resources :posts, :path => "/admin" + # + # In each of these cases, the named routes remain the same as if you did + # not use scope. In the last case, the following paths map to + # PostsController: + # + # GET /admin/photos + # GET /admin/photos/new + # POST /admin/photos + # GET /admin/photos/1 + # GET /admin/photos/1/edit + # PUT /admin/photos/1 + # DELETE /admin/photos/1 module Scoping def initialize(*args) #:nodoc: @scope = {} super end + # Used to route /photos (without the prefix /admin) + # to Admin::PostsController: + # + # scope :module => "admin" do + # resources :posts + # end def scope(*args) options = args.extract_options! options = options.dup @@ -441,6 +522,37 @@ module ActionDispatch end end + # Resource routing allows you to quickly declare all of the common routes + # for a given resourceful controller. Instead of declaring separate routes + # for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+ + # actions, a resourceful route declares them in a single line of code: + # + # resources :photos + # + # Sometimes, you have a resource that clients always look up without + # referencing an ID. A common example, /profile always shows the profile of + # the currently logged in user. In this case, you can use a singular resource + # to map /profile (rather than /profile/:id) to the show action. + # + # resource :profile + # + # It's common to have resources that are logically children of other + # resources: + # + # resources :magazines do + # resources :ads + # end + # + # You may wish to organize groups of controllers under a namespace. Most + # commonly, you might group a number of administrative controllers under + # an +admin+ namespace. You would place these controllers under the + # app/controllers/admin directory, and you can group them together in your + # router: + # + # namespace "admin" do + # resources :posts, :comments + # end + # 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. @@ -549,6 +661,24 @@ module ActionDispatch @scope[:path_names].merge!(options) end + # Sometimes, you have a resource that clients always look up without + # referencing an ID. A common example, /profile always shows the + # profile of the currently logged in user. In this case, you can use + # a singular resource to map /profile (rather than /profile/:id) to + # the show action: + # + # resource :geocoder + # + # creates six different routes in your application, all mapping to + # the GeoCoders controller (note that the controller is named after + # the plural): + # + # GET /geocoder/new + # POST /geocoder + # GET /geocoder + # GET /geocoder/edit + # PUT /geocoder + # DELETE /geocoder def resource(*resources, &block) options = resources.extract_options! @@ -578,6 +708,22 @@ module ActionDispatch self end + # In Rails, a resourceful route provides a mapping between HTTP verbs + # and URLs and controller actions. By convention, each action also maps + # to particular CRUD operations in a database. A single entry in the + # routing file, such as + # + # resources :photos + # + # creates seven different routes in your application, all mapping to + # the Photos controller: + # + # GET /photos/new + # POST /photos + # GET /photos/:id + # GET /photos/:id/edit + # PUT /photos/:id + # DELETE /photos/:id def resources(*resources, &block) options = resources.extract_options! @@ -608,6 +754,18 @@ module ActionDispatch self end + # To add a route to the collection: + # + # resources :photos do + # collection do + # get 'search' + # end + # end + # + # This will enable Rails to recognize paths such as /photos/search + # with GET, and route to the search action of PhotosController. It will also + # create the search_photos_url and search_photos_path + # route helpers. def collection unless @scope[:scope_level] == :resources raise ArgumentError, "can't use collection outside resources scope" @@ -618,6 +776,17 @@ module ActionDispatch end end + # To add a member route, add a member block into the resource block: + # + # resources :photos do + # member do + # get 'preview' + # end + # end + # + # This will recognize /photos/1/preview with GET, and route to the + # preview action of PhotosController. It will also create the + # preview_photo_url and preview_photo_path helpers. def member unless resource_scope? raise ArgumentError, "can't use member outside resource(s) scope" diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index 31dba835ac..acebde6ede 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -17,7 +17,7 @@ module ActionDispatch # # == Usage within the framework # - # Polymorphic URL helpers are used in a number of places throughout the Rails framework: + # Polymorphic URL helpers are used in a number of places throughout the \Rails framework: # # * url_for, so you can use it with a record as the argument, e.g. # url_for(@article); diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index ba93ff8630..28ec830fe8 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -1,6 +1,6 @@ module ActionDispatch module Routing - # In routes.rb one defines URL-to-controller mappings, but the reverse + # In config/routes.rb you define URL-to-controller mappings, but the reverse # is also possible: an URL can be generated from one of your routing definitions. # URL generation functionality is centralized in this module. # @@ -12,15 +12,14 @@ module ActionDispatch # # == URL generation from parameters # - # As you may know, some functions - such as ActionController::Base#url_for + # As you may know, some functions, such as ActionController::Base#url_for # and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set # of parameters. For example, you've probably had the chance to write code # like this in one of your views: # # <%= link_to('Click here', :controller => 'users', # :action => 'new', :message => 'Welcome!') %> - # - # # Generates a link to /users/new?message=Welcome%21 + # # => "/users/new?message=Welcome%21" # # link_to, and all other functions that require URL generation functionality, # actually use ActionController::UrlFor under the hood. And in particular, @@ -61,7 +60,7 @@ module ActionDispatch # # UrlFor also allows one to access methods that have been auto-generated from # named routes. For example, suppose that you have a 'users' resource in your - # routes.rb: + # config/routes.rb: # # resources :users # diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index b52795c575..590ebbf364 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -115,8 +115,8 @@ module ActionDispatch end end - # An integration Session instance represents a set of requests and responses - # performed sequentially by some virtual user. Because you can instantiate + # An instance of this class represents a set of requests and responses + # performed sequentially by a test process. Because you can instantiate # multiple sessions and run them side-by-side, you can also mimic (to some # limited extent) multiple simultaneous users interacting with your system. # @@ -373,12 +373,12 @@ module ActionDispatch end end - # An IntegrationTest is one that spans multiple controllers and actions, + # An test that spans multiple controllers and actions, # tying them all together to ensure they work together as expected. It tests # more completely than either unit or functional tests do, exercising the # entire stack, from the dispatcher to the database. # - # At its simplest, you simply extend IntegrationTest and write your tests + # At its simplest, you simply extend IntegrationTest and write your tests # using the get/post methods: # # require "test_helper" @@ -403,7 +403,7 @@ module ActionDispatch # However, you can also have multiple session instances open per test, and # even extend those instances with assertions and methods to create a very # powerful testing DSL that is specific for your application. You can even - # reference any named routes you happen to have defined! + # reference any named routes you happen to have defined. # # require "test_helper" # -- cgit v1.2.3 From 02480a897be25c24f59180513d37649a31ad3835 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Tue, 31 Aug 2010 17:02:49 +0100 Subject: Move implicit nested call before options handling so that nested constraints work [#5513 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/routing/mapper.rb | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index a3bd4771c2..a2570cb877 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -909,6 +909,11 @@ module ActionDispatch return true end + if resource_scope? + nested { send(method, resources.pop, options, &block) } + return true + end + options.keys.each do |k| (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp) end @@ -925,13 +930,6 @@ module ActionDispatch options.merge!(scope_action_options) if scope_action_options? end - if resource_scope? - nested do - send(method, resources.pop, options, &block) - end - return true - end - false end @@ -1017,11 +1015,11 @@ module ActionDispatch end def id_constraint? - @scope[:id].is_a?(Regexp) || (@scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp)) + @scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp) end def id_constraint - @scope[:id] || @scope[:constraints][:id] + @scope[:constraints][:id] end def canonical_action?(action, flag) -- cgit v1.2.3 From 38a421b34d0b414564e919f67d339fac067a56e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Strza=C5=82kowski?= Date: Wed, 11 Aug 2010 21:56:22 +0200 Subject: Setup explicit requires for files with exceptions. Removed them from autoloading. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/request.rb | 1 + actionpack/lib/action_dispatch/middleware/show_exceptions.rb | 1 + actionpack/lib/action_dispatch/routing/deprecated_mapper.rb | 1 + actionpack/lib/action_dispatch/routing/route_set.rb | 1 + 4 files changed, 4 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 5606d6abfe..7eccd23dab 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -5,6 +5,7 @@ require 'strscan' require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/string/access' require 'action_dispatch/http/headers' +require 'action_controller/metal/exceptions' module ActionDispatch class Request < Rack::Request diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index ef0c9c51f5..9355b9c657 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -1,6 +1,7 @@ require 'active_support/core_ext/exception' require 'active_support/notifications' require 'action_dispatch/http/request' +require 'action_controller/metal/exceptions' module ActionDispatch # This middleware rescues any exception returned by the application and renders diff --git a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb index e04062ce8b..c97cbfe1f1 100644 --- a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb +++ b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb @@ -1,6 +1,7 @@ require 'active_support/core_ext/object/blank' require 'active_support/core_ext/object/with_options' require 'active_support/core_ext/object/try' +require 'action_controller/metal/exceptions' module ActionDispatch module Routing diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index b531cc1a8e..e6803b2722 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -2,6 +2,7 @@ require 'rack/mount' require 'forwardable' require 'active_support/core_ext/object/to_query' require 'action_dispatch/routing/deprecated_mapper' +require 'action_controller/metal/exceptions' module ActionDispatch module Routing -- cgit v1.2.3 From 48bf667a8b1c489bd6edff0b8322324a7a1b06bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 2 Sep 2010 12:54:16 +0200 Subject: Ensure routes are loaded only after the initialization process finishes, ensuring all configuration options were applied. --- actionpack/lib/action_dispatch/railtie.rb | 5 ----- 1 file changed, 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb index a3af37947a..ed066ad75e 100644 --- a/actionpack/lib/action_dispatch/railtie.rb +++ b/actionpack/lib/action_dispatch/railtie.rb @@ -8,10 +8,5 @@ module ActionDispatch config.action_dispatch.ip_spoofing_check = true config.action_dispatch.show_exceptions = true config.action_dispatch.best_standards_support = true - - # Prepare dispatcher callbacks and run 'prepare' callbacks - initializer "action_dispatch.prepare_dispatcher" do |app| - ActionDispatch::Callbacks.to_prepare { app.routes_reloader.execute_if_updated } - end end end -- cgit v1.2.3 From 599e46bf24419a429ee0bb0ea02afd48f47aa4ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 2 Sep 2010 21:10:29 +0200 Subject: Revert "Setup explicit requires for files with exceptions. Removed them from autoloading." Booting a new Rails application does not work after this commit [#5359 state:open] This reverts commit 38a421b34d0b414564e919f67d339fac067a56e6. --- actionpack/lib/action_dispatch/http/request.rb | 1 - actionpack/lib/action_dispatch/middleware/show_exceptions.rb | 1 - actionpack/lib/action_dispatch/routing/deprecated_mapper.rb | 1 - actionpack/lib/action_dispatch/routing/route_set.rb | 1 - 4 files changed, 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 7eccd23dab..5606d6abfe 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -5,7 +5,6 @@ require 'strscan' require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/string/access' require 'action_dispatch/http/headers' -require 'action_controller/metal/exceptions' module ActionDispatch class Request < Rack::Request diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 9355b9c657..ef0c9c51f5 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -1,7 +1,6 @@ require 'active_support/core_ext/exception' require 'active_support/notifications' require 'action_dispatch/http/request' -require 'action_controller/metal/exceptions' module ActionDispatch # This middleware rescues any exception returned by the application and renders diff --git a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb index c97cbfe1f1..e04062ce8b 100644 --- a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb +++ b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb @@ -1,7 +1,6 @@ require 'active_support/core_ext/object/blank' require 'active_support/core_ext/object/with_options' require 'active_support/core_ext/object/try' -require 'action_controller/metal/exceptions' module ActionDispatch module Routing diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index e6803b2722..b531cc1a8e 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -2,7 +2,6 @@ require 'rack/mount' require 'forwardable' require 'active_support/core_ext/object/to_query' require 'action_dispatch/routing/deprecated_mapper' -require 'action_controller/metal/exceptions' module ActionDispatch module Routing -- cgit v1.2.3 From f7af75976a9117aa1cb294114af4f99a1d28f1cd Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 23 Jun 2010 02:38:44 +0200 Subject: require 'active_support/dependencies' in action_dispatch/middleware/stack --- actionpack/lib/action_dispatch/middleware/stack.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 5a029a60d1..6f243574e4 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -1,4 +1,5 @@ require "active_support/inflector/methods" +require "active_support/dependencies" module ActionDispatch class MiddlewareStack < Array -- cgit v1.2.3 From 28016d33b0f2e668ca59a912c7fb2d777e3cf0a3 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 1 Jul 2010 09:04:30 +0200 Subject: Use env['action_dispatch.routes'] to determine if we should generate prefix or not. This technique is here to allow using routes from Engine in Application and vice versa. When using Engine routes inside Application it should generate prefix based on mount point. When using Engine routes inside Engine it should use env['SCRIPT_NAME']. In any other case it should generate prefix as env should not be even available. --- actionpack/lib/action_dispatch/routing/mapper.rb | 27 ++++++++++++++++++++++ .../lib/action_dispatch/routing/route_set.rb | 20 +++++++++++----- actionpack/lib/action_dispatch/routing/url_for.rb | 8 ++++++- 3 files changed, 48 insertions(+), 7 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index a2570cb877..f3aa09f4a7 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -261,7 +261,11 @@ module ActionDispatch raise "A rack application must be specified" unless path + options[:as] ||= app_name(app) + match(path, options.merge(:to => app, :anchor => false, :format => false)) + + define_generate_prefix(app, options[:as]) self end @@ -269,6 +273,29 @@ module ActionDispatch @set.default_url_options = options end alias_method :default_url_options, :default_url_options= + + private + def app_name(app) + return unless app.respond_to?(:routes) + class_name = app.class.is_a?(Class) ? app.name : app.class.name + ActiveSupport::Inflector.underscore(class_name).gsub("/", "_") + end + + def define_generate_prefix(app, name) + return unless app.respond_to?(:routes) + + _route = @set.named_routes.routes[name.to_sym] + _router = @set + app.routes.class_eval do + define_method :_generate_prefix do |options| + keys = _route.segment_keys + ActionDispatch::Routing::RouteSet::RESERVED_OPTIONS + prefix_options = options.reject { |k, v| !(keys).include?(k) } + # we must actually delete prefix segment keys to avoid passing them to next url_for + _route.segment_keys.each { |k| options.delete(k) } + _router.url_helpers.send("#{name}_path", prefix_options) + end + end + end end module HttpHelpers diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index b531cc1a8e..cb0373951f 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -303,10 +303,9 @@ module ActionDispatch end class Generator #:nodoc: - attr_reader :options, :recall, :set, :script_name, :named_route + attr_reader :options, :recall, :set, :named_route def initialize(options, recall, set, extras = false) - @script_name = options.delete(:script_name) @named_route = options.delete(:use_route) @options = options.dup @recall = recall.dup @@ -401,7 +400,7 @@ module ActionDispatch return [path, params.keys] if @extras path << "?#{params.to_query}" if params.any? - "#{script_name}#{path}" + path rescue Rack::Mount::RoutingError raise_routing_error end @@ -453,7 +452,11 @@ module ActionDispatch Generator.new(options, recall, self, extras).generate end - RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :port, :trailing_slash] + RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :port, :trailing_slash, :script_name, :skip_prefix, :routes] + + def _generate_prefix(options = {}) + nil + end def url_for(options) finalize! @@ -464,7 +467,6 @@ module ActionDispatch rewritten_url = "" path_segments = options.delete(:_path_segments) - unless options[:only_path] rewritten_url << (options[:protocol] || "http") rewritten_url << "://" unless rewritten_url.match("://") @@ -476,9 +478,15 @@ module ActionDispatch rewritten_url << ":#{options.delete(:port)}" if options.key?(:port) end + path = [options.delete(:script_name)] + if !options.delete(:skip_prefix) + path << _generate_prefix(options) + end + path_options = options.except(*RESERVED_OPTIONS) path_options = yield(path_options) if block_given? - path = generate(path_options, path_segments || {}) + path << generate(path_options, path_segments || {}) + path = path.compact.join '' # ROUTES TODO: This can be called directly, so script_name should probably be set in the routes rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index 28ec830fe8..f73067688c 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -128,7 +128,13 @@ module ActionDispatch when String options when nil, Hash - _routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys) + routes = (options ? options.delete(:routes) : nil) || _routes + + if respond_to?(:env) && env && routes.equal?(env["action_dispatch.routes"]) + options[:skip_prefix] = true + end + + routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys) else polymorphic_url(options) end -- cgit v1.2.3 From 451c9942bb493190d5673c1b55be7506056db13b Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 7 Jul 2010 11:26:03 +0200 Subject: Allow to generate Application routes inside Engine This requires knowledge about original SCRIPT_NAME and the parent router. It should be pass through the env as ORIGIAL_SCRIPT_NAME and action_dispatch.parent_routes --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- actionpack/lib/action_dispatch/routing/url_for.rb | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f3aa09f4a7..0e138524cd 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -289,7 +289,7 @@ module ActionDispatch app.routes.class_eval do define_method :_generate_prefix do |options| keys = _route.segment_keys + ActionDispatch::Routing::RouteSet::RESERVED_OPTIONS - prefix_options = options.reject { |k, v| !(keys).include?(k) } + prefix_options = options.slice(*keys) # we must actually delete prefix segment keys to avoid passing them to next url_for _route.segment_keys.each { |k| options.delete(k) } _router.url_helpers.send("#{name}_path", prefix_options) diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index f73067688c..deaf1cdf03 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -129,9 +129,9 @@ module ActionDispatch options when nil, Hash routes = (options ? options.delete(:routes) : nil) || _routes - - if respond_to?(:env) && env && routes.equal?(env["action_dispatch.routes"]) - options[:skip_prefix] = true + if respond_to?(:env) && env + options[:skip_prefix] = true if routes.equal?(env["action_dispatch.routes"]) + options[:script_name] = env["ORIGINAL_SCRIPT_NAME"] if routes.equal?(env["action_dispatch.parent_routes"]) end routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys) -- cgit v1.2.3 From eedbf87d15b99a7cae38b0d8894fc39f1e70a81e Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 8 Jul 2010 15:42:40 +0200 Subject: New way of generating urls for Application from Engine. It's based specifying application's script_name with: Rails.application.default_url_options = {:script_name => "/foo"} default_url_options method is delegated to routes. If router used to generate url differs from the router passed via env it always overwrites :script_name with this value. --- actionpack/lib/action_dispatch/routing/route_set.rb | 4 ++-- actionpack/lib/action_dispatch/routing/url_for.rb | 15 ++++++++++----- 2 files changed, 12 insertions(+), 7 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index cb0373951f..7519d74183 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -280,10 +280,10 @@ module ActionDispatch # Yes plz - JP included do routes.install_helpers(self) - singleton_class.send(:define_method, :_routes) { routes } + singleton_class.send(:define_method, :_routes) { @_routes || routes } end - define_method(:_routes) { routes } + define_method(:_routes) { @_routes || routes } end helpers diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index deaf1cdf03..5da41df485 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -129,16 +129,21 @@ module ActionDispatch options when nil, Hash routes = (options ? options.delete(:routes) : nil) || _routes - if respond_to?(:env) && env - options[:skip_prefix] = true if routes.equal?(env["action_dispatch.routes"]) - options[:script_name] = env["ORIGINAL_SCRIPT_NAME"] if routes.equal?(env["action_dispatch.parent_routes"]) - end - routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys) + _with_routes(routes) do + routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys) + end else polymorphic_url(options) end end + + def _with_routes(routes) + old_routes, @_routes = @_routes, routes + yield + ensure + @_routes = old_routes + end end end end -- cgit v1.2.3 From 8a077089d9b7aa89cb56ef754b4540f411453375 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Fri, 9 Jul 2010 01:22:18 +0200 Subject: Get rid of :skip_prefix options in routes --- actionpack/lib/action_dispatch/routing/route_set.rb | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 7519d74183..6f182ae652 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -452,7 +452,7 @@ module ActionDispatch Generator.new(options, recall, self, extras).generate end - RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :port, :trailing_slash, :script_name, :skip_prefix, :routes] + RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :port, :trailing_slash, :script_name, :routes] def _generate_prefix(options = {}) nil @@ -478,15 +478,12 @@ module ActionDispatch rewritten_url << ":#{options.delete(:port)}" if options.key?(:port) end - path = [options.delete(:script_name)] - if !options.delete(:skip_prefix) - path << _generate_prefix(options) - end + script_name = options.delete(:script_name) + path = (script_name.blank? ? _generate_prefix(options) : script_name).to_s path_options = options.except(*RESERVED_OPTIONS) path_options = yield(path_options) if block_given? path << generate(path_options, path_segments || {}) - path = path.compact.join '' # ROUTES TODO: This can be called directly, so script_name should probably be set in the routes rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) -- cgit v1.2.3 From b53efd21059b9d829a6617fb5b2dd86754684c60 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 14 Jul 2010 00:46:42 +0200 Subject: Extended url_for to handle specifying which router should be used. A few examples: url_for Blog::Engine, :posts_path url_for Blog::Engine, @post url_for Blog::Engine, :action => "main", :controller => "index" --- .../action_dispatch/routing/polymorphic_routes.rb | 2 +- .../lib/action_dispatch/routing/route_set.rb | 24 ++++++------ actionpack/lib/action_dispatch/routing/url_for.rb | 45 ++++++++++++++-------- 3 files changed, 42 insertions(+), 29 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index fb2118a8d7..15ee7c8051 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -111,7 +111,7 @@ module ActionDispatch args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options end - send(named_route, *args) + url_for _routes.url_helpers.__send__("hash_for_#{named_route}", *args) end # Returns the path component of a URL for the given record. It uses diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 6f182ae652..c94b00257b 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -158,10 +158,17 @@ module ActionDispatch # We use module_eval to avoid leaks @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1 - def #{selector}(options = nil) # def hash_for_users_url(options = nil) - options ? #{options.inspect}.merge(options) : #{options.inspect} # options ? {:only_path=>false}.merge(options) : {:only_path=>false} - end # end - protected :#{selector} # protected :hash_for_users_url + def #{selector}(*args) + options = args.extract_options! + + if args.any? + options[:_positional_args] = args + options[:_positional_keys] = #{route.segment_keys.inspect} + end + + options ? #{options.inspect}.merge(options) : #{options.inspect} + end + protected :#{selector} END_EVAL helpers << selector end @@ -185,14 +192,7 @@ module ActionDispatch @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1 def #{selector}(*args) - options = #{hash_access_method}(args.extract_options!) - - if args.any? - options[:_positional_args] = args - options[:_positional_keys] = #{route.segment_keys.inspect} - end - - url_for(options) + url_for(#{hash_access_method}(*args)) end END_EVAL helpers << selector diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index 5da41df485..edcb7f9cbe 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -123,27 +123,40 @@ module ActionDispatch # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok' # url_for :controller => 'tasks', :action => 'testing', :trailing_slash=>true # => 'http://somehost.org/tasks/testing/' # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33' - def url_for(options = nil) - case options - when String - options - when nil, Hash - routes = (options ? options.delete(:routes) : nil) || _routes - - _with_routes(routes) do - routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys) + def url_for(*args) + if args.first.respond_to?(:routes) + app = args.shift + _with_routes(app.routes) do + if args.first.is_a? Symbol + named_route = args.shift + url_for _routes.url_helpers.__send__("hash_for_#{named_route}", *args) + else + url_for(*args) + end end else - polymorphic_url(options) + options = args.first + case options + when String + options + when nil, Hash + routes = (options ? options.delete(:routes) : nil) || _routes + _with_routes(routes) do + routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys) + end + else + polymorphic_url(options) + end end end - def _with_routes(routes) - old_routes, @_routes = @_routes, routes - yield - ensure - @_routes = old_routes - end + protected + def _with_routes(routes) + old_routes, @_routes = @_routes, routes + yield + ensure + @_routes = old_routes + end end end end -- cgit v1.2.3 From e9791bec823e42372eca095b946c93c1712a0613 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 15 Jul 2010 01:18:02 +0200 Subject: Routes refactoring: * added more tests for prefix generation * fixed bug with generating host for both prefix and url * refactored url_for method * organized tests for prefix generation --- actionpack/lib/action_dispatch/routing/mapper.rb | 3 +-- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- actionpack/lib/action_dispatch/routing/url_for.rb | 10 ++++------ 3 files changed, 6 insertions(+), 9 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 0e138524cd..88152ac290 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -288,8 +288,7 @@ module ActionDispatch _router = @set app.routes.class_eval do define_method :_generate_prefix do |options| - keys = _route.segment_keys + ActionDispatch::Routing::RouteSet::RESERVED_OPTIONS - prefix_options = options.slice(*keys) + prefix_options = options.slice(*_route.segment_keys) # we must actually delete prefix segment keys to avoid passing them to next url_for _route.segment_keys.each { |k| options.delete(k) } _router.url_helpers.send("#{name}_path", prefix_options) diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index c94b00257b..b3945a4963 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -452,7 +452,7 @@ module ActionDispatch Generator.new(options, recall, self, extras).generate end - RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :port, :trailing_slash, :script_name, :routes] + RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :port, :trailing_slash, :script_name] def _generate_prefix(options = {}) nil diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index edcb7f9cbe..30b456f3df 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -123,19 +123,17 @@ module ActionDispatch # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok' # url_for :controller => 'tasks', :action => 'testing', :trailing_slash=>true # => 'http://somehost.org/tasks/testing/' # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33' - def url_for(*args) - if args.first.respond_to?(:routes) - app = args.shift - _with_routes(app.routes) do + def url_for(options = nil, *args) + if options.respond_to?(:routes) + _with_routes(options.routes) do if args.first.is_a? Symbol named_route = args.shift - url_for _routes.url_helpers.__send__("hash_for_#{named_route}", *args) + url_for _routes.url_helpers.send("hash_for_#{named_route}", *args) else url_for(*args) end end else - options = args.first case options when String options -- cgit v1.2.3 From 6c95e0f879aafa5921cd7898d5951b9a926d3c9a Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Sun, 18 Jul 2010 19:49:51 +0200 Subject: Add mounted_helpers to routes mounted_helpers are a bit similar to url_helpers. They're automatically included in controllers for Rails.application and each of mounted Engines. Mounted helper allows to call url_for and named helpers for given application. Given Blog::Engine mounted as blog_engine, there are 2 helpers defined: app and blog_engine. You can call routes for app and engine using those helpers: app.root_url app.url_for(:controller => "foo") blog_engine.posts_path blog_engine.url_for(@post) --- actionpack/lib/action_dispatch/routing/mapper.rb | 5 +- .../lib/action_dispatch/routing/route_set.rb | 59 ++++++++++++++++++++++ actionpack/lib/action_dispatch/routing/url_for.rb | 28 +++------- 3 files changed, 69 insertions(+), 23 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 88152ac290..ef1bee106a 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -285,13 +285,14 @@ module ActionDispatch return unless app.respond_to?(:routes) _route = @set.named_routes.routes[name.to_sym] - _router = @set + _routes = @set + app.routes.define_mounted_helper(name) app.routes.class_eval do define_method :_generate_prefix do |options| prefix_options = options.slice(*_route.segment_keys) # we must actually delete prefix segment keys to avoid passing them to next url_for _route.segment_keys.each { |k| options.delete(k) } - _router.url_helpers.send("#{name}_path", prefix_options) + _routes.url_helpers.send("#{name}_path", prefix_options) end end end diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index b3945a4963..0f8bb5c504 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -261,6 +261,65 @@ module ActionDispatch named_routes.install(destinations, regenerate_code) end + class RoutesProxy + include ActionDispatch::Routing::UrlFor + + %w(url_options polymorphic_url polymorphic_path).each do |method| + self.class_eval <<-RUBY, __FILE__, __LINE__ +1 + def #{method}(*args) + scope.send(:_with_routes, routes) do + scope.#{method}(*args) + end + end + RUBY + end + + attr_accessor :scope, :routes + alias :_routes :routes + + def initialize(routes, scope) + @routes, @scope = routes, scope + end + + def method_missing(method, *args) + if routes.url_helpers.respond_to?(method) + self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{method}(*args) + options = args.extract_options! + args << url_options.merge((options || {}).symbolize_keys) + routes.url_helpers.#{method}(*args) + end + RUBY + send(method, *args) + else + super + end + end + end + + module MountedHelpers + end + + def mounted_helpers(name = nil) + define_mounted_helper(name) if name + MountedHelpers + end + + def define_mounted_helper(name, helpers = nil) + routes = self + MountedHelpers.class_eval do + define_method "_#{name}" do + RoutesProxy.new(routes, self) + end + end + + MountedHelpers.class_eval <<-RUBY + def #{name} + @#{name} ||= _#{name} + end + RUBY + end + def url_helpers @url_helpers ||= begin routes = self diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index 30b456f3df..19db730b6a 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -123,28 +123,14 @@ module ActionDispatch # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok' # url_for :controller => 'tasks', :action => 'testing', :trailing_slash=>true # => 'http://somehost.org/tasks/testing/' # url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33' - def url_for(options = nil, *args) - if options.respond_to?(:routes) - _with_routes(options.routes) do - if args.first.is_a? Symbol - named_route = args.shift - url_for _routes.url_helpers.send("hash_for_#{named_route}", *args) - else - url_for(*args) - end - end + def url_for(options = nil) + case options + when String + options + when nil, Hash + _routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys) else - case options - when String - options - when nil, Hash - routes = (options ? options.delete(:routes) : nil) || _routes - _with_routes(routes) do - routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys) - end - else - polymorphic_url(options) - end + polymorphic_url(options) end end -- cgit v1.2.3 From a132229d7b4382d9ffe8847fa58f469cb8f2ecfc Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 22 Jul 2010 22:11:32 +0200 Subject: Added ability to set asset_path for engines --- actionpack/lib/action_dispatch/testing/test_request.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb index b3e67f6e36..c587a36930 100644 --- a/actionpack/lib/action_dispatch/testing/test_request.rb +++ b/actionpack/lib/action_dispatch/testing/test_request.rb @@ -10,7 +10,7 @@ module ActionDispatch end def initialize(env = {}) - env = Rails.application.env_defaults.merge(env) if defined?(Rails.application) + env = Rails.application.env_config.merge(env) if defined?(Rails.application) super(DEFAULT_ENV.merge(env)) self.host = 'test.host' -- cgit v1.2.3 From 4cd6f7752658f0ec13d082fa2ee2a6f766410645 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Sat, 24 Jul 2010 17:43:33 +0200 Subject: We don't need delegating polymorphic_url and polymorphic_path anymore --- actionpack/lib/action_dispatch/routing/route_set.rb | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 0f8bb5c504..121e7c2c75 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -264,16 +264,6 @@ module ActionDispatch class RoutesProxy include ActionDispatch::Routing::UrlFor - %w(url_options polymorphic_url polymorphic_path).each do |method| - self.class_eval <<-RUBY, __FILE__, __LINE__ +1 - def #{method}(*args) - scope.send(:_with_routes, routes) do - scope.#{method}(*args) - end - end - RUBY - end - attr_accessor :scope, :routes alias :_routes :routes @@ -281,6 +271,12 @@ module ActionDispatch @routes, @scope = routes, scope end + def url_options + scope.send(:_with_routes, routes) do + scope.url_options + end + end + def method_missing(method, *args) if routes.url_helpers.respond_to?(method) self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1 -- cgit v1.2.3 From bfccbc6df91a3c24bbf99262383c6f1e9069e1dd Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Mon, 26 Jul 2010 17:05:04 +0200 Subject: Add Rails::Railtie.railtie_name method to allow setting custom name for railtie --- actionpack/lib/action_dispatch/routing/mapper.rb | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index ef1bee106a..b437d7a17d 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -277,8 +277,13 @@ module ActionDispatch private def app_name(app) return unless app.respond_to?(:routes) - class_name = app.class.is_a?(Class) ? app.name : app.class.name - ActiveSupport::Inflector.underscore(class_name).gsub("/", "_") + + if app.respond_to?(:railtie_name) + app.railtie_name + else + class_name = app.class.is_a?(Class) ? app.name : app.class.name + ActiveSupport::Inflector.underscore(class_name).gsub("/", "_") + end end def define_generate_prefix(app, name) -- cgit v1.2.3 From 401cd97923fb52c8f8c458b8cb276b338e0b20f3 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 29 Jul 2010 14:12:25 +0200 Subject: Modified ActionDispatch::Static to allow passing multiple roots --- .../lib/action_dispatch/middleware/static.rb | 60 ++++++++++++++++++---- 1 file changed, 50 insertions(+), 10 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index d7e88a54e4..c2d686f514 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -2,11 +2,43 @@ require 'rack/utils' module ActionDispatch class Static + class FileHandler + def initialize(at, root) + @at = at.chomp("/") + @file_server = ::Rack::File.new(root) + end + + def file_exist?(path) + (path = full_readable_path(path)) && File.file?(path) + end + + def directory_exist?(path) + (path = full_readable_path(path)) && File.directory?(path) + end + + def call(env) + env["PATH_INFO"].gsub!(/^#{@at}/, "") + @file_server.call(env) + end + + private + def includes_path?(path) + @at == "" || path =~ /^#{@at}/ + end + + def full_readable_path(path) + return unless includes_path?(path) + path = path.gsub(/^#{@at}/, "") + File.join(@file_server.root, ::Rack::Utils.unescape(path)) + end + end + FILE_METHODS = %w(GET HEAD).freeze - def initialize(app, root) + def initialize(app, roots) @app = app - @file_server = ::Rack::File.new(root) + roots = normalize_roots(roots) + @file_handlers = file_handlers(roots) end def call(env) @@ -14,15 +46,15 @@ module ActionDispatch method = env['REQUEST_METHOD'] if FILE_METHODS.include?(method) - if file_exist?(path) - return @file_server.call(env) + if file_handler = file_exist?(path) + return file_handler.call(env) else cached_path = directory_exist?(path) ? "#{path}/index" : path cached_path += ::ActionController::Base.page_cache_extension - if file_exist?(cached_path) + if file_handler = file_exist?(cached_path) env['PATH_INFO'] = cached_path - return @file_server.call(env) + return file_handler.call(env) end end end @@ -32,13 +64,21 @@ module ActionDispatch private def file_exist?(path) - full_path = File.join(@file_server.root, ::Rack::Utils.unescape(path)) - File.file?(full_path) && File.readable?(full_path) + @file_handlers.detect { |f| f.file_exist?(path) } end def directory_exist?(path) - full_path = File.join(@file_server.root, ::Rack::Utils.unescape(path)) - File.directory?(full_path) && File.readable?(full_path) + @file_handlers.detect { |f| f.directory_exist?(path) } + end + + def normalize_roots(roots) + roots.is_a?(Hash) ? roots : { "/" => roots.chomp("/") } + end + + def file_handlers(roots) + roots.map do |at, root| + FileHandler.new(at, root) + end end end end -- cgit v1.2.3 From 99131939316230065b4297573d080d1585e4e5a7 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Sat, 31 Jul 2010 11:27:08 +0200 Subject: For view_context we need to initialize RoutesProxy in context of controller, not view, quick fix, I need to dig into it later --- actionpack/lib/action_dispatch/routing/route_set.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 121e7c2c75..c67b0199ce 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -301,11 +301,13 @@ module ActionDispatch MountedHelpers end - def define_mounted_helper(name, helpers = nil) + def define_mounted_helper(name) + return if MountedHelpers.method_defined?(name) + routes = self MountedHelpers.class_eval do define_method "_#{name}" do - RoutesProxy.new(routes, self) + RoutesProxy.new(routes, (self.respond_to?(:controller) ? controller : self)) end end -- cgit v1.2.3 From befa77fc18ba54c1be89553466312039c1073f02 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Mon, 2 Aug 2010 02:55:01 +0200 Subject: Fix generating urls with mounted helpers in view context There were actually 2 problems with this one: * script_name was added to options as a string and then it was used in RouteSet#url_for with usage of <<, which was changing the original script_name * the second issue was with _with_routes method. It was called in RoutesProxy to modify _routes in view_context, but url_helpers in views is just delegating it to controller, so another _with_routes call is needed there --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index c67b0199ce..6e7e133cc5 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -307,7 +307,7 @@ module ActionDispatch routes = self MountedHelpers.class_eval do define_method "_#{name}" do - RoutesProxy.new(routes, (self.respond_to?(:controller) ? controller : self)) + RoutesProxy.new(routes, self) end end -- cgit v1.2.3 From 79bd92b7833d52b74f50259cf8a21f9b05f3e9e3 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Tue, 3 Aug 2010 19:36:53 +0200 Subject: Refactor ActionMailer to not use hide_actions --- actionpack/lib/action_dispatch/routing/route_set.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 6e7e133cc5..219fa37fcb 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -337,7 +337,12 @@ module ActionDispatch # Yes plz - JP included do routes.install_helpers(self) - singleton_class.send(:define_method, :_routes) { @_routes || routes } + singleton_class.send(:define_method, :_routes) { routes } + end + + def initialize(*) + @_routes = nil + super end define_method(:_routes) { @_routes || routes } -- cgit v1.2.3 From f3c703a32f6c7833705e46b8e14f172330a1c916 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 4 Aug 2010 16:20:56 +0200 Subject: Refactor RoutesProxy to avoid using _with_routes in helpers --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- actionpack/lib/action_dispatch/routing/url_for.rb | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 219fa37fcb..363bcbd2b0 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -307,7 +307,7 @@ module ActionDispatch routes = self MountedHelpers.class_eval do define_method "_#{name}" do - RoutesProxy.new(routes, self) + RoutesProxy.new(routes, self._routes_context) end end diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index 19db730b6a..e836cf7c8e 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -141,6 +141,10 @@ module ActionDispatch ensure @_routes = old_routes end + + def _routes_context + self + end end end end -- cgit v1.2.3 From 8fb9df535e9fcf4c117ffd3254027e0fe2425cb7 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 4 Aug 2010 23:00:33 +0200 Subject: Modified polymorphic_url to check for model's namespace This change allows using namespaced models with polymorphic_url, in the way that you would use them without namespace. Let's say that you have Blog::Post model in namespaced Engine. When you use polymorphic_path with Blog::Post instances, like in form_for(@post), it will look for blog_posts_path named url helper. As we are inside Blog::Engine, it's annoying to always use the prefix. With this commit, blog_ prefix will be removed and posts_path will be called. --- actionpack/lib/action_dispatch/routing/polymorphic_routes.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index 15ee7c8051..037b94b577 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -111,6 +111,10 @@ module ActionDispatch args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options end + if namespace = record.class.parents.detect { |n| n.respond_to?(:_railtie) } + named_route.sub!(/#{namespace._railtie.railtie_name}_/, '') + end + url_for _routes.url_helpers.__send__("hash_for_#{named_route}", *args) end -- cgit v1.2.3 From 00874a2009ce209d0c3a3cc2bf6c26b1bb15f3e5 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Sun, 22 Aug 2010 18:06:03 +0200 Subject: This was used only to clear warning in ActionMailer tests, it shouldn't be done like that --- actionpack/lib/action_dispatch/routing/route_set.rb | 5 ----- 1 file changed, 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 363bcbd2b0..c09c1fef6f 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -340,11 +340,6 @@ module ActionDispatch singleton_class.send(:define_method, :_routes) { routes } end - def initialize(*) - @_routes = nil - super - end - define_method(:_routes) { @_routes || routes } end -- cgit v1.2.3 From 8ec2175aee93ecfd928de67c0a125bccc5e1c152 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Mon, 23 Aug 2010 14:02:05 +0200 Subject: Added more tests for polymorphic_url with namespaced models and implemented missing use cases --- .../lib/action_dispatch/routing/polymorphic_routes.rb | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index 037b94b577..517936bc96 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -111,10 +111,6 @@ module ActionDispatch args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options end - if namespace = record.class.parents.detect { |n| n.respond_to?(:_railtie) } - named_route.sub!(/#{namespace._railtie.railtie_name}_/, '') - end - url_for _routes.url_helpers.__send__("hash_for_#{named_route}", *args) end @@ -159,7 +155,8 @@ module ActionDispatch if parent.is_a?(Symbol) || parent.is_a?(String) parent else - ActiveModel::Naming.plural(parent).singularize + str = ActiveModel::Naming.plural(parent).singularize + remove_namespace(str, parent) end end end @@ -168,6 +165,7 @@ module ActionDispatch route << record else route << ActiveModel::Naming.plural(record) + remove_namespace(route, record) route = [route.join("_").singularize] if inflection == :singular route << "index" if ActiveModel::Naming.uncountable?(record) && inflection == :plural end @@ -177,6 +175,13 @@ module ActionDispatch action_prefix(options) + route.join("_") end + def remove_namespace(string, parent) + if namespace = parent.class.parents.detect { |n| n.respond_to?(:_railtie) } + string.sub!(/#{namespace._railtie.railtie_name}_/, '') + end + string + end + def extract_record(record_or_hash_or_array) case record_or_hash_or_array when Array; record_or_hash_or_array.last -- cgit v1.2.3 From b1c66f060bba22d16abf6d24d3df762c240e367c Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 25 Aug 2010 13:41:56 +0200 Subject: Move RoutesProxy to separate file --- actionpack/lib/action_dispatch/routing.rb | 1 + .../lib/action_dispatch/routing/route_set.rb | 32 -------------------- .../lib/action_dispatch/routing/routes_proxy.rb | 35 ++++++++++++++++++++++ 3 files changed, 36 insertions(+), 32 deletions(-) create mode 100644 actionpack/lib/action_dispatch/routing/routes_proxy.rb (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index 0b9689dc88..b2b0f4c08e 100644 --- a/actionpack/lib/action_dispatch/routing.rb +++ b/actionpack/lib/action_dispatch/routing.rb @@ -268,6 +268,7 @@ module ActionDispatch autoload :Mapper, 'action_dispatch/routing/mapper' autoload :Route, 'action_dispatch/routing/route' autoload :RouteSet, 'action_dispatch/routing/route_set' + autoload :RoutesProxy, 'action_dispatch/routing/routes_proxy' autoload :UrlFor, 'action_dispatch/routing/url_for' autoload :PolymorphicRoutes, 'action_dispatch/routing/polymorphic_routes' diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index c09c1fef6f..0d83ca956b 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -261,38 +261,6 @@ module ActionDispatch named_routes.install(destinations, regenerate_code) end - class RoutesProxy - include ActionDispatch::Routing::UrlFor - - attr_accessor :scope, :routes - alias :_routes :routes - - def initialize(routes, scope) - @routes, @scope = routes, scope - end - - def url_options - scope.send(:_with_routes, routes) do - scope.url_options - end - end - - def method_missing(method, *args) - if routes.url_helpers.respond_to?(method) - self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def #{method}(*args) - options = args.extract_options! - args << url_options.merge((options || {}).symbolize_keys) - routes.url_helpers.#{method}(*args) - end - RUBY - send(method, *args) - else - super - end - end - end - module MountedHelpers end diff --git a/actionpack/lib/action_dispatch/routing/routes_proxy.rb b/actionpack/lib/action_dispatch/routing/routes_proxy.rb new file mode 100644 index 0000000000..f7d5f6397d --- /dev/null +++ b/actionpack/lib/action_dispatch/routing/routes_proxy.rb @@ -0,0 +1,35 @@ +module ActionDispatch + module Routing + class RoutesProxy #:nodoc: + include ActionDispatch::Routing::UrlFor + + attr_accessor :scope, :routes + alias :_routes :routes + + def initialize(routes, scope) + @routes, @scope = routes, scope + end + + def url_options + scope.send(:_with_routes, routes) do + scope.url_options + end + end + + def method_missing(method, *args) + if routes.url_helpers.respond_to?(method) + self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1 + def #{method}(*args) + options = args.extract_options! + args << url_options.merge((options || {}).symbolize_keys) + routes.url_helpers.#{method}(*args) + end + RUBY + send(method, *args) + else + super + end + end + end + end +end -- cgit v1.2.3 From 613cbe1f0075eed7ebf1ac521e99f652f6891330 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 25 Aug 2010 15:42:24 +0200 Subject: Add possibility to explicitly call engine's routes through polymorphic_routes, for example: polymorphic_url([blog, @post]) --- .../action_dispatch/routing/polymorphic_routes.rb | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index 517936bc96..e8ba1de40e 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -42,6 +42,18 @@ module ActionDispatch # # edit_polymorphic_path(@post) # => "/posts/1/edit" # polymorphic_path(@post, :format => :pdf) # => "/posts/1.pdf" + # + # == Using with mounted engines + # + # If you use mounted engine, there is a possibility that you will need to use + # polymorphic_url pointing at engine's routes. To do that, just pass proxy used + # to reach engine's routes as a first argument: + # + # For example: + # + # polymorphic_url([blog, @post]) # it will call blog.post_path(@post) + # form_for([blog, @post]) # => "/blog/posts/1 + # module PolymorphicRoutes # Constructs a call to a named RESTful route for the given record and returns the # resulting URL string. For example: @@ -78,6 +90,9 @@ module ActionDispatch def polymorphic_url(record_or_hash_or_array, options = {}) if record_or_hash_or_array.kind_of?(Array) record_or_hash_or_array = record_or_hash_or_array.compact + if record_or_hash_or_array.first.is_a?(ActionDispatch::Routing::RoutesProxy) + proxy = record_or_hash_or_array.shift + end record_or_hash_or_array = record_or_hash_or_array[0] if record_or_hash_or_array.size == 1 end @@ -111,7 +126,11 @@ module ActionDispatch args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options end - url_for _routes.url_helpers.__send__("hash_for_#{named_route}", *args) + if proxy + proxy.send(named_route, *args) + else + url_for _routes.url_helpers.__send__("hash_for_#{named_route}", *args) + end end # Returns the path component of a URL for the given record. It uses -- cgit v1.2.3 From 706a3223a303d56feeee2cc7601da1bd9f381243 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 25 Aug 2010 15:59:25 +0200 Subject: Add short note on using url_for instead of directly calling named route in polymorphic_url --- actionpack/lib/action_dispatch/routing/polymorphic_routes.rb | 3 +++ 1 file changed, 3 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index e8ba1de40e..ecc1651dfe 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -129,6 +129,9 @@ module ActionDispatch if proxy proxy.send(named_route, *args) else + # we need to use url_for, because polymorphic_url can be used in context of other than + # current routes (e.g. engine's routes). As named routes from engine are not included + # calling engine's named route directly would fail. url_for _routes.url_helpers.__send__("hash_for_#{named_route}", *args) end end -- cgit v1.2.3 From 2607def8621c41d5b0bee09e379ae26890b27f7d Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Tue, 31 Aug 2010 23:43:32 +0200 Subject: Use new ActiveModel::Naming.route_key in polymorphic_routes --- .../lib/action_dispatch/routing/polymorphic_routes.rb | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index ecc1651dfe..02ba5236ee 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -177,8 +177,7 @@ module ActionDispatch if parent.is_a?(Symbol) || parent.is_a?(String) parent else - str = ActiveModel::Naming.plural(parent).singularize - remove_namespace(str, parent) + ActiveModel::Naming.route_key(parent).singularize end end end @@ -186,8 +185,7 @@ module ActionDispatch if record.is_a?(Symbol) || record.is_a?(String) route << record else - route << ActiveModel::Naming.plural(record) - remove_namespace(route, record) + route << ActiveModel::Naming.route_key(record) route = [route.join("_").singularize] if inflection == :singular route << "index" if ActiveModel::Naming.uncountable?(record) && inflection == :plural end @@ -197,13 +195,6 @@ module ActionDispatch action_prefix(options) + route.join("_") end - def remove_namespace(string, parent) - if namespace = parent.class.parents.detect { |n| n.respond_to?(:_railtie) } - string.sub!(/#{namespace._railtie.railtie_name}_/, '') - end - string - end - def extract_record(record_or_hash_or_array) case record_or_hash_or_array when Array; record_or_hash_or_array.last -- cgit v1.2.3 From b8d6dc3c84321c751ab2ca8232e1e3fb332a844c Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 1 Sep 2010 19:17:47 +0200 Subject: Implemented RouteSet#default_scope, which allows to set the scope for the entire routes object --- actionpack/lib/action_dispatch/routing/mapper.rb | 6 ++++++ actionpack/lib/action_dispatch/routing/route_set.rb | 8 ++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index b437d7a17d..900900ee24 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -274,6 +274,12 @@ module ActionDispatch end alias_method :default_url_options, :default_url_options= + def with_default_scope(scope, &block) + scope(scope) do + instance_exec(&block) + end + end + private def app_name(app) return unless app.respond_to?(:routes) diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 0d83ca956b..107e44287d 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -199,7 +199,7 @@ module ActionDispatch end end - attr_accessor :set, :routes, :named_routes + attr_accessor :set, :routes, :named_routes, :default_scope attr_accessor :disable_clear_and_finalize, :resources_path_names attr_accessor :default_url_options, :request_class, :valid_conditions @@ -230,7 +230,11 @@ module ActionDispatch if block.arity == 1 mapper.instance_exec(DeprecatedMapper.new(self), &block) else - mapper.instance_exec(&block) + if default_scope + mapper.with_default_scope(default_scope, &block) + else + mapper.instance_exec(&block) + end end finalize! unless @disable_clear_and_finalize -- cgit v1.2.3 From 9f0a1ae14e2a9306605d7b572612ccf36fa8b2da Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Fri, 3 Sep 2010 12:48:21 +0200 Subject: Optimize ActionDispatch::Static --- .../lib/action_dispatch/middleware/static.rb | 86 +++++++++------------- 1 file changed, 35 insertions(+), 51 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index c2d686f514..e7e335df49 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -1,44 +1,43 @@ require 'rack/utils' module ActionDispatch - class Static - class FileHandler - def initialize(at, root) - @at = at.chomp("/") - @file_server = ::Rack::File.new(root) - end - - def file_exist?(path) - (path = full_readable_path(path)) && File.file?(path) - end - - def directory_exist?(path) - (path = full_readable_path(path)) && File.directory?(path) - end - - def call(env) - env["PATH_INFO"].gsub!(/^#{@at}/, "") - @file_server.call(env) - end + class FileHandler + def initialize(at, root) + @at, @root = at.chomp('/'), root.chomp('/') + @compiled_at = Regexp.compile(/^#{Regexp.escape(at)}/) unless @at.blank? + @compiled_root = Regexp.compile(/^#{Regexp.escape(root)}/) + @file_server = ::Rack::File.new(root) + + ext = ::ActionController::Base.page_cache_extension + @ext = "{,#{ext},/index#{ext}}" + end - private - def includes_path?(path) - @at == "" || path =~ /^#{@at}/ + def match?(path) + path = path.dup + if @compiled_at.blank? || path.sub!(@compiled_at, '') + full_path = File.join(@root, ::Rack::Utils.unescape(path)) + paths = "#{full_path}#{@ext}" + + matches = Dir[paths] + match = matches.detect { |m| File.file?(m) } + if match + match.sub!(@compiled_root, '') + match end + end + end - def full_readable_path(path) - return unless includes_path?(path) - path = path.gsub(/^#{@at}/, "") - File.join(@file_server.root, ::Rack::Utils.unescape(path)) - end + def call(env) + @file_server.call(env) end + end + class Static FILE_METHODS = %w(GET HEAD).freeze def initialize(app, roots) @app = app - roots = normalize_roots(roots) - @file_handlers = file_handlers(roots) + @file_handlers = create_file_handlers(roots) end def call(env) @@ -46,14 +45,9 @@ module ActionDispatch method = env['REQUEST_METHOD'] if FILE_METHODS.include?(method) - if file_handler = file_exist?(path) - return file_handler.call(env) - else - cached_path = directory_exist?(path) ? "#{path}/index" : path - cached_path += ::ActionController::Base.page_cache_extension - - if file_handler = file_exist?(cached_path) - env['PATH_INFO'] = cached_path + @file_handlers.each do |file_handler| + if match = file_handler.match?(path) + env["PATH_INFO"] = match return file_handler.call(env) end end @@ -63,22 +57,12 @@ module ActionDispatch end private - def file_exist?(path) - @file_handlers.detect { |f| f.file_exist?(path) } - end + def create_file_handlers(roots) + roots = { '' => roots } unless roots.is_a?(Hash) - def directory_exist?(path) - @file_handlers.detect { |f| f.directory_exist?(path) } - end - - def normalize_roots(roots) - roots.is_a?(Hash) ? roots : { "/" => roots.chomp("/") } - end - - def file_handlers(roots) roots.map do |at, root| - FileHandler.new(at, root) - end + FileHandler.new(at, root) if File.exist?(root) + end.compact end end end -- cgit v1.2.3 From c3c1a1e14859e6716970283caeab0c4c3720862e Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Fri, 3 Sep 2010 23:25:57 +0200 Subject: Do not use ActionController::Base.page_cache_extension in initialize to not load more ActiveSupport than we need --- actionpack/lib/action_dispatch/middleware/static.rb | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index e7e335df49..581cadbeb4 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -7,16 +7,13 @@ module ActionDispatch @compiled_at = Regexp.compile(/^#{Regexp.escape(at)}/) unless @at.blank? @compiled_root = Regexp.compile(/^#{Regexp.escape(root)}/) @file_server = ::Rack::File.new(root) - - ext = ::ActionController::Base.page_cache_extension - @ext = "{,#{ext},/index#{ext}}" end def match?(path) path = path.dup if @compiled_at.blank? || path.sub!(@compiled_at, '') full_path = File.join(@root, ::Rack::Utils.unescape(path)) - paths = "#{full_path}#{@ext}" + paths = "#{full_path}#{ext}" matches = Dir[paths] match = matches.detect { |m| File.file?(m) } @@ -30,6 +27,13 @@ module ActionDispatch def call(env) @file_server.call(env) end + + def ext + @ext ||= begin + ext = ::ActionController::Base.page_cache_extension + "{,#{ext},/index#{ext}}" + end + end end class Static -- cgit v1.2.3 From b3eb26a161acb23781e55fc6c37b948f160cd9b5 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 5 Aug 2010 15:44:23 +0200 Subject: Removed deprecated RouteSet API, still many tests fail --- actionpack/lib/action_dispatch/routing.rb | 1 - actionpack/lib/action_dispatch/routing/mapper.rb | 7 +------ actionpack/lib/action_dispatch/routing/route_set.rb | 12 +++--------- 3 files changed, 4 insertions(+), 16 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index b2b0f4c08e..8810227a59 100644 --- a/actionpack/lib/action_dispatch/routing.rb +++ b/actionpack/lib/action_dispatch/routing.rb @@ -264,7 +264,6 @@ module ActionDispatch # Target specific controllers by prefixing the command with CONTROLLER=x. # module Routing - autoload :DeprecatedMapper, 'action_dispatch/routing/deprecated_mapper' autoload :Mapper, 'action_dispatch/routing/mapper' autoload :Route, 'action_dispatch/routing/route' autoload :RouteSet, 'action_dispatch/routing/route_set' diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 900900ee24..cee3fd880c 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -443,11 +443,6 @@ module ActionDispatch options = args.extract_options! options = options.dup - if name_prefix = options.delete(:name_prefix) - options[:as] ||= name_prefix - ActiveSupport::Deprecation.warn ":name_prefix was deprecated in the new router syntax. Use :as instead.", caller - end - options[:path] = args.first if args.first.is_a?(String) recover = {} @@ -770,7 +765,7 @@ module ActionDispatch end resource_scope(Resource.new(resources.pop, options)) do - yield if block_given? + instance_eval(&block) if block_given? collection_scope do get :index if parent_resource.actions.include?(:index) diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 107e44287d..956bd2e719 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -1,7 +1,6 @@ require 'rack/mount' require 'forwardable' require 'active_support/core_ext/object/to_query' -require 'action_dispatch/routing/deprecated_mapper' module ActionDispatch module Routing @@ -211,7 +210,6 @@ module ActionDispatch self.routes = [] self.named_routes = NamedRouteCollection.new self.resources_path_names = self.class.default_resources_path_names.dup - self.controller_namespaces = Set.new self.default_url_options = {} self.request_class = request_class @@ -227,14 +225,10 @@ module ActionDispatch clear! unless @disable_clear_and_finalize mapper = Mapper.new(self) - if block.arity == 1 - mapper.instance_exec(DeprecatedMapper.new(self), &block) + if default_scope + mapper.with_default_scope(default_scope, &block) else - if default_scope - mapper.with_default_scope(default_scope, &block) - else - mapper.instance_exec(&block) - end + mapper.instance_exec(&block) end finalize! unless @disable_clear_and_finalize -- cgit v1.2.3 From 8958f332bbb552e87fd9f8c78dd11bdeab7897fc Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 5 Aug 2010 23:16:08 +0200 Subject: Implemented resources :foos, :except => :all option --- actionpack/lib/action_dispatch/routing/mapper.rb | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index cee3fd880c..f52fb91e97 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -611,9 +611,18 @@ module ActionDispatch end def actions - if only = @options[:only] + only, except = @options.values_at(:only, :except) + if only == :all || except == :none + only = nil + except = [] + elsif only == :none || except == :all + only = [] + except = nil + end + + if only Array(only).map(&:to_sym) - elsif except = @options[:except] + elsif except default_actions - Array(except).map(&:to_sym) else default_actions -- cgit v1.2.3 From 3088b4f84f802fb84c4750ce25d8fe57c6c0a79e Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 5 Aug 2010 23:58:12 +0200 Subject: raise error on invalid HTTP methods or :head passed with :via in routes --- actionpack/lib/action_dispatch/routing/mapper.rb | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f52fb91e97..d53c10e5f3 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -898,6 +898,15 @@ module ActionDispatch return self end + via = Array.wrap(options[:via]).map(&:to_sym) + if via.include?(:head) + raise ArgumentError, "HTTP method HEAD is invalid in route conditions. Rails processes HEAD requests the same as GETs, returning just the response headers" + end + + unless (invalid = via - HTTP_METHODS).empty? + raise ArgumentError, "Invalid HTTP method (#{invalid.join(', ')}) specified in :via" + end + on = options.delete(:on) if VALID_ON_OPTIONS.include?(on) args.push(options) -- cgit v1.2.3 From ca3936dbd691538d97d8dbe2bc1d64c21dc7db0e Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Fri, 6 Aug 2010 18:03:55 +0200 Subject: Ported missing functionality from Rails 2.3.x, raise error on wrong regexps in :constraints in routes --- actionpack/lib/action_dispatch/routing/mapper.rb | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index d53c10e5f3..fdcfe26781 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -113,6 +113,15 @@ module ActionDispatch @requirements ||= (@options[:constraints].is_a?(Hash) ? @options[:constraints] : {}).tap do |requirements| requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints] @options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) } + + requirements.each do |_, requirement| + if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z} + raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}" + end + if requirement.multiline? + raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}" + end + end end end -- cgit v1.2.3 From faba03850acc8adaf9c51004193c85191a4623e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Strza=C5=82kowski?= Date: Mon, 9 Aug 2010 22:49:15 +0200 Subject: Removed deprecated_mapper - we don't need it anymore --- .../action_dispatch/routing/deprecated_mapper.rb | 525 --------------------- 1 file changed, 525 deletions(-) delete mode 100644 actionpack/lib/action_dispatch/routing/deprecated_mapper.rb (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb b/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb deleted file mode 100644 index e04062ce8b..0000000000 --- a/actionpack/lib/action_dispatch/routing/deprecated_mapper.rb +++ /dev/null @@ -1,525 +0,0 @@ -require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/object/with_options' -require 'active_support/core_ext/object/try' - -module ActionDispatch - module Routing - class RouteSet - attr_accessor :controller_namespaces - - CONTROLLER_REGEXP = /[_a-zA-Z0-9]+/ - - def controller_constraints - @controller_constraints ||= begin - namespaces = controller_namespaces + in_memory_controller_namespaces - source = namespaces.map { |ns| "#{Regexp.escape(ns)}/#{CONTROLLER_REGEXP.source}" } - source << CONTROLLER_REGEXP.source - Regexp.compile(source.sort.reverse.join('|')) - end - end - - def in_memory_controller_namespaces - namespaces = Set.new - ActionController::Base.descendants.each do |klass| - next if klass.anonymous? - namespaces << klass.name.underscore.split('/')[0...-1].join('/') - end - namespaces.delete('') - namespaces - end - end - - class DeprecatedMapper #:nodoc: - def initialize(set) #:nodoc: - ActiveSupport::Deprecation.warn "You are using the old router DSL which will be removed in Rails 3.1. " << - "Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/" - @set = set - end - - def connect(path, options = {}) - options = options.dup - - if conditions = options.delete(:conditions) - conditions = conditions.dup - method = [conditions.delete(:method)].flatten.compact - method.map! { |m| - m = m.to_s.upcase - - if m == "HEAD" - raise ArgumentError, "HTTP method HEAD is invalid in route conditions. Rails processes HEAD requests the same as GETs, returning just the response headers" - end - - unless HTTP_METHODS.include?(m.downcase.to_sym) - raise ArgumentError, "Invalid HTTP method specified in route conditions" - end - - m - } - - if method.length > 1 - method = Regexp.union(*method) - elsif method.length == 1 - method = method.first - else - method = nil - end - end - - path_prefix = options.delete(:path_prefix) - name_prefix = options.delete(:name_prefix) - namespace = options.delete(:namespace) - - name = options.delete(:_name) - name = "#{name_prefix}#{name}" if name_prefix - - requirements = options.delete(:requirements) || {} - defaults = options.delete(:defaults) || {} - options.each do |k, v| - if v.is_a?(Regexp) - if value = options.delete(k) - requirements[k.to_sym] = value - end - else - value = options.delete(k) - defaults[k.to_sym] = value.is_a?(Symbol) ? value : value.to_param - end - end - - requirements.each do |_, requirement| - if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z} - raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}" - end - if requirement.multiline? - raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}" - end - end - - requirements[:controller] ||= @set.controller_constraints - - if defaults[:controller] - defaults[:action] ||= 'index' - defaults[:controller] = defaults[:controller].to_s - defaults[:controller] = "#{namespace}#{defaults[:controller]}" if namespace - end - - if defaults[:action] - defaults[:action] = defaults[:action].to_s - end - - if path.is_a?(String) - path = "#{path_prefix}/#{path}" if path_prefix - path = path.gsub('.:format', '(.:format)') - path = optionalize_trailing_dynamic_segments(path, requirements, defaults) - glob = $1.to_sym if path =~ /\/\*(\w+)$/ - path = ::Rack::Mount::Utils.normalize_path(path) - - if glob && !defaults[glob].blank? - raise ActionController::RoutingError, "paths cannot have non-empty default values" - end - end - - app = Routing::RouteSet::Dispatcher.new(:defaults => defaults, :glob => glob) - - conditions = {} - conditions[:request_method] = method if method - conditions[:path_info] = path if path - - @set.add_route(app, conditions, requirements, defaults, name) - end - - def optionalize_trailing_dynamic_segments(path, requirements, defaults) #:nodoc: - path = (path =~ /^\//) ? path.dup : "/#{path}" - optional, segments = true, [] - - required_segments = requirements.keys - required_segments -= defaults.keys.compact - - old_segments = path.split('/') - old_segments.shift - length = old_segments.length - - old_segments.reverse.each_with_index do |segment, index| - required_segments.each do |required| - if segment =~ /#{required}/ - optional = false - break - end - end - - if optional - if segment == ":id" && segments.include?(":action") - optional = false - elsif segment == ":controller" || segment == ":action" || segment == ":id" - # Ignore - elsif !(segment =~ /^:\w+$/) && - !(segment =~ /^:\w+\(\.:format\)$/) - optional = false - elsif segment =~ /^:(\w+)$/ - if defaults.has_key?($1.to_sym) - defaults.delete($1.to_sym) if defaults[$1.to_sym].nil? - else - optional = false - end - end - end - - if optional && index < length - 1 - segments.unshift('(/', segment) - segments.push(')') - elsif optional - segments.unshift('/(', segment) - segments.push(')') - else - segments.unshift('/', segment) - end - end - - segments.join - end - private :optionalize_trailing_dynamic_segments - - # Creates a named route called "root" for matching the root level request. - def root(options = {}) - if options.is_a?(Symbol) - if source_route = @set.named_routes.routes[options] - options = source_route.defaults.merge({ :conditions => source_route.conditions }) - end - end - named_route("root", '', options) - end - - def named_route(name, path, options = {}) #:nodoc: - options[:_name] = name - connect(path, options) - end - - def namespace(name, options = {}, &block) - if options[:namespace] - with_options({:path_prefix => "#{options.delete(:path_prefix)}/#{name}", :name_prefix => "#{options.delete(:name_prefix)}#{name}_", :namespace => "#{options.delete(:namespace)}#{name}/" }.merge(options), &block) - else - with_options({:path_prefix => name, :name_prefix => "#{name}_", :namespace => "#{name}/" }.merge(options), &block) - end - end - - def method_missing(route_name, *args, &proc) #:nodoc: - super unless args.length >= 1 && proc.nil? - named_route(route_name, *args) - end - - INHERITABLE_OPTIONS = :namespace, :shallow - - class Resource #:nodoc: - DEFAULT_ACTIONS = :index, :create, :new, :edit, :show, :update, :destroy - - attr_reader :collection_methods, :member_methods, :new_methods - attr_reader :path_prefix, :name_prefix, :path_segment - attr_reader :plural, :singular - attr_reader :options, :defaults - - def initialize(entities, options, defaults) - @plural ||= entities - @singular ||= options[:singular] || plural.to_s.singularize - @path_segment = options.delete(:as) || @plural - - @options = options - @defaults = defaults - - arrange_actions - add_default_actions - set_allowed_actions - set_prefixes - end - - def controller - @controller ||= "#{options[:namespace]}#{(options[:controller] || plural).to_s}" - end - - def requirements(with_id = false) - @requirements ||= @options[:requirements] || {} - @id_requirement ||= { :id => @requirements.delete(:id) || /[^#{Routing::SEPARATORS.join}]+/ } - - with_id ? @requirements.merge(@id_requirement) : @requirements - end - - def conditions - @conditions ||= @options[:conditions] || {} - end - - def path - @path ||= "#{path_prefix}/#{path_segment}" - end - - def new_path - new_action = self.options[:path_names][:new] if self.options[:path_names] - new_action ||= self.defaults[:path_names][:new] - @new_path ||= "#{path}/#{new_action}" - end - - def shallow_path_prefix - @shallow_path_prefix ||= @options[:shallow] ? @options[:namespace].try(:sub, /\/$/, '') : path_prefix - end - - def member_path - @member_path ||= "#{shallow_path_prefix}/#{path_segment}/:id" - end - - def nesting_path_prefix - @nesting_path_prefix ||= "#{shallow_path_prefix}/#{path_segment}/:#{singular}_id" - end - - def shallow_name_prefix - @shallow_name_prefix ||= @options[:shallow] ? @options[:namespace].try(:gsub, /\//, '_') : name_prefix - end - - def nesting_name_prefix - "#{shallow_name_prefix}#{singular}_" - end - - def action_separator - @action_separator ||= ActionController::Base.resource_action_separator - end - - def uncountable? - @singular.to_s == @plural.to_s - end - - def has_action?(action) - !DEFAULT_ACTIONS.include?(action) || action_allowed?(action) - end - - protected - def arrange_actions - @collection_methods = arrange_actions_by_methods(options.delete(:collection)) - @member_methods = arrange_actions_by_methods(options.delete(:member)) - @new_methods = arrange_actions_by_methods(options.delete(:new)) - end - - def add_default_actions - add_default_action(member_methods, :get, :edit) - add_default_action(new_methods, :get, :new) - end - - def set_allowed_actions - only, except = @options.values_at(:only, :except) - @allowed_actions ||= {} - - if only == :all || except == :none - only = nil - except = [] - elsif only == :none || except == :all - only = [] - except = nil - end - - if only - @allowed_actions[:only] = Array(only).map {|a| a.to_sym } - elsif except - @allowed_actions[:except] = Array(except).map {|a| a.to_sym } - end - end - - def action_allowed?(action) - only, except = @allowed_actions.values_at(:only, :except) - (!only || only.include?(action)) && (!except || !except.include?(action)) - end - - def set_prefixes - @path_prefix = options.delete(:path_prefix) - @name_prefix = options.delete(:name_prefix) - end - - def arrange_actions_by_methods(actions) - (actions || {}).inject({}) do |flipped_hash, (key, value)| - (flipped_hash[value] ||= []) << key - flipped_hash - end - end - - def add_default_action(collection, method, action) - (collection[method] ||= []).unshift(action) - end - end - - class SingletonResource < Resource #:nodoc: - def initialize(entity, options, defaults) - @singular = @plural = entity - options[:controller] ||= @singular.to_s.pluralize - super - end - - alias_method :shallow_path_prefix, :path_prefix - alias_method :shallow_name_prefix, :name_prefix - alias_method :member_path, :path - alias_method :nesting_path_prefix, :path - end - - def resources(*entities, &block) - options = entities.extract_options! - entities.each { |entity| map_resource(entity, options.dup, &block) } - end - - def resource(*entities, &block) - options = entities.extract_options! - entities.each { |entity| map_singleton_resource(entity, options.dup, &block) } - end - - private - def map_resource(entities, options = {}, &block) - resource = Resource.new(entities, options, :path_names => @set.resources_path_names) - - with_options :controller => resource.controller do |map| - map_associations(resource, options) - - if block_given? - with_options(options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix), &block) - end - - map_collection_actions(map, resource) - map_default_collection_actions(map, resource) - map_new_actions(map, resource) - map_member_actions(map, resource) - end - end - - def map_singleton_resource(entities, options = {}, &block) - resource = SingletonResource.new(entities, options, :path_names => @set.resources_path_names) - - with_options :controller => resource.controller do |map| - map_associations(resource, options) - - if block_given? - with_options(options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix), &block) - end - - map_collection_actions(map, resource) - map_new_actions(map, resource) - map_member_actions(map, resource) - map_default_singleton_actions(map, resource) - end - end - - def map_associations(resource, options) - map_has_many_associations(resource, options.delete(:has_many), options) if options[:has_many] - - path_prefix = "#{options.delete(:path_prefix)}#{resource.nesting_path_prefix}" - name_prefix = "#{options.delete(:name_prefix)}#{resource.nesting_name_prefix}" - - Array(options[:has_one]).each do |association| - resource(association, options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => path_prefix, :name_prefix => name_prefix)) - end - end - - def map_has_many_associations(resource, associations, options) - case associations - when Hash - associations.each do |association,has_many| - map_has_many_associations(resource, association, options.merge(:has_many => has_many)) - end - when Array - associations.each do |association| - map_has_many_associations(resource, association, options) - end - when Symbol, String - resources(associations, options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :has_many => options[:has_many])) - else - end - end - - def map_collection_actions(map, resource) - resource.collection_methods.each do |method, actions| - actions.each do |action| - [method].flatten.each do |m| - action_path = resource.options[:path_names][action] if resource.options[:path_names].is_a?(Hash) - action_path ||= action - - map_resource_routes(map, resource, action, "#{resource.path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.name_prefix}#{resource.plural}", m) - end - end - end - end - - def map_default_collection_actions(map, resource) - index_route_name = "#{resource.name_prefix}#{resource.plural}" - - if resource.uncountable? - index_route_name << "_index" - end - - map_resource_routes(map, resource, :index, resource.path, index_route_name) - map_resource_routes(map, resource, :create, resource.path, index_route_name) - end - - def map_default_singleton_actions(map, resource) - map_resource_routes(map, resource, :create, resource.path, "#{resource.shallow_name_prefix}#{resource.singular}") - end - - def map_new_actions(map, resource) - resource.new_methods.each do |method, actions| - actions.each do |action| - route_path = resource.new_path - route_name = "new_#{resource.name_prefix}#{resource.singular}" - - unless action == :new - route_path = "#{route_path}#{resource.action_separator}#{action}" - route_name = "#{action}_#{route_name}" - end - - map_resource_routes(map, resource, action, route_path, route_name, method) - end - end - end - - def map_member_actions(map, resource) - resource.member_methods.each do |method, actions| - actions.each do |action| - [method].flatten.each do |m| - action_path = resource.options[:path_names][action] if resource.options[:path_names].is_a?(Hash) - action_path ||= @set.resources_path_names[action] || action - - map_resource_routes(map, resource, action, "#{resource.member_path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", m, { :force_id => true }) - end - end - end - - route_path = "#{resource.shallow_name_prefix}#{resource.singular}" - map_resource_routes(map, resource, :show, resource.member_path, route_path) - map_resource_routes(map, resource, :update, resource.member_path, route_path) - map_resource_routes(map, resource, :destroy, resource.member_path, route_path) - end - - def map_resource_routes(map, resource, action, route_path, route_name = nil, method = nil, resource_options = {} ) - if resource.has_action?(action) - action_options = action_options_for(action, resource, method, resource_options) - formatted_route_path = "#{route_path}.:format" - - if route_name && @set.named_routes[route_name.to_sym].nil? - map.named_route(route_name, formatted_route_path, action_options) - else - map.connect(formatted_route_path, action_options) - end - end - end - - def add_conditions_for(conditions, method) - {:conditions => conditions.dup}.tap do |options| - options[:conditions][:method] = method unless method == :any - end - end - - def action_options_for(action, resource, method = nil, resource_options = {}) - default_options = { :action => action.to_s } - require_id = !resource.kind_of?(SingletonResource) - force_id = resource_options[:force_id] && !resource.kind_of?(SingletonResource) - - case default_options[:action] - when "index", "new"; default_options.merge(add_conditions_for(resource.conditions, method || :get)).merge(resource.requirements) - when "create"; default_options.merge(add_conditions_for(resource.conditions, method || :post)).merge(resource.requirements) - when "show", "edit"; default_options.merge(add_conditions_for(resource.conditions, method || :get)).merge(resource.requirements(require_id)) - when "update"; default_options.merge(add_conditions_for(resource.conditions, method || :put)).merge(resource.requirements(require_id)) - when "destroy"; default_options.merge(add_conditions_for(resource.conditions, method || :delete)).merge(resource.requirements(require_id)) - else default_options.merge(add_conditions_for(resource.conditions, method)).merge(resource.requirements(force_id)) - end - end - end - end -end -- cgit v1.2.3 From 8a3461b8c1cb6371c809618420de9e69a71d183f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 5 Sep 2010 15:59:25 +0200 Subject: Remove a few tests from old router that do not make sense with the new one. --- actionpack/lib/action_dispatch/routing/mapper.rb | 24 +++--------------------- 1 file changed, 3 insertions(+), 21 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index fdcfe26781..8a161b0837 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -620,18 +620,9 @@ module ActionDispatch end def actions - only, except = @options.values_at(:only, :except) - if only == :all || except == :none - only = nil - except = [] - elsif only == :none || except == :all - only = [] - except = nil - end - - if only + if only = @options[:only] Array(only).map(&:to_sym) - elsif except + elsif except = @options[:except] default_actions - Array(except).map(&:to_sym) else default_actions @@ -783,7 +774,7 @@ module ActionDispatch end resource_scope(Resource.new(resources.pop, options)) do - instance_eval(&block) if block_given? + yield if block_given? collection_scope do get :index if parent_resource.actions.include?(:index) @@ -907,15 +898,6 @@ module ActionDispatch return self end - via = Array.wrap(options[:via]).map(&:to_sym) - if via.include?(:head) - raise ArgumentError, "HTTP method HEAD is invalid in route conditions. Rails processes HEAD requests the same as GETs, returning just the response headers" - end - - unless (invalid = via - HTTP_METHODS).empty? - raise ArgumentError, "Invalid HTTP method (#{invalid.join(', ')}) specified in :via" - end - on = options.delete(:on) if VALID_ON_OPTIONS.include?(on) args.push(options) -- cgit v1.2.3 From 9532d746a998f790a5c0c61caff17beeb43f39f0 Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Sun, 5 Sep 2010 22:59:41 -0300 Subject: Cleanup deprecations in Action Dispatch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/url.rb | 9 +-- actionpack/lib/action_dispatch/middleware/stack.rb | 5 -- .../lib/action_dispatch/testing/test_response.rb | 93 ---------------------- 3 files changed, 1 insertion(+), 106 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index f6375902f6..38f46fa120 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -95,13 +95,6 @@ module ActionDispatch subdomains(tld_length).join('.') end - # Returns the request URI, accounting for server idiosyncrasies. - # WEBrick includes the full \URL. IIS leaves REQUEST_URI blank. - def request_uri - ActiveSupport::Deprecation.warn "Using #request_uri is deprecated. Use fullpath instead.", caller - fullpath - end - private def named_host?(host) @@ -109,4 +102,4 @@ module ActionDispatch end end end -end \ No newline at end of file +end diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 6f243574e4..db7f342bc5 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -69,11 +69,6 @@ module ActionDispatch push(middleware) end - def active - ActiveSupport::Deprecation.warn "All middlewares in the chain are active since the laziness " << - "was removed from the middleware stack", caller - end - def build(app = nil, &block) app ||= block raise "MiddlewareStack#build requires an app" unless app diff --git a/actionpack/lib/action_dispatch/testing/test_response.rb b/actionpack/lib/action_dispatch/testing/test_response.rb index 44fb1bde99..926034762f 100644 --- a/actionpack/lib/action_dispatch/testing/test_response.rb +++ b/actionpack/lib/action_dispatch/testing/test_response.rb @@ -14,99 +14,6 @@ module ActionDispatch end end - module DeprecatedHelpers - def template - ActiveSupport::Deprecation.warn("response.template has been deprecated. Use controller.template instead", caller) - @template - end - attr_writer :template - - def session - ActiveSupport::Deprecation.warn("response.session has been deprecated. Use request.session instead", caller) - @request.session - end - - def assigns - ActiveSupport::Deprecation.warn("response.assigns has been deprecated. Use controller.assigns instead", caller) - @template.controller.assigns - end - - def layout - ActiveSupport::Deprecation.warn("response.layout has been deprecated. Use template.layout instead", caller) - @template.layout - end - - def redirected_to - ::ActiveSupport::Deprecation.warn("response.redirected_to is deprecated. Use response.redirect_url instead", caller) - redirect_url - end - - def redirect_url_match?(pattern) - ::ActiveSupport::Deprecation.warn("response.redirect_url_match? is deprecated. Use assert_match(/foo/, response.redirect_url) instead", caller) - return false if redirect_url.nil? - p = Regexp.new(pattern) if pattern.class == String - p = pattern if pattern.class == Regexp - return false if p.nil? - p.match(redirect_url) != nil - end - - # Returns the template of the file which was used to - # render this response (or nil) - def rendered - ActiveSupport::Deprecation.warn("response.rendered has been deprecated. Use template.rendered instead", caller) - @template.instance_variable_get(:@_rendered) - end - - # A shortcut to the flash. Returns an empty hash if no session flash exists. - def flash - ActiveSupport::Deprecation.warn("response.flash has been deprecated. Use request.flash instead", caller) - request.session['flash'] || {} - end - - # Do we have a flash? - def has_flash? - ActiveSupport::Deprecation.warn("response.has_flash? has been deprecated. Use flash.any? instead", caller) - !flash.empty? - end - - # Do we have a flash that has contents? - def has_flash_with_contents? - ActiveSupport::Deprecation.warn("response.has_flash_with_contents? has been deprecated. Use flash.any? instead", caller) - !flash.empty? - end - - # Does the specified flash object exist? - def has_flash_object?(name=nil) - ActiveSupport::Deprecation.warn("response.has_flash_object? has been deprecated. Use flash[name] instead", caller) - !flash[name].nil? - end - - # Does the specified object exist in the session? - def has_session_object?(name=nil) - ActiveSupport::Deprecation.warn("response.has_session_object? has been deprecated. Use session[name] instead", caller) - !session[name].nil? - end - - # A shortcut to the template.assigns - def template_objects - ActiveSupport::Deprecation.warn("response.template_objects has been deprecated. Use template.assigns instead", caller) - @template.assigns || {} - end - - # Does the specified template object exist? - def has_template_object?(name=nil) - ActiveSupport::Deprecation.warn("response.has_template_object? has been deprecated. Use tempate.assigns[name].nil? instead", caller) - !template_objects[name].nil? - end - - # Returns binary content (downloadable file), converted to a String - def binary_content - ActiveSupport::Deprecation.warn("response.binary_content has been deprecated. Use response.body instead", caller) - body - end - end - include DeprecatedHelpers - # Was the response successful? def success? (200..299).include?(response_code) -- cgit v1.2.3 From 18aee333359a4dea6847754f3055ce223aa2474c Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Mon, 6 Sep 2010 20:47:25 +0200 Subject: Do not require passing :app to mounted helpers, it's actually useless and not DRY --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 956bd2e719..19a277a18c 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -262,7 +262,7 @@ module ActionDispatch module MountedHelpers end - def mounted_helpers(name = nil) + def mounted_helpers(name = :app) define_mounted_helper(name) if name MountedHelpers end -- cgit v1.2.3 From 6258f7c972f0dcf85916a0ac9ce3d34460201353 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Tue, 7 Sep 2010 14:53:37 +0200 Subject: Change app to main_app in mounted_helpers --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 19a277a18c..835ba03784 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -262,7 +262,7 @@ module ActionDispatch module MountedHelpers end - def mounted_helpers(name = :app) + def mounted_helpers(name = :main_app) define_mounted_helper(name) if name MountedHelpers end -- cgit v1.2.3 From 7fae0aa4ac116bcbf522a9a4f19972c653d366fa Mon Sep 17 00:00:00 2001 From: Simon Jefford Date: Tue, 27 Jul 2010 15:39:28 +0100 Subject: Add configuration option for tld length --- actionpack/lib/action_dispatch/http/url.rb | 10 ++++++---- actionpack/lib/action_dispatch/railtie.rb | 10 ++++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 38f46fa120..2e39d0dbc2 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -1,7 +1,9 @@ module ActionDispatch module Http module URL - # Returns the complete \URL used for this request. + mattr_accessor :tld_length + + # Returns the complete URL used for this request. def url protocol + host_with_port + fullpath end @@ -85,13 +87,13 @@ module ActionDispatch # returned for "dev.www.rubyonrails.org". You can specify a different tld_length, # such as 2 to catch ["www"] instead of ["www", "rubyonrails"] # in "www.rubyonrails.co.uk". - def subdomains(tld_length = 1) + def subdomains(tld_length = @@tld_length) return [] unless named_host?(host) parts = host.split('.') parts[0..-(tld_length+2)] end - def subdomain(tld_length = 1) + def subdomain(tld_length = @@tld_length) subdomains(tld_length).join('.') end @@ -102,4 +104,4 @@ module ActionDispatch end end end -end +end \ No newline at end of file diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb index ed066ad75e..c202fee990 100644 --- a/actionpack/lib/action_dispatch/railtie.rb +++ b/actionpack/lib/action_dispatch/railtie.rb @@ -8,5 +8,15 @@ module ActionDispatch config.action_dispatch.ip_spoofing_check = true config.action_dispatch.show_exceptions = true config.action_dispatch.best_standards_support = true + config.action_dispatch.tld_length = 1 + + # Prepare dispatcher callbacks and run 'prepare' callbacks + initializer "action_dispatch.prepare_dispatcher" do |app| + ActionDispatch::Callbacks.to_prepare { app.routes_reloader.execute_if_updated } + end + + initializer "action_dispatch.configure" do |app| + ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length + end end end -- cgit v1.2.3 From 8b66c91c51bfc163fa8c2af019a1a6f64c3e6a53 Mon Sep 17 00:00:00 2001 From: Mikel Lindsaar Date: Sat, 11 Sep 2010 20:45:40 +1000 Subject: Partial revert of commit #7fae0aa4ac116 removing action_dispatch.prepare_dispatcher per commit #48bf667a8b1 See line note: http://github.com/rails/rails/commit/7fae0aa4ac116bcbf522a9a4f19972c653d366fa#commitcomment-145148 --- actionpack/lib/action_dispatch/railtie.rb | 5 ----- 1 file changed, 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb index c202fee990..69537be876 100644 --- a/actionpack/lib/action_dispatch/railtie.rb +++ b/actionpack/lib/action_dispatch/railtie.rb @@ -10,11 +10,6 @@ module ActionDispatch config.action_dispatch.best_standards_support = true config.action_dispatch.tld_length = 1 - # Prepare dispatcher callbacks and run 'prepare' callbacks - initializer "action_dispatch.prepare_dispatcher" do |app| - ActionDispatch::Callbacks.to_prepare { app.routes_reloader.execute_if_updated } - end - initializer "action_dispatch.configure" do |app| ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length end -- cgit v1.2.3 From 0aa66f04e4b4698718023cacb18612e04a4c5eb1 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 12 Sep 2010 00:57:45 +0200 Subject: gets rid of a double negation, no need to force exactly true/false in a predicate --- actionpack/lib/action_dispatch/http/request.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 5606d6abfe..789ecfdbd9 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -136,11 +136,11 @@ module ActionDispatch super.to_i end - # Returns true if the request's "X-Requested-With" header contains - # "XMLHttpRequest". (The Prototype Javascript library sends this header with - # every Ajax request.) + # Returns true if the "X-Requested-With" header contains "XMLHttpRequest" + # (case-insensitive). All major JavaScript libraries send this header with + # every Ajax request. def xml_http_request? - !(@env['HTTP_X_REQUESTED_WITH'] !~ /XMLHttpRequest/i) + @env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/i end alias :xhr? :xml_http_request? -- cgit v1.2.3 From 9a8861f2e4080fe19b9cb1f10e39ba0110d1da7b Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 12 Sep 2010 01:33:42 +0200 Subject: removes /i from the TRUSTED_PROXIES regexp, adds /x and comments for readability, adds a pointer to a Wikipedia section that documents the matched IPs --- actionpack/lib/action_dispatch/http/request.rb | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 789ecfdbd9..7a28228817 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -149,8 +149,16 @@ module ActionDispatch end # Which IP addresses are "trusted proxies" that can be stripped from - # the right-hand-side of X-Forwarded-For - TRUSTED_PROXIES = /^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\./i + # the right-hand-side of X-Forwarded-For. + # + # http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces. + TRUSTED_PROXIES = %r{ + ^127\.0\.0\.1$ | # localhost + ^(10 | # private IP 10.x.x.x + 172\.(1[6-9]|2[0-9]|3[0-1]) | # private IP in the range 172.16.0.0 .. 172.31.255.255 + 192\.168 # private IP 192.168.x.x + )\. + }x # Determines originating IP address. REMOTE_ADDR is the standard # but will fail if the user is behind a proxy. HTTP_CLIENT_IP and/or -- cgit v1.2.3 From 9cd094b8da492b711002dd4b1f2792f315e9bde0 Mon Sep 17 00:00:00 2001 From: "W. Andrew Loe III" Date: Mon, 13 Sep 2010 14:29:25 -0700 Subject: Only send secure cookies over SSL. --- actionpack/lib/action_dispatch/middleware/session/abstract_store.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index dd82294644..348a2d1eb2 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -152,6 +152,10 @@ module ActionDispatch options = env[ENV_SESSION_OPTIONS_KEY] if !session_data.is_a?(AbstractStore::SessionHash) || session_data.loaded? || options[:expire_after] + request = ActionDispatch::Request.new(env) + + return response if (options[:secure] && !request.ssl?) + session_data.send(:load!) if session_data.is_a?(AbstractStore::SessionHash) && !session_data.loaded? sid = options[:id] || generate_sid @@ -165,7 +169,6 @@ module ActionDispatch cookie[:expires] = Time.now + options.delete(:expire_after) end - request = ActionDispatch::Request.new(env) set_cookie(request, cookie.merge!(options)) end -- cgit v1.2.3 From 254ab7d916e579b9300951f5f33d3c5d3ee755a2 Mon Sep 17 00:00:00 2001 From: wycats Date: Mon, 13 Sep 2010 14:03:06 -0700 Subject: First pass at Rack::Cache --- actionpack/lib/action_dispatch/http/rack_cache.rb | 67 +++++++++++++++++++++++ actionpack/lib/action_dispatch/railtie.rb | 1 + 2 files changed, 68 insertions(+) create mode 100644 actionpack/lib/action_dispatch/http/rack_cache.rb (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/rack_cache.rb b/actionpack/lib/action_dispatch/http/rack_cache.rb new file mode 100644 index 0000000000..e5914abc81 --- /dev/null +++ b/actionpack/lib/action_dispatch/http/rack_cache.rb @@ -0,0 +1,67 @@ +require "rack/cache" +require "rack/cache/context" +require "active_support/cache" + +module ActionDispatch + class RailsMetaStore < Rack::Cache::MetaStore + def self.resolve(uri) + new + end + + # TODO: Finally deal with the RAILS_CACHE global + def initialize(store = RAILS_CACHE) + @store = store + end + + def read(key) + @store.read(key) || [] + end + + def write(key, value) + @store.write(key, value) + end + + def purge(key) + @store.delete(key) + nil + end + + ::Rack::Cache::MetaStore::RAILS = self + end + + class RailsEntityStore < Rack::Cache::EntityStore + def self.resolve(uri) + new + end + + def initialize(store = RAILS_CACHE) + @store = store + end + + def exist?(key) + @store.exist?(key) + end + + def open(key) + @store.read(key) + end + + def read(key) + body = open(key) + body.join if body + end + + def write(body) + buf = [] + key, size = slurp(body) { |part| buf << part } + @store.write(key, buf) + [key, size] + end + + def purge(key) + @store.delete(key) + end + + ::Rack::Cache::EntityStore::RAILS = self + end +end diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb index 69537be876..0a3bd5fe40 100644 --- a/actionpack/lib/action_dispatch/railtie.rb +++ b/actionpack/lib/action_dispatch/railtie.rb @@ -9,6 +9,7 @@ module ActionDispatch config.action_dispatch.show_exceptions = true config.action_dispatch.best_standards_support = true config.action_dispatch.tld_length = 1 + config.action_dispatch.rack_cache = {:metastore => "rails:/", :entitystore => "rails:/", :verbose => true} initializer "action_dispatch.configure" do |app| ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length -- cgit v1.2.3 From 7418a440967586851a182bbcd6d93dbba9497cdb Mon Sep 17 00:00:00 2001 From: Carl Lerche Date: Fri, 17 Sep 2010 12:05:40 -0700 Subject: Add RouteSet#append Allows specifying blocks to the routeset that will get appended after the RouteSet is drawn. --- actionpack/lib/action_dispatch/routing/route_set.rb | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 835ba03784..7ac07fe426 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -217,27 +217,35 @@ module ActionDispatch self.valid_conditions.delete(:id) self.valid_conditions.push(:controller, :action) + @append = [] @disable_clear_and_finalize = false clear! end def draw(&block) clear! unless @disable_clear_and_finalize + eval_block(block) + finalize! unless @disable_clear_and_finalize + + nil + end + + def append(&block) + @append << block + end + def eval_block(block) mapper = Mapper.new(self) if default_scope mapper.with_default_scope(default_scope, &block) else mapper.instance_exec(&block) end - - finalize! unless @disable_clear_and_finalize - - nil end def finalize! return if @finalized + @append.each { |blk| eval_block(blk) } @finalized = true @set.freeze end -- cgit v1.2.3 From 013ed1c0503e59dc8f1cfff1bd00d0e579c604a1 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Sat, 18 Sep 2010 13:32:54 +0100 Subject: Remove leading slash from controller [#5651 state:resolved] --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 8a161b0837..42ca351cfa 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -137,7 +137,7 @@ module ActionDispatch { } else if to.is_a?(String) - controller, action = to.split('#') + controller, action = to.sub(%r{\A/}, '').split('#') elsif to.is_a?(Symbol) action = to.to_s end -- cgit v1.2.3 From 0bffd7d933a46df958c3e6bae1d9871aca515a12 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Sat, 18 Sep 2010 17:49:46 +0100 Subject: Raise ArgumentError instead of normalizing controller name when there is a leading slash [#5651 state:resolved] --- actionpack/lib/action_dispatch/routing/mapper.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 42ca351cfa..fe85acb94e 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -137,7 +137,7 @@ module ActionDispatch { } else if to.is_a?(String) - controller, action = to.sub(%r{\A/}, '').split('#') + controller, action = to.split('#') elsif to.is_a?(Symbol) action = to.to_s end @@ -149,6 +149,10 @@ module ActionDispatch controller = [@scope[:module], controller].compact.join("/").presence end + if controller.is_a?(String) && controller =~ %r{\A/} + raise ArgumentError, "controller name should not start with a slash" + end + controller = controller.to_s unless controller.is_a?(Regexp) action = action.to_s unless action.is_a?(Regexp) -- cgit v1.2.3 From 59296ab26dc8518fb83f0015a3871936149b86da Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 22 Sep 2010 11:50:15 -0300 Subject: Refactor routing methods. Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/routing/route.rb | 6 +----- actionpack/lib/action_dispatch/routing/route_set.rb | 7 +------ 2 files changed, 2 insertions(+), 11 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route.rb b/actionpack/lib/action_dispatch/routing/route.rb index aefebf8f80..f91a48e16c 100644 --- a/actionpack/lib/action_dispatch/routing/route.rb +++ b/actionpack/lib/action_dispatch/routing/route.rb @@ -21,11 +21,7 @@ module ActionDispatch conditions[:path_info] = ::Rack::Mount::Strexp.compile(path, requirements, SEPARATORS, anchor) end - @conditions = conditions.inject({}) { |h, (k, v)| - h[k] = Rack::Mount::RegexpWithNamedGroups.new(v) - h - } - + @conditions = Hash[conditions.map { |k,v| [k, Rack::Mount::RegexpWithNamedGroups.new(v)] }] @conditions.delete_if{ |k,v| k != :path_info && !valid_condition?(k) } @requirements.delete_if{ |k,v| !valid_condition?(k) } end diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 7ac07fe426..1a5f21bd09 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -566,13 +566,8 @@ module ActionDispatch keys = options.delete(:_positional_keys) keys -= options.keys if args.size < keys.size - 1 # take format into account - args = args.zip(keys).inject({}) do |h, (v, k)| - h[k] = v - h - end - # Tell url_for to skip default_url_options - options.merge!(args) + options.merge!(Hash[args.zip(keys).map { |v, k| [k, v] }]) end def rewrite_authentication(options) -- cgit v1.2.3 From de9b3385fc05211cf6f2e620ba885d517751e906 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 22 Sep 2010 17:09:06 -0700 Subject: fixing bug with rails use of rack-test --- actionpack/lib/action_dispatch/testing/integration.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 590ebbf364..a681c9a5b6 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -257,17 +257,19 @@ module ActionDispatch end end + port = host.split(':')[1] + env = { :method => method, :params => parameters, "SERVER_NAME" => host.split(':')[0], - "SERVER_PORT" => (https? ? "443" : "80"), + "SERVER_PORT" => (port ? port : (https? ? "443" : "80")), "HTTPS" => https? ? "on" : "off", "rack.url_scheme" => https? ? "https" : "http", "REQUEST_URI" => path, - "HTTP_HOST" => host, + "HTTP_HOST" => [host, port].compact.join(':'), "REMOTE_ADDR" => remote_addr, "CONTENT_TYPE" => "application/x-www-form-urlencoded", "HTTP_ACCEPT" => accept -- cgit v1.2.3 From 1da0dc2f906bbf6c248a33f8d18662fd1494cfba Mon Sep 17 00:00:00 2001 From: Carl Lerche Date: Wed, 22 Sep 2010 17:35:21 -0700 Subject: Improve performance of applications using file uploads by not busting the method cache on every request containing a file upload. --- actionpack/lib/action_dispatch/http/upload.rb | 49 +++++++++++---------------- 1 file changed, 20 insertions(+), 29 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb index 8ee4b81cdd..49465d820e 100644 --- a/actionpack/lib/action_dispatch/http/upload.rb +++ b/actionpack/lib/action_dispatch/http/upload.rb @@ -2,32 +2,27 @@ require 'active_support/core_ext/object/blank' module ActionDispatch module Http - module UploadedFile - def self.extended(object) - object.class_eval do - attr_accessor :original_path, :content_type - alias_method :local_path, :path if method_defined?(:path) - end - end + class UploadedFile < Tempfile + attr_accessor :original_filename, :content_type, :tempfile, :headers - # Take the basename of the upload's original filename. - # This handles the full Windows paths given by Internet Explorer - # (and perhaps other broken user agents) without affecting - # those which give the lone filename. - # The Windows regexp is adapted from Perl's File::Basename. - def original_filename - unless defined? @original_filename - @original_filename = - unless original_path.blank? - if original_path =~ /^(?:.*[:\\\/])?(.*)/m - $1 - else - File.basename original_path - end - end + def initialize(hash) + @original_filename = hash[:filename] + @content_type = hash[:type] + @headers = hash[:head] + + # To the untrained eye, this may appear as insanity. Given the alternatives, + # such as busting the method cache on every request or breaking backwards + # compatibility with is_a?(Tempfile), this solution is the best available + # option. + # + # TODO: Deprecate is_a?(Tempfile) and define a real API for this parameter + tempfile = hash[:tempfile] + tempfile.instance_variables.each do |ivar| + instance_variable_set(ivar, tempfile.instance_variable_get(ivar)) end - @original_filename end + + alias local_path path end module Upload @@ -35,11 +30,7 @@ module ActionDispatch # file upload hash with UploadedFile objects def normalize_parameters(value) if Hash === value && value.has_key?(:tempfile) - upload = value[:tempfile] - upload.extend(UploadedFile) - upload.original_path = value[:filename] - upload.content_type = value[:type] - upload + UploadedFile.new(value) else super end @@ -47,4 +38,4 @@ module ActionDispatch private :normalize_parameters end end -end \ No newline at end of file +end -- cgit v1.2.3 From 308517e913ef1e8d9f13e023bc450374b5ed780a Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Fri, 6 Aug 2010 11:24:09 -0700 Subject: Don't duplicate Rack::Response functionality. [#5320 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- .../lib/action_dispatch/testing/test_response.rb | 22 ++++------------------ 1 file changed, 4 insertions(+), 18 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/test_response.rb b/actionpack/lib/action_dispatch/testing/test_response.rb index 926034762f..82039e72e7 100644 --- a/actionpack/lib/action_dispatch/testing/test_response.rb +++ b/actionpack/lib/action_dispatch/testing/test_response.rb @@ -15,29 +15,15 @@ module ActionDispatch end # Was the response successful? - def success? - (200..299).include?(response_code) - end + alias_method :success?, :successful? # Was the URL not found? - def missing? - response_code == 404 - end + alias_method :missing?, :not_found? # Were we redirected? - def redirect? - (300..399).include?(response_code) - end + alias_method :redirect?, :redirection? # Was there a server-side error? - def error? - (500..599).include?(response_code) - end - alias_method :server_error?, :error? - - # Was there a client client? - def client_error? - (400..499).include?(response_code) - end + alias_method :error?, :server_error? end end -- cgit v1.2.3 From 7fc1edd790a3f590a81991d4582ab567de5a3de0 Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Sat, 25 Sep 2010 08:15:52 +0800 Subject: Remove deprecated stuff in ActionController This removes all deprecated classes in ActionController related to Routing, Abstract Request/Response and Integration/IntegrationTest. All tests and docs were changed to ActionDispatch instead of ActionController. --- actionpack/lib/action_dispatch/testing/integration.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index a681c9a5b6..84039c06ab 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -385,7 +385,7 @@ module ActionDispatch # # require "test_helper" # - # class ExampleTest < ActionController::IntegrationTest + # class ExampleTest < ActionDispatch::IntegrationTest # fixtures :people # # def test_login @@ -409,7 +409,7 @@ module ActionDispatch # # require "test_helper" # - # class AdvancedTest < ActionController::IntegrationTest + # class AdvancedTest < ActionDispatch::IntegrationTest # fixtures :people, :rooms # # def test_login_and_speak -- cgit v1.2.3 From 29f13beda35e30b472c6617fcf3fc5cc22d3468a Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sun, 26 Sep 2010 12:06:19 -0300 Subject: port is appended twice to HTTP_HOST when host already has the port --- actionpack/lib/action_dispatch/testing/integration.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 84039c06ab..404b6185c2 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -257,19 +257,19 @@ module ActionDispatch end end - port = host.split(':')[1] + hostname, port = host.split(':') env = { :method => method, :params => parameters, - "SERVER_NAME" => host.split(':')[0], + "SERVER_NAME" => hostname, "SERVER_PORT" => (port ? port : (https? ? "443" : "80")), "HTTPS" => https? ? "on" : "off", "rack.url_scheme" => https? ? "https" : "http", "REQUEST_URI" => path, - "HTTP_HOST" => [host, port].compact.join(':'), + "HTTP_HOST" => host, "REMOTE_ADDR" => remote_addr, "CONTENT_TYPE" => "application/x-www-form-urlencoded", "HTTP_ACCEPT" => accept -- cgit v1.2.3 From db23e321413aedcfb30207da80bfe06a0eb90e8b Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sun, 26 Sep 2010 17:43:26 -0300 Subject: Not need to do this double ternary --- actionpack/lib/action_dispatch/testing/integration.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 404b6185c2..41729beefb 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -264,7 +264,7 @@ module ActionDispatch :params => parameters, "SERVER_NAME" => hostname, - "SERVER_PORT" => (port ? port : (https? ? "443" : "80")), + "SERVER_PORT" => port || https? ? "443" : "80", "HTTPS" => https? ? "on" : "off", "rack.url_scheme" => https? ? "https" : "http", -- cgit v1.2.3 From 56de4e9a8090e2e617a0d478d38c0fccfce7d725 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sun, 26 Sep 2010 17:54:00 -0300 Subject: Fix the precedence issue here --- actionpack/lib/action_dispatch/testing/integration.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 41729beefb..50bdad1b1c 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -264,7 +264,7 @@ module ActionDispatch :params => parameters, "SERVER_NAME" => hostname, - "SERVER_PORT" => port || https? ? "443" : "80", + "SERVER_PORT" => port || (https? ? "443" : "80"), "HTTPS" => https? ? "on" : "off", "rack.url_scheme" => https? ? "https" : "http", -- cgit v1.2.3 From 5d773f8dedef85f3ef5d3bdebcedd72716002268 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 22 Sep 2010 16:11:15 -0300 Subject: Remove warning "URI.unescape is obsolete" from actionpack. --- actionpack/lib/action_dispatch/routing/mapper.rb | 18 +++++++++--------- actionpack/lib/action_dispatch/routing/route_set.rb | 12 ++++++++++-- 2 files changed, 19 insertions(+), 11 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index fe85acb94e..8ddf67c0cf 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -395,10 +395,10 @@ module ActionDispatch # namespace "admin" do # resources :posts, :comments # end - # + # # This will create a number of routes for each of the posts and comments # controller. For Admin::PostsController, Rails will create: - # + # # GET /admin/photos # GET /admin/photos/new # POST /admin/photos @@ -406,33 +406,33 @@ module ActionDispatch # GET /admin/photos/1/edit # PUT /admin/photos/1 # DELETE /admin/photos/1 - # + # # If you want to route /photos (without the prefix /admin) to # Admin::PostsController, you could use - # + # # scope :module => "admin" do # resources :posts, :comments # end # # or, for a single case - # + # # resources :posts, :module => "admin" - # + # # If you want to route /admin/photos to PostsController # (without the Admin:: module prefix), you could use - # + # # scope "/admin" do # resources :posts, :comments # end # # or, for a single case - # + # # resources :posts, :path => "/admin" # # In each of these cases, the named routes remain the same as if you did # not use scope. In the last case, the following paths map to # PostsController: - # + # # GET /admin/photos # GET /admin/photos/new # POST /admin/photos diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 1a5f21bd09..b885a573d5 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -66,7 +66,11 @@ module ActionDispatch end def split_glob_param!(params) - params[@glob_param] = params[@glob_param].split('/').map { |v| URI.unescape(v) } + params[@glob_param] = params[@glob_param].split('/').map { |v| uri_parser.unescape(v) } + end + + def uri_parser + @uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI end end @@ -543,7 +547,7 @@ module ActionDispatch params.each do |key, value| if value.is_a?(String) value = value.dup.force_encoding(Encoding::BINARY) if value.encoding_aware? - params[key] = URI.unescape(value) + params[key] = uri_parser.unescape(value) end end @@ -560,6 +564,10 @@ module ActionDispatch end private + def uri_parser + @uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI + end + def handle_positional_args(options) return unless args = options.delete(:_positional_args) -- cgit v1.2.3 From 5ced275ac1fc8d52654521bf61742cb7f2f0d796 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 24 Sep 2010 13:01:31 -0300 Subject: Remove old method before redefining it. --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index b885a573d5..ebb9e194c7 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -161,6 +161,7 @@ module ActionDispatch # We use module_eval to avoid leaks @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1 + remove_method :#{selector} if method_defined?(:#{selector}) def #{selector}(*args) options = args.extract_options! @@ -194,6 +195,7 @@ module ActionDispatch hash_access_method = hash_access_name(name, kind) @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1 + remove_method :#{selector} if method_defined?(:#{selector}) def #{selector}(*args) url_for(#{hash_access_method}(*args)) end -- cgit v1.2.3 From bb2f53b4090768e4750af66c6fed15d6596bb11c Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 24 Sep 2010 13:04:51 -0300 Subject: Initialize @as before plural method is called. --- actionpack/lib/action_dispatch/routing/mapper.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 8ddf67c0cf..f6d625e7c3 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -676,6 +676,7 @@ module ActionDispatch DEFAULT_ACTIONS = [:show, :create, :update, :destroy, :new, :edit] def initialize(entities, options) + @as = nil @name = entities.to_s @path = (options.delete(:path) || @name).to_s @controller = (options.delete(:controller) || plural).to_s -- cgit v1.2.3 From b9fa46ca97b448d8cf5b285750341da50d417f8a Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 24 Sep 2010 15:39:59 -0300 Subject: Initialize @_etag. --- actionpack/lib/action_dispatch/http/response.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index ff5e96fdf7..a5d082c6a2 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -43,6 +43,7 @@ module ActionDispatch # :nodoc: @writer = lambda { |x| @body << x } @block = nil @length = 0 + @_etag = nil @status, @header = status, header self.body = body -- cgit v1.2.3 From 986bad6a3b89fed39c02f87068210f0c74e083cd Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 24 Sep 2010 15:40:14 -0300 Subject: Remove warning "too many arguments for format string" when interpolating with empty hash. --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f6d625e7c3..5e95d8ed39 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -350,7 +350,7 @@ module ActionDispatch options = args.last.is_a?(Hash) ? args.pop : {} path = args.shift || block - path_proc = path.is_a?(Proc) ? path : proc { |params| path % params } + path_proc = path.is_a?(Proc) ? path : proc { |params| params.empty? ? path : (path % params) } status = options[:status] || 301 lambda do |env| -- cgit v1.2.3 From cd681681e655b155b8f739d8042389a58be28111 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 24 Sep 2010 15:41:01 -0300 Subject: Initialize @_routes if it doesn't exists. --- actionpack/lib/action_dispatch/routing/url_for.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index e836cf7c8e..045c9ec77d 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -128,6 +128,7 @@ module ActionDispatch when String options when nil, Hash + @_routes ||= nil _routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys) else polymorphic_url(options) -- cgit v1.2.3 From 24ef32fe93a701c0b65a0aedf7c361ff3364c42b Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 24 Sep 2010 15:41:19 -0300 Subject: Ask is @controller is defined to avoid warning. --- actionpack/lib/action_dispatch/testing/assertions/routing.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index c5fed1fc8f..4293ed19e1 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -171,7 +171,7 @@ module ActionDispatch # ROUTES TODO: These assertions should really work in an integration context def method_missing(selector, *args, &block) - if @controller && @routes && @routes.named_routes.helpers.include?(selector) + if defined?(@controller) && @controller && @routes && @routes.named_routes.helpers.include?(selector) @controller.send(selector, *args, &block) else super -- cgit v1.2.3 From 53b91b11ccb18551d6193dc5e96571c24c688e6a Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 24 Sep 2010 15:41:42 -0300 Subject: Avoid uninitialized variable warning, reuse @integration_session. --- .../lib/action_dispatch/testing/integration.rb | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 50bdad1b1c..3204115e9f 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -182,6 +182,7 @@ module ActionDispatch reset! end + remove_method :default_url_options def default_url_options { :host => host, :protocol => https? ? "https" : "http" } end @@ -319,10 +320,10 @@ module ActionDispatch %w(get post put head delete cookies assigns xml_http_request xhr get_via_redirect post_via_redirect).each do |method| define_method(method) do |*args| - reset! unless @integration_session + reset! unless integration_session # reset the html_document variable, but only for new get/post calls @html_document = nil unless %w(cookies assigns).include?(method) - @integration_session.__send__(method, *args).tap do + integration_session.__send__(method, *args).tap do copy_session_variables! end end @@ -347,7 +348,7 @@ module ActionDispatch # Copy the instance variables from the current session instance into the # test instance. def copy_session_variables! #:nodoc: - return unless @integration_session + return unless integration_session %w(controller response request).each do |var| instance_variable_set("@#{var}", @integration_session.__send__(var)) end @@ -357,21 +358,26 @@ module ActionDispatch include ActionDispatch::Routing::UrlFor def url_options - reset! unless @integration_session - @integration_session.url_options + reset! unless integration_session + integration_session.url_options end # Delegate unhandled messages to the current session instance. def method_missing(sym, *args, &block) - reset! unless @integration_session - if @integration_session.respond_to?(sym) - @integration_session.__send__(sym, *args, &block).tap do + reset! unless integration_session + if integration_session.respond_to?(sym) + integration_session.__send__(sym, *args, &block).tap do copy_session_variables! end else super end end + + private + def integration_session + @integration_session ||= nil + end end end -- cgit v1.2.3 From dafb4bd33ba26bf8ca3455db270fee843c8bd2fd Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 22 Sep 2010 16:53:02 -0300 Subject: Don't shadow outer local variables. --- actionpack/lib/action_dispatch/testing/test_request.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb index c587a36930..abc2e9afcc 100644 --- a/actionpack/lib/action_dispatch/testing/test_request.rb +++ b/actionpack/lib/action_dispatch/testing/test_request.rb @@ -66,7 +66,7 @@ module ActionDispatch def accept=(mime_types) @env.delete('action_dispatch.request.accepts') - @env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_types| mime_types.to_s }.join(",") + @env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",") end def cookies -- cgit v1.2.3 From 583ddf22a2a9d9f903ff0f2dba72cc04e80a378f Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 22 Sep 2010 16:47:22 -0300 Subject: Remove more warnings shadowing outer local variable. --- actionpack/lib/action_dispatch/testing/assertions/selector.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb index e1015c62cd..86fba87586 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -513,8 +513,8 @@ module ActionDispatch node.content.gsub(/)?/m) { Rack::Utils.escapeHTML($1) } end - selected = elements.map do |element| - text = element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join + selected = elements.map do |ele| + text = ele.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join root = HTML::Document.new(CGI.unescapeHTML("#{text}")).root css_select(root, "encoded:root", &block)[0] end -- cgit v1.2.3 From 1ed18fcc91e8e908f26291f6ec9ffbd61e48195f Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 24 Sep 2010 16:07:01 -0300 Subject: Initialize @cookies. --- actionpack/lib/action_dispatch/testing/test_request.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb index abc2e9afcc..cf440a1fad 100644 --- a/actionpack/lib/action_dispatch/testing/test_request.rb +++ b/actionpack/lib/action_dispatch/testing/test_request.rb @@ -13,6 +13,7 @@ module ActionDispatch env = Rails.application.env_config.merge(env) if defined?(Rails.application) super(DEFAULT_ENV.merge(env)) + @cookies = nil self.host = 'test.host' self.remote_addr = '0.0.0.0' self.user_agent = 'Rails Testing' -- cgit v1.2.3 From c2940a6bf4b101eafc0c9d968f4e702473156613 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 24 Sep 2010 16:57:28 -0300 Subject: Refactor method to avoid warnings and not run unnecessary code. --- .../action_dispatch/testing/assertions/routing.rb | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 4293ed19e1..0cdc69760b 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -146,25 +146,25 @@ module ActionDispatch # def with_routing old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new - old_controller, @controller = @controller, @controller.clone if @controller - _routes = @routes - - # Unfortunately, there is currently an abstraction leak between AC::Base - # and AV::Base which requires having the URL helpers in both AC and AV. - # To do this safely at runtime for tests, we need to bump up the helper serial - # to that the old AV subclass isn't cached. - # - # TODO: Make this unnecessary - if @controller + if defined?(@controller) && @controller + old_controller, @controller = @controller, @controller.clone + + # Unfortunately, there is currently an abstraction leak between AC::Base + # and AV::Base which requires having the URL helpers in both AC and AV. + # To do this safely at runtime for tests, we need to bump up the helper serial + # to that the old AV subclass isn't cached. + # + # TODO: Make this unnecessary @controller.singleton_class.send(:include, _routes.url_helpers) @controller.view_context_class = Class.new(@controller.view_context_class) do include _routes.url_helpers end end + _routes = @routes yield @routes ensure @routes = old_routes - if @controller + if defined?(@controller) && @controller @controller = old_controller end end -- cgit v1.2.3 From 50decfbc0e2e58961cc3665710922860d38ee2fb Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 24 Sep 2010 17:07:54 -0300 Subject: _routes must be inside @controller conditional. --- actionpack/lib/action_dispatch/testing/assertions/routing.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 0cdc69760b..1390b74a95 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -148,6 +148,7 @@ module ActionDispatch old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new if defined?(@controller) && @controller old_controller, @controller = @controller, @controller.clone + _routes = @routes # Unfortunately, there is currently an abstraction leak between AC::Base # and AV::Base which requires having the URL helpers in both AC and AV. @@ -160,7 +161,6 @@ module ActionDispatch include _routes.url_helpers end end - _routes = @routes yield @routes ensure @routes = old_routes -- cgit v1.2.3 From 86bcccf8dfced5e9428407a71f02c1dcc186f2ba Mon Sep 17 00:00:00 2001 From: thedarkone Date: Thu, 23 Sep 2010 18:08:43 +0200 Subject: No need to create a separate lambda for each call. --- .../lib/action_dispatch/routing/route_set.rb | 29 +++++++++++----------- 1 file changed, 14 insertions(+), 15 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 1a5f21bd09..60b1342d55 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -334,6 +334,19 @@ module ActionDispatch end class Generator #:nodoc: + PARAMETERIZE = { + :parameterize => lambda do |name, value| + if name == :controller + value + elsif value.is_a?(Array) + value.map { |v| Rack::Mount::Utils.escape_uri(v.to_param) }.join('/') + else + return nil unless param = value.to_param + param.split('/').map { |v| Rack::Mount::Utils.escape_uri(v) }.join("/") + end + end + } + attr_reader :options, :recall, :set, :named_route def initialize(options, recall, set, extras = false) @@ -422,7 +435,7 @@ module ActionDispatch end def generate - path, params = @set.set.generate(:path_info, named_route, options, recall, opts) + path, params = @set.set.generate(:path_info, named_route, options, recall, PARAMETERIZE) raise_routing_error unless path @@ -436,20 +449,6 @@ module ActionDispatch raise_routing_error end - def opts - parameterize = lambda do |name, value| - if name == :controller - value - elsif value.is_a?(Array) - value.map { |v| Rack::Mount::Utils.escape_uri(v.to_param) }.join('/') - else - return nil unless param = value.to_param - param.split('/').map { |v| Rack::Mount::Utils.escape_uri(v) }.join("/") - end - end - {:parameterize => parameterize} - end - def raise_routing_error raise ActionController::RoutingError.new("No route matches #{options.inspect}") end -- cgit v1.2.3 From e12e2fb4f660da479110b35b375694bf267aedfb Mon Sep 17 00:00:00 2001 From: thedarkone Date: Mon, 27 Sep 2010 17:37:40 +0200 Subject: Cache 2 of Request's commonly called methods. --- actionpack/lib/action_dispatch/http/url.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 2e39d0dbc2..3e5cd6a2f9 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -15,12 +15,12 @@ module ActionDispatch # Returns 'https://' if this is an SSL request and 'http://' otherwise. def protocol - ssl? ? 'https://' : 'http://' + @protocol ||= ssl? ? 'https://' : 'http://' end # Is this an SSL request? def ssl? - @env['HTTPS'] == 'on' || @env['HTTP_X_FORWARDED_PROTO'] == 'https' + @ssl ||= @env['HTTPS'] == 'on' || @env['HTTP_X_FORWARDED_PROTO'] == 'https' end # Returns the \host for this request, such as "example.com". -- cgit v1.2.3 From 7cee1587f14638e61a33d12114a0d5ae2620d62b Mon Sep 17 00:00:00 2001 From: thedarkone Date: Sat, 25 Sep 2010 16:15:21 +0200 Subject: options[:action] is very likely to be nil. --- actionpack/lib/action_dispatch/routing/polymorphic_routes.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index 02ba5236ee..eaef09d445 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -105,7 +105,7 @@ module ActionDispatch else [ record_or_hash_or_array ] end - inflection = if options[:action].to_s == "new" + inflection = if options[:action] && options[:action].to_s == "new" args.pop :singular elsif (record.respond_to?(:persisted?) && !record.persisted?) -- cgit v1.2.3 From 5b81d1f3ef1f1b06495eadcc1c2d110d76ac1de3 Mon Sep 17 00:00:00 2001 From: thedarkone Date: Mon, 27 Sep 2010 17:42:32 +0200 Subject: Hash#empty? is faster than Enumerable#any? when used on a Hash. --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 60b1342d55..eeec10a403 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -443,7 +443,7 @@ module ActionDispatch return [path, params.keys] if @extras - path << "?#{params.to_query}" if params.any? + path << "?#{params.to_query}" unless params.empty? path rescue Rack::Mount::RoutingError raise_routing_error -- cgit v1.2.3 From bb47927d914480218b003d322c8e8ebcd388093e Mon Sep 17 00:00:00 2001 From: thedarkone Date: Mon, 27 Sep 2010 17:44:11 +0200 Subject: Convert unless/else into if/else. --- actionpack/lib/action_dispatch/routing/polymorphic_routes.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index eaef09d445..49e237f8db 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -168,10 +168,7 @@ module ActionDispatch end def build_named_route_call(records, inflection, options = {}) - unless records.is_a?(Array) - record = extract_record(records) - route = [] - else + if records.is_a?(Array) record = records.pop route = records.map do |parent| if parent.is_a?(Symbol) || parent.is_a?(String) @@ -180,6 +177,9 @@ module ActionDispatch ActiveModel::Naming.route_key(parent).singularize end end + else + record = extract_record(records) + route = [] end if record.is_a?(Symbol) || record.is_a?(String) -- cgit v1.2.3 From 2f326b7f27349b933fe617d83b3f80c6573ce5d8 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Mon, 27 Sep 2010 15:13:11 -0300 Subject: Remove warning "URI.unescape is obsolete" from actionpack. Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/routing/route_set.rb | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index a203ee5934..4289e78641 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -5,6 +5,8 @@ require 'active_support/core_ext/object/to_query' module ActionDispatch module Routing class RouteSet #:nodoc: + include ActionController::UriParser + PARAMETERS_KEY = 'action_dispatch.request.path_parameters' class Dispatcher #:nodoc: @@ -68,10 +70,6 @@ module ActionDispatch def split_glob_param!(params) params[@glob_param] = params[@glob_param].split('/').map { |v| uri_parser.unescape(v) } end - - def uri_parser - @uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI - end end # A NamedRouteCollection instance is a collection of named routes, and also -- cgit v1.2.3 From 1ab2ab07b5e7c4031c014175887e9f20b8f60a4c Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Mon, 27 Sep 2010 15:18:35 -0300 Subject: Remove more warnings shadowing outer local variable. Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/testing/assertions/selector.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb index 86fba87586..353be10d20 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -513,8 +513,8 @@ module ActionDispatch node.content.gsub(/)?/m) { Rack::Utils.escapeHTML($1) } end - selected = elements.map do |ele| - text = ele.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join + selected = elements.map do |_element| + text = _element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join root = HTML::Document.new(CGI.unescapeHTML("#{text}")).root css_select(root, "encoded:root", &block)[0] end -- cgit v1.2.3 From 8adb24016d76a2257b79f4566de66e1b88e56c71 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Mon, 27 Sep 2010 16:17:32 -0300 Subject: Define @_routes inside method, makes more sense and will be initialized when called anywhere. Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- actionpack/lib/action_dispatch/routing/url_for.rb | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 4289e78641..66b487ba6d 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -318,7 +318,7 @@ module ActionDispatch singleton_class.send(:define_method, :_routes) { routes } end - define_method(:_routes) { @_routes || routes } + define_method(:_routes) { @_routes ||= nil; @_routes || routes } end helpers diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index 045c9ec77d..e836cf7c8e 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -128,7 +128,6 @@ module ActionDispatch when String options when nil, Hash - @_routes ||= nil _routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys) else polymorphic_url(options) -- cgit v1.2.3 From dd83140b24dcb8a27e226c9de286318a44d7fab1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 27 Sep 2010 22:58:31 +0200 Subject: Properly initialize variables inside the initialize method. --- actionpack/lib/action_dispatch/routing/route_set.rb | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 66b487ba6d..e25b30ffa6 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -304,9 +304,9 @@ module ActionDispatch extend ActiveSupport::Concern include UrlFor - @routes = routes + @_routes = routes class << self - delegate :url_for, :to => '@routes' + delegate :url_for, :to => '@_routes' end extend routes.named_routes.module @@ -318,7 +318,12 @@ module ActionDispatch singleton_class.send(:define_method, :_routes) { routes } end - define_method(:_routes) { @_routes ||= nil; @_routes || routes } + def initialize(*) + @_routes = nil + super + end + + define_method(:_routes) { @_routes || routes } end helpers -- cgit v1.2.3 From 8aa86babad2eddb5244ba79b4e3b5702e7e77217 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 28 Sep 2010 00:39:10 +0200 Subject: Fix tests on 1.9.2. --- actionpack/lib/action_dispatch/routing/route_set.rb | 5 ----- 1 file changed, 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index e25b30ffa6..9271191f6d 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -318,11 +318,6 @@ module ActionDispatch singleton_class.send(:define_method, :_routes) { routes } end - def initialize(*) - @_routes = nil - super - end - define_method(:_routes) { @_routes || routes } end -- cgit v1.2.3 From 197a995bc548e206bb907c40d75f8ed70fa5a923 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Mon, 27 Sep 2010 20:57:26 -0300 Subject: Move uri parser to AS as URI.parser method to reuse it in AP and ARes. --- actionpack/lib/action_dispatch/routing/route_set.rb | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 66b487ba6d..66e6ecc74c 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -5,8 +5,6 @@ require 'active_support/core_ext/object/to_query' module ActionDispatch module Routing class RouteSet #:nodoc: - include ActionController::UriParser - PARAMETERS_KEY = 'action_dispatch.request.path_parameters' class Dispatcher #:nodoc: @@ -68,7 +66,7 @@ module ActionDispatch end def split_glob_param!(params) - params[@glob_param] = params[@glob_param].split('/').map { |v| uri_parser.unescape(v) } + params[@glob_param] = params[@glob_param].split('/').map { |v| URI.parser.unescape(v) } end end @@ -546,7 +544,7 @@ module ActionDispatch params.each do |key, value| if value.is_a?(String) value = value.dup.force_encoding(Encoding::BINARY) if value.encoding_aware? - params[key] = uri_parser.unescape(value) + params[key] = URI.parser.unescape(value) end end @@ -563,10 +561,6 @@ module ActionDispatch end private - def uri_parser - @uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI - end - def handle_positional_args(options) return unless args = options.delete(:_positional_args) -- cgit v1.2.3 From 71acc2737aa346ee57f9fc21252a508ae83367a4 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 07:57:26 +0800 Subject: Move uri parser to AS as URI.parser method to reuse it in AP and ARes. --- actionpack/lib/action_dispatch/routing/route_set.rb | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 9271191f6d..8d9f0cfdeb 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -5,8 +5,6 @@ require 'active_support/core_ext/object/to_query' module ActionDispatch module Routing class RouteSet #:nodoc: - include ActionController::UriParser - PARAMETERS_KEY = 'action_dispatch.request.path_parameters' class Dispatcher #:nodoc: @@ -68,7 +66,7 @@ module ActionDispatch end def split_glob_param!(params) - params[@glob_param] = params[@glob_param].split('/').map { |v| uri_parser.unescape(v) } + params[@glob_param] = params[@glob_param].split('/').map { |v| URI.parser.unescape(v) } end end @@ -546,7 +544,7 @@ module ActionDispatch params.each do |key, value| if value.is_a?(String) value = value.dup.force_encoding(Encoding::BINARY) if value.encoding_aware? - params[key] = uri_parser.unescape(value) + params[key] = URI.parser.unescape(value) end end @@ -563,10 +561,6 @@ module ActionDispatch end private - def uri_parser - @uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI - end - def handle_positional_args(options) return unless args = options.delete(:_positional_args) -- cgit v1.2.3 From b8c565fbd68343b419b05a53b4e1844062d1197e Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 15:10:15 -0300 Subject: Initialize @app if it doesn't exists. --- actionpack/lib/action_dispatch/testing/integration.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 3204115e9f..8c05462d0d 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -308,7 +308,7 @@ module ActionDispatch include ActionDispatch::Assertions def app - @app + @app ||= nil end # Reset the current session. This is useful for testing multiple sessions -- cgit v1.2.3 From 4bce8e3c7510cd1bc1821af208d05e8c87349fb2 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 15:10:55 -0300 Subject: No need to call super here. Use yield instead block.call --- actionpack/lib/action_dispatch/middleware/stack.rb | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index db7f342bc5..9ea188c3e2 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -41,9 +41,8 @@ module ActionDispatch end end - def initialize(*args, &block) - super(*args) - block.call(self) if block_given? + def initialize(*args) + yield(self) if block_given? end def insert(index, *args, &block) -- cgit v1.2.3 From adcc5e11fe5edd2883b6ec4d08ab72180a973155 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 15:29:40 -0300 Subject: @selected may not be defined here, avoid warning. --- actionpack/lib/action_dispatch/testing/assertions/selector.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb index 353be10d20..9ae4f65db9 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -197,7 +197,7 @@ module ActionDispatch # This usually happens when passing a node/element that # happens to be nil. raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?" - elsif @selected + elsif defined?(@selected) && @selected root = HTML::Node.new(nil) root.children.concat @selected else -- cgit v1.2.3 From 059d609a1a59300faefdc2d4186bae13b30c9699 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 15:46:30 -0300 Subject: Avoid more uninitialized variable warnings. --- actionpack/lib/action_dispatch/testing/assertions/selector.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb index 9ae4f65db9..f5ecb9a199 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -187,6 +187,7 @@ module ActionDispatch def assert_select(*args, &block) # Start with optional element followed by mandatory selector. arg = args.shift + @selected ||= nil if arg.is_a?(HTML::Node) # First argument is a node (tag or text, but also HTML root), @@ -197,7 +198,7 @@ module ActionDispatch # This usually happens when passing a node/element that # happens to be nil. raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?" - elsif defined?(@selected) && @selected + elsif @selected root = HTML::Node.new(nil) root.children.concat @selected else -- cgit v1.2.3 From c9416546a209847e2167edf49de7b4f6c9950694 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 16:09:31 -0300 Subject: Use parenthesis to avoid ambiguous first argument warning. --- actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb index d18b162a93..c3fa4dba0a 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb @@ -19,7 +19,7 @@ <% end %> <% traces.each do |name, trace| %> -
;"> +
;">
<%=h trace.join "\n" %>
<% end %> -- cgit v1.2.3 From 540e87256df08d350e9eb572408e5f68fa59f42b Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 16:12:07 -0300 Subject: Remove remaining warnings on _trace by adding parenthesis to gsub arguments. --- .../lib/action_dispatch/middleware/templates/rescues/_trace.erb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb index c3fa4dba0a..8771b5fd6d 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.erb @@ -12,14 +12,14 @@
<% names.each do |name| %> <% - show = "document.getElementById('#{name.gsub /\s/, '-'}').style.display='block';" - hide = (names - [name]).collect {|hide_name| "document.getElementById('#{hide_name.gsub /\s/, '-'}').style.display='none';"} + show = "document.getElementById('#{name.gsub(/\s/, '-')}').style.display='block';" + hide = (names - [name]).collect {|hide_name| "document.getElementById('#{hide_name.gsub(/\s/, '-')}').style.display='none';"} %> <%= name %> <%= '|' unless names.last == name %> <% end %> <% traces.each do |name, trace| %> -
;"> +
;">
<%=h trace.join "\n" %>
<% end %> -- cgit v1.2.3 From 6286b63f27b6b36b9603c4c68600f8f352b84137 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 16:20:48 -0300 Subject: Remove warings from rescues: don't define more than once debug_hash method and ask if @response if defined. --- .../middleware/templates/rescues/_request_and_response.erb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb index e963b04524..97f7cf0bbe 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb @@ -14,7 +14,7 @@ def debug_hash(hash) hash.sort_by { |k, v| k.to_s }.map { |k, v| "#{k}: #{v.inspect rescue $!.message}" }.join("\n") - end + end unless self.class.method_defined?(:debug_hash) %>

Request

@@ -28,4 +28,4 @@

Response

-

Headers:

<%=h @response ? @response.headers.inspect.gsub(',', ",\n") : 'None' %>

+

Headers:

<%=h defined?(@response) ? @response.headers.inspect.gsub(',', ",\n") : 'None' %>

-- cgit v1.2.3 From eea61a030e96625c53c57b63f0a9449850cf78df Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 16:24:42 -0300 Subject: Initialize @compiled_at if it is not. --- actionpack/lib/action_dispatch/middleware/static.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index 581cadbeb4..6d442b91f5 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -7,6 +7,7 @@ module ActionDispatch @compiled_at = Regexp.compile(/^#{Regexp.escape(at)}/) unless @at.blank? @compiled_root = Regexp.compile(/^#{Regexp.escape(root)}/) @file_server = ::Rack::File.new(root) + @compiled_at ||= nil end def match?(path) -- cgit v1.2.3 From da8f9ca4329499fc9cc9c3f999a9d6eecdc801d3 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 16:27:05 -0300 Subject: Remove more warnings on variables. --- actionpack/lib/action_dispatch/routing/url_for.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index e836cf7c8e..7be0f2769a 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -136,6 +136,7 @@ module ActionDispatch protected def _with_routes(routes) + @_routes ||= nil old_routes, @_routes = @_routes, routes yield ensure -- cgit v1.2.3 From 4d6e178f888c8287eb59e14bd9ecb77b4d71455b Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 16:31:21 -0300 Subject: Remove method if exists, avoid calling Array#first so many times. --- actionpack/lib/action_dispatch/middleware/callbacks.rb | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb index e4ae480bfb..0bb950d1cc 100644 --- a/actionpack/lib/action_dispatch/middleware/callbacks.rb +++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb @@ -19,9 +19,11 @@ module ActionDispatch # replace the existing callback. Passing an identifier is a suggested # practice if the code adding a preparation block may be reloaded. def self.to_prepare(*args, &block) - if args.first.is_a?(Symbol) && block_given? - define_method :"__#{args.first}", &block - set_callback(:prepare, :"__#{args.first}") + first_arg = args.first + if first_arg.is_a?(Symbol) && block_given? + remove_method :"__#{first_arg}" if method_defined?(:"__#{first_arg}") + define_method :"__#{first_arg}", &block + set_callback(:prepare, :"__#{first_arg}") else set_callback(:prepare, *args, &block) end -- cgit v1.2.3 From 19d9fffb9b8350b03cf8b1e3a3249eba06d22c1a Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 17:08:10 -0300 Subject: Use redefine_method instead define_method, it may be already defined. --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 66e6ecc74c..71a320ce9c 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -313,7 +313,7 @@ module ActionDispatch # Yes plz - JP included do routes.install_helpers(self) - singleton_class.send(:define_method, :_routes) { routes } + singleton_class.send(:redefine_method, :_routes) { routes } end define_method(:_routes) { @_routes ||= nil; @_routes || routes } -- cgit v1.2.3 From 523f98099d331908db6ab4c45f7657e61a8a4d5f Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 28 Sep 2010 18:01:48 -0300 Subject: Remove more warnings on AP. --- actionpack/lib/action_dispatch/middleware/session/abstract_store.rb | 4 ++-- actionpack/lib/action_dispatch/testing/assertions/selector.rb | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index 348a2d1eb2..ea49b30630 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -102,8 +102,8 @@ module ActionDispatch def destroy clear - @by.send(:destroy, @env) if @by - @env[ENV_SESSION_OPTIONS_KEY][:id] = nil if @env && @env[ENV_SESSION_OPTIONS_KEY] + @by.send(:destroy, @env) if defined?(@by) && @by + @env[ENV_SESSION_OPTIONS_KEY][:id] = nil if defined?(@env) && @env && @env[ENV_SESSION_OPTIONS_KEY] @loaded = false end diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb index f5ecb9a199..2b862fb7d6 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -67,7 +67,7 @@ module ActionDispatch arg = args.shift elsif arg == nil raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?" - elsif @selected + elsif defined?(@selected) && @selected matches = [] @selected.each do |selected| @@ -443,6 +443,7 @@ module ActionDispatch assert_block("") { true } # to count the assertion if block_given? && !([:remove, :show, :hide, :toggle].include? rjs_type) begin + @selected ||= nil in_scope, @selected = @selected, matches yield matches ensure -- cgit v1.2.3 From 14f9904e0fc6d8a1e5627ac64c4b5b14e95177c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 29 Sep 2010 11:18:31 +0200 Subject: Avoid (@_var ||= nil) pattern by using initialize methods and ensuring everyone calls super as expected. --- actionpack/lib/action_dispatch/middleware/stack.rb | 4 ++++ actionpack/lib/action_dispatch/middleware/static.rb | 3 +-- actionpack/lib/action_dispatch/routing/url_for.rb | 6 +++++- actionpack/lib/action_dispatch/testing/integration.rb | 1 + 4 files changed, 11 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 9ea188c3e2..e3cd779756 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -41,7 +41,11 @@ module ActionDispatch end end + # Use this instead of super to work around a warning. + alias :array_initialize :initialize + def initialize(*args) + array_initialize(*args) yield(self) if block_given? end diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index 6d442b91f5..cf13938331 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -4,10 +4,9 @@ module ActionDispatch class FileHandler def initialize(at, root) @at, @root = at.chomp('/'), root.chomp('/') - @compiled_at = Regexp.compile(/^#{Regexp.escape(at)}/) unless @at.blank? + @compiled_at = (Regexp.compile(/^#{Regexp.escape(at)}/) unless @at.blank?) @compiled_root = Regexp.compile(/^#{Regexp.escape(root)}/) @file_server = ::Rack::File.new(root) - @compiled_at ||= nil end def match?(path) diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index 7be0f2769a..bfdea41f60 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -98,6 +98,11 @@ module ActionDispatch end end + def initialize(*) + @_routes = nil + super + end + def url_options default_url_options end @@ -136,7 +141,6 @@ module ActionDispatch protected def _with_routes(routes) - @_routes ||= nil old_routes, @_routes = @_routes, routes yield ensure diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 8c05462d0d..4d25bb8d7b 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -171,6 +171,7 @@ module ActionDispatch # Create and initialize a new Session instance. def initialize(app) + super @app = app # If the app is a Rails app, make url_helpers available on the session -- cgit v1.2.3 From 392df0fc06a985e607c89c8a0090cb036adc5b7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 29 Sep 2010 11:19:22 +0200 Subject: @_etag is not used anywhere. --- actionpack/lib/action_dispatch/http/response.rb | 2 -- 1 file changed, 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index a5d082c6a2..151c90167b 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -43,7 +43,6 @@ module ActionDispatch # :nodoc: @writer = lambda { |x| @body << x } @block = nil @length = 0 - @_etag = nil @status, @header = status, header self.body = body @@ -141,7 +140,6 @@ module ActionDispatch # :nodoc: assign_default_content_type_and_charset! handle_conditional_get! self["Set-Cookie"] = self["Set-Cookie"].join("\n") if self["Set-Cookie"].respond_to?(:join) - self["ETag"] = @_etag if @_etag super end -- cgit v1.2.3 From b1ae796284850e29d5ad0fc769e55ed4a43676a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 29 Sep 2010 11:28:38 +0200 Subject: Fix an error on 1.8.7. --- actionpack/lib/action_dispatch/testing/integration.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 4d25bb8d7b..fee8cad9f5 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -171,7 +171,7 @@ module ActionDispatch # Create and initialize a new Session instance. def initialize(app) - super + super() @app = app # If the app is a Rails app, make url_helpers available on the session -- cgit v1.2.3 From f63d35fba55867111427bfeb54c31b11e02d5d3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 29 Sep 2010 14:24:32 +0200 Subject: Ensure that named routes do not overwrite previously defined routes. --- actionpack/lib/action_dispatch/routing/mapper.rb | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 5e95d8ed39..0cb02c5b80 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -62,7 +62,6 @@ module ActionDispatch if using_match_shorthand?(path_without_format, @options) to_shorthand = @options[:to].blank? @options[:to] ||= path_without_format[1..-1].sub(%r{/([^/]*)$}, '#\1') - @options[:as] ||= Mapper.normalize_name(path_without_format) end @options.merge!(default_controller_and_action(to_shorthand)) @@ -924,9 +923,14 @@ module ActionDispatch if action.to_s =~ /^[\w\/]+$/ options[:action] ||= action unless action.to_s.include?("/") - options[:as] = name_for_action(action, options[:as]) else - options[:as] = name_for_action(options[:as]) + action = nil + end + + if options.key?(:as) && !options[:as] + options.delete(:as) + else + options[:as] = name_for_action(options[:as], action) end super(path, options) @@ -1092,18 +1096,16 @@ module ActionDispatch path || @scope[:path_names][name.to_sym] || name.to_s end - def prefix_name_for_action(action, as) - if as.present? + def prefix_name_for_action(as, action) + if as as.to_s - elsif as - nil elsif !canonical_action?(action, @scope[:scope_level]) action.to_s end end - def name_for_action(action, as=nil) - prefix = prefix_name_for_action(action, as) + def name_for_action(as, action) + prefix = prefix_name_for_action(as, action) prefix = Mapper.normalize_name(prefix) if prefix name_prefix = @scope[:as] @@ -1127,7 +1129,8 @@ module ActionDispatch [name_prefix, member_name, prefix] end - name.select(&:present?).join("_").presence + candidate = name.select(&:present?).join("_").presence + candidate unless as.nil? && @set.routes.map(&:name).include?(candidate) end end -- cgit v1.2.3 From 152580ee00205b42de45950d69349c6eab6dd291 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 29 Sep 2010 11:37:08 -0300 Subject: Don't try to interpolate string if there's no interpolation point at all. --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 0cb02c5b80..189da138d8 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -349,7 +349,7 @@ module ActionDispatch options = args.last.is_a?(Hash) ? args.pop : {} path = args.shift || block - path_proc = path.is_a?(Proc) ? path : proc { |params| params.empty? ? path : (path % params) } + path_proc = path.is_a?(Proc) ? path : proc { |params| (params.empty? || !path.match(/%{\w*}/)) ? path : (path % params) } status = options[:status] || 301 lambda do |env| -- cgit v1.2.3 From 8823b85010a217df555b981a453384e24ce7da47 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 29 Sep 2010 12:13:58 -0300 Subject: Remove redundant conditional. --- actionpack/lib/action_dispatch/testing/assertions/response.rb | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb index 10b122557a..e381b9abdf 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/response.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb @@ -84,11 +84,7 @@ module ActionDispatch when %r{^\w[\w\d+.-]*:.*} fragment when String - if fragment =~ %r{^\w[\w\d+.-]*:.*} - fragment - else - @request.protocol + @request.host_with_port + fragment - end + @request.protocol + @request.host_with_port + fragment when :back raise RedirectBackError unless refer = @request.headers["Referer"] refer -- cgit v1.2.3 From c37800aae123d21d53a49433cac2e0a2479c6bbd Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 29 Sep 2010 12:55:43 -0300 Subject: _ is not a valid scheme name character, \w includes it and also is redundant with \d. 'The scheme name consists of a letter followed by any combination of letters, digits, and the plus ("+"), period ("."), or hyphen ("-") characters; and is terminated by a colon (":").' --- actionpack/lib/action_dispatch/testing/assertions/response.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb index e381b9abdf..1558c3ae05 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/response.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb @@ -81,7 +81,7 @@ module ActionDispatch def normalize_argument_to_redirection(fragment) case fragment - when %r{^\w[\w\d+.-]*:.*} + when %r{^\w[A-Za-z\d+.-]*:.*} fragment when String @request.protocol + @request.host_with_port + fragment -- cgit v1.2.3 From 78ac9c2be738ff48c847a26ae8fc4464e881e184 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 29 Sep 2010 16:09:58 -0700 Subject: dry up method checking in the request object --- actionpack/lib/action_dispatch/http/request.rb | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 7a28228817..09d6ba8223 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -54,11 +54,7 @@ module ActionDispatch # the application should use), this \method returns the overridden # value, not the original. def request_method - @request_method ||= begin - method = env["REQUEST_METHOD"] - HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}") - method - end + @request_method ||= check_method(env["REQUEST_METHOD"]) end # Returns a symbol form of the #request_method @@ -70,11 +66,7 @@ module ActionDispatch # even if it was overridden by middleware. See #request_method for # more information. def method - @method ||= begin - method = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'] - HTTP_METHOD_LOOKUP[method] || raise(ActionController::UnknownHttpMethod, "#{method}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}") - method - end + @method ||= check_method(env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']) end # Returns a symbol form of the #method @@ -246,5 +238,12 @@ module ActionDispatch def local? LOCALHOST.any? { |local_ip| local_ip === remote_addr && local_ip === remote_ip } end + + private + + def check_method(name) + HTTP_METHOD_LOOKUP[name] || raise(ActionController::UnknownHttpMethod, "#{name}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}") + name + end end end -- cgit v1.2.3 From 692f5184c405b3b0f9b6ac02c37aaefb7d2ffb62 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Thu, 30 Sep 2010 02:24:47 +0800 Subject: no need to check for nil? --- actionpack/lib/action_dispatch/middleware/session/abstract_store.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index ea49b30630..db0187c015 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -165,7 +165,7 @@ module ActionDispatch return response unless value cookie = { :value => value } - unless options[:expire_after].nil? + if options[:expire_after] cookie[:expires] = Time.now + options.delete(:expire_after) end -- cgit v1.2.3 From 7e057d11aa21383394e570d0de8f4d5f3729d024 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 29 Sep 2010 18:23:33 -0700 Subject: fixing regexp warnings --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 189da138d8..0c6e1b37a7 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -349,7 +349,7 @@ module ActionDispatch options = args.last.is_a?(Hash) ? args.pop : {} path = args.shift || block - path_proc = path.is_a?(Proc) ? path : proc { |params| (params.empty? || !path.match(/%{\w*}/)) ? path : (path % params) } + path_proc = path.is_a?(Proc) ? path : proc { |params| (params.empty? || !path.match(/%\{\w*\}/)) ? path : (path % params) } status = options[:status] || 301 lambda do |env| -- cgit v1.2.3 From 31752f3516e5977b459cc713ae50515b20fda67b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 29 Sep 2010 18:32:51 -0700 Subject: avoid creating a block if possible --- actionpack/lib/action_dispatch/routing/mapper.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 0c6e1b37a7..0a888505d2 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -345,10 +345,10 @@ module ActionDispatch # Redirect any path to another path: # # match "/stories" => redirect("/posts") - def redirect(*args, &block) + def redirect(*args) options = args.last.is_a?(Hash) ? args.pop : {} - path = args.shift || block + path = args.shift || Proc.new path_proc = path.is_a?(Proc) ? path : proc { |params| (params.empty? || !path.match(/%\{\w*\}/)) ? path : (path % params) } status = options[:status] || 301 -- cgit v1.2.3 From 69f97f469747777ed1c457715f5361f6b8a0ab7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 30 Sep 2010 07:25:06 +0200 Subject: Use .find here as it is simpler and faster. --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 0a888505d2..47aed0273c 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1130,7 +1130,7 @@ module ActionDispatch end candidate = name.select(&:present?).join("_").presence - candidate unless as.nil? && @set.routes.map(&:name).include?(candidate) + candidate unless as.nil? && @set.routes.find { |r| r.name == candidate } end end -- cgit v1.2.3 From 22b11a41cc764bc0f7b0c0f518a5289230428597 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Sat, 25 Sep 2010 19:22:32 +0200 Subject: Allow mounting engines at '/' Without that commit script_name always become '/', which results in paths like //posts/1 instead of /posts/1 --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 5d18dfe369..99a3019f3a 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -511,7 +511,7 @@ module ActionDispatch end script_name = options.delete(:script_name) - path = (script_name.blank? ? _generate_prefix(options) : script_name).to_s + path = (script_name.blank? ? _generate_prefix(options) : script_name.chomp('/')).to_s path_options = options.except(*RESERVED_OPTIONS) path_options = yield(path_options) if block_given? -- cgit v1.2.3 From ec5d846ac6137e60d81257041e4fde82c0480b32 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Sun, 26 Sep 2010 00:17:06 +0200 Subject: Properly reload routes defined in class definition Sometimes it's easier to define routes inside Engine or Application class definition (e.g. one file applications). The problem with such case is that if there is a plugin that has config/routes.rb file, it will trigger routes reload on application. Since routes definition for application is not in config/routes.rb file routes_reloader will fail to reload application's routes properly. With this commit you can pass routes definition as a block to routes method, which will allow to properly reload it: class MyApp::Application < Rails::Application routes do resources :users end end --- actionpack/lib/action_dispatch/routing/route_set.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 99a3019f3a..32f41934f1 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -1,6 +1,7 @@ require 'rack/mount' require 'forwardable' require 'active_support/core_ext/object/to_query' +require 'active_support/core_ext/hash/slice' module ActionDispatch module Routing -- cgit v1.2.3 From ff2fdcc52b391514cb62c2a1ef29827ac94914c6 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 1 Oct 2010 17:22:42 -0700 Subject: removing AS::Testing::Default in favor of just undefing default_test --- actionpack/lib/action_dispatch/testing/performance_test.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/performance_test.rb b/actionpack/lib/action_dispatch/testing/performance_test.rb index 33a5c68b9d..d6c98b4db7 100644 --- a/actionpack/lib/action_dispatch/testing/performance_test.rb +++ b/actionpack/lib/action_dispatch/testing/performance_test.rb @@ -11,9 +11,8 @@ begin # formats are written, so you'll have two output files per test method. class PerformanceTest < ActionDispatch::IntegrationTest include ActiveSupport::Testing::Performance - include ActiveSupport::Testing::Default end end rescue NameError $stderr.puts "Specify ruby-prof as application's dependency in Gemfile to run benchmarks." -end \ No newline at end of file +end -- cgit v1.2.3 From 50215f9525b6b5e3bfe703724b9f68177ed8565d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 20 Sep 2010 10:18:44 +0200 Subject: Rely on Rack::Session stores API for more compatibility across the Ruby world. --- actionpack/lib/action_dispatch/http/url.rb | 5 - .../middleware/session/abstract_store.rb | 280 ++++----------------- .../middleware/session/cookie_store.rb | 64 ++--- .../middleware/session/mem_cache_store.rb | 53 +--- 4 files changed, 76 insertions(+), 326 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 3e5cd6a2f9..cfee95eb4b 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -18,11 +18,6 @@ module ActionDispatch @protocol ||= ssl? ? 'https://' : 'http://' end - # Is this an SSL request? - def ssl? - @ssl ||= @env['HTTPS'] == 'on' || @env['HTTP_X_FORWARDED_PROTO'] == 'https' - end - # Returns the \host for this request, such as "example.com". def raw_host_with_port if forwarded = env["HTTP_X_FORWARDED_HOST"] diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index db0187c015..679ba7fc8e 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -1,5 +1,6 @@ require 'rack/utils' require 'rack/request' +require 'rack/session/abstract/id' require 'action_dispatch/middleware/cookies' require 'active_support/core_ext/object/blank' @@ -8,252 +9,69 @@ module ActionDispatch class SessionRestoreError < StandardError #:nodoc: end - class AbstractStore - ENV_SESSION_KEY = 'rack.session'.freeze - ENV_SESSION_OPTIONS_KEY = 'rack.session.options'.freeze - - # thin wrapper around Hash that allows us to lazily - # load session id into session_options - class OptionsHash < Hash - def initialize(by, env, default_options) - @by = by - @env = env - @session_id_loaded = false - merge!(default_options) - end - - def [](key) - if key == :id - load_session_id! unless key?(:id) || has_session_id? - end - super - end - - private - - def has_session_id? - @session_id_loaded - end - - def load_session_id! - self[:id] = @by.send(:extract_session_id, @env) - @session_id_loaded = true - end - end - - class SessionHash < Hash - def initialize(by, env) - super() - @by = by - @env = env - @loaded = false - end - - def [](key) - load_for_read! - super(key.to_s) - end - - def has_key?(key) - load_for_read! - super(key.to_s) - end - - def []=(key, value) - load_for_write! - super(key.to_s, value) - end - - def clear - load_for_write! - super - end - - def to_hash - load_for_read! - h = {}.replace(self) - h.delete_if { |k,v| v.nil? } - h - end - - def update(hash) - load_for_write! - super(hash.stringify_keys) - end - - def delete(key) - load_for_write! - super(key.to_s) - end - - def inspect - load_for_read! - super - end - - def exists? - return @exists if instance_variable_defined?(:@exists) - @exists = @by.send(:exists?, @env) - end - - def loaded? - @loaded - end - - def destroy - clear - @by.send(:destroy, @env) if defined?(@by) && @by - @env[ENV_SESSION_OPTIONS_KEY][:id] = nil if defined?(@env) && @env && @env[ENV_SESSION_OPTIONS_KEY] - @loaded = false - end - - private - - def load_for_read! - load! if !loaded? && exists? - end - - def load_for_write! - load! unless loaded? - end - - def load! - id, session = @by.send(:load_session, @env) - @env[ENV_SESSION_OPTIONS_KEY][:id] = id - replace(session.stringify_keys) - @loaded = true - end - + module DestroyableSession + def destroy + clear + options = @env[Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY] if @env + options ||= {} + @by.send(:destroy_session, @env, options[:id], options) if @by + options[:id] = nil + @loaded = false end + end - DEFAULT_OPTIONS = { - :key => '_session_id', - :path => '/', - :domain => nil, - :expire_after => nil, - :secure => false, - :httponly => true, - :cookie_only => true - } + ::Rack::Session::Abstract::SessionHash.send :include, DestroyableSession + module Compatibility def initialize(app, options = {}) - @app = app - @default_options = DEFAULT_OPTIONS.merge(options) - @key = @default_options.delete(:key).freeze - @cookie_only = @default_options.delete(:cookie_only) - ensure_session_key! + options[:key] ||= '_session_id' + super end - def call(env) - prepare!(env) - response = @app.call(env) - - session_data = env[ENV_SESSION_KEY] - options = env[ENV_SESSION_OPTIONS_KEY] - - if !session_data.is_a?(AbstractStore::SessionHash) || session_data.loaded? || options[:expire_after] - request = ActionDispatch::Request.new(env) - - return response if (options[:secure] && !request.ssl?) - - session_data.send(:load!) if session_data.is_a?(AbstractStore::SessionHash) && !session_data.loaded? - - sid = options[:id] || generate_sid - session_data = session_data.to_hash - - value = set_session(env, sid, session_data) - return response unless value - - cookie = { :value => value } - if options[:expire_after] - cookie[:expires] = Time.now + options.delete(:expire_after) - end - - set_cookie(request, cookie.merge!(options)) - end - - response + def generate_sid + ActiveSupport::SecureRandom.hex(16) end + end - private - - def prepare!(env) - env[ENV_SESSION_KEY] = SessionHash.new(self, env) - env[ENV_SESSION_OPTIONS_KEY] = OptionsHash.new(self, env, @default_options) - end - - def generate_sid - ActiveSupport::SecureRandom.hex(16) - end - - def set_cookie(request, options) - if request.cookie_jar[@key] != options[:value] || !options[:expires].nil? - request.cookie_jar[@key] = options - end - end - - def load_session(env) - stale_session_check! do - sid = current_session_id(env) - sid, session = get_session(env, sid) - [sid, session] - end - end - - def extract_session_id(env) - stale_session_check! do - request = ActionDispatch::Request.new(env) - sid = request.cookies[@key] - sid ||= request.params[@key] unless @cookie_only - sid - end - end - - def current_session_id(env) - env[ENV_SESSION_OPTIONS_KEY][:id] - end + module StaleSessionCheck + def load_session(env) + stale_session_check! { super } + end - def ensure_session_key! - if @key.blank? - raise ArgumentError, 'A key is required to write a ' + - 'cookie containing the session data. Use ' + - 'config.session_store SESSION_STORE, { :key => ' + - '"_myapp_session" } in config/application.rb' - end - end + def extract_session_id(env) + stale_session_check! { super } + end - def stale_session_check! - yield - rescue ArgumentError => argument_error - if argument_error.message =~ %r{undefined class/module ([\w:]*\w)} - begin - # Note that the regexp does not allow $1 to end with a ':' - $1.constantize - rescue LoadError, NameError => const_error - raise ActionDispatch::Session::SessionRestoreError, "Session contains objects whose class definition isn't available.\nRemember to require the classes for all objects kept in the session.\n(Original exception: #{const_error.message} [#{const_error.class}])\n" - end - retry - else - raise + def stale_session_check! + yield + rescue ArgumentError => argument_error + if argument_error.message =~ %r{undefined class/module ([\w:]*\w)} + begin + # Note that the regexp does not allow $1 to end with a ':' + $1.constantize + rescue LoadError, NameError => const_error + raise ActionDispatch::Session::SessionRestoreError, "Session contains objects whose class definition isn't available.\nRemember to require the classes for all objects kept in the session.\n(Original exception: #{const_error.message} [#{const_error.class}])\n" end + retry + else + raise end + end + end - def exists?(env) - current_session_id(env).present? - end - - def get_session(env, sid) - raise '#get_session needs to be implemented.' - end + class AbstractStore < Rack::Session::Abstract::ID + include Compatibility + include StaleSessionCheck - def set_session(env, sid, session_data) - raise '#set_session needs to be implemented and should return ' << - 'the value to be stored in the cookie (usually the sid)' - end + def destroy_session(env, sid, options) + ActiveSupport::Deprecation.warn "Implementing #destroy in session stores is deprecated. " << + "Please implement destroy_session(env, session_id, options) instead." + destroy(env) + end - def destroy(env) - raise '#destroy needs to be implemented.' - end + def destroy(env) + raise '#destroy needs to be implemented.' + end end end end diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb index ca1494425f..9c9ccc62f5 100644 --- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb @@ -1,5 +1,7 @@ require 'active_support/core_ext/hash/keys' require 'active_support/core_ext/object/blank' +require 'action_dispatch/middleware/session/abstract_store' +require 'rack/session/cookie' module ActionDispatch module Session @@ -38,58 +40,32 @@ module ActionDispatch # "rake secret" and set the key in config/initializers/secret_token.rb. # # Note that changing digest or secret invalidates all existing sessions! - class CookieStore < AbstractStore - - def initialize(app, options = {}) - super(app, options.merge!(:cookie_only => true)) - freeze - end + class CookieStore < Rack::Session::Cookie + include Compatibility + include StaleSessionCheck private - def load_session(env) - data = unpacked_cookie_data(env) - data = persistent_session_id!(data) - [data["session_id"], data] - end - - def extract_session_id(env) - if data = unpacked_cookie_data(env) - data["session_id"] - else - nil - end - end - - def unpacked_cookie_data(env) - env["action_dispatch.request.unsigned_session_cookie"] ||= begin - stale_session_check! do - request = ActionDispatch::Request.new(env) - if data = request.cookie_jar.signed[@key] - data.stringify_keys! - end - data || {} + def unpacked_cookie_data(env) + env["action_dispatch.request.unsigned_session_cookie"] ||= begin + stale_session_check! do + request = ActionDispatch::Request.new(env) + if data = request.cookie_jar.signed[@key] + data.stringify_keys! end + data || {} end end + end - def set_cookie(request, options) - request.cookie_jar.signed[@key] = options - end - - def set_session(env, sid, session_data) - persistent_session_id!(session_data, sid) - end - - def destroy(env) - # session data is stored on client; nothing to do here - end + def set_session(env, sid, session_data, options) + persistent_session_id!(session_data, sid) + end - def persistent_session_id!(data, sid=nil) - data ||= {} - data["session_id"] ||= sid || generate_sid - data - end + def set_cookie(env, session_id, cookie) + request = ActionDispatch::Request.new(env) + request.cookie_jar.signed[@key] = cookie + end end end end diff --git a/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb b/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb index 28e3dbd732..4dd9a946c2 100644 --- a/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb @@ -1,56 +1,17 @@ +require 'action_dispatch/middleware/session/abstract_store' +require 'rack/session/memcache' + module ActionDispatch module Session - class MemCacheStore < AbstractStore + class MemCacheStore < Rack::Session::Memcache + include Compatibility + include StaleSessionCheck + def initialize(app, options = {}) require 'memcache' - - # Support old :expires option options[:expire_after] ||= options[:expires] - - super - - @default_options = { - :namespace => 'rack:session', - :memcache_server => 'localhost:11211' - }.merge(@default_options) - - @pool = options[:cache] || MemCache.new(@default_options[:memcache_server], @default_options) - unless @pool.servers.any? { |s| s.alive? } - raise "#{self} unable to find server during initialization." - end - @mutex = Mutex.new - super end - - private - def get_session(env, sid) - sid ||= generate_sid - begin - session = @pool.get(sid) || {} - rescue MemCache::MemCacheError, Errno::ECONNREFUSED - session = {} - end - [sid, session] - end - - def set_session(env, sid, session_data) - options = env['rack.session.options'] - expiry = options[:expire_after] || 0 - @pool.set(sid, session_data, expiry) - sid - rescue MemCache::MemCacheError, Errno::ECONNREFUSED - false - end - - def destroy(env) - if sid = current_session_id(env) - @pool.delete(sid) - end - rescue MemCache::MemCacheError, Errno::ECONNREFUSED - false - end - end end end -- cgit v1.2.3 From 74dd8a3681c6984ea35c879f88c6a87521b58ec2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 22 Sep 2010 21:40:14 +0200 Subject: Move ETag and ConditionalGet logic from AD::Response to the middleware stack. --- actionpack/lib/action_dispatch/http/cache.rb | 22 +--------------------- actionpack/lib/action_dispatch/http/response.rb | 2 +- 2 files changed, 2 insertions(+), 22 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb index 047fab006e..4061222d11 100644 --- a/actionpack/lib/action_dispatch/http/cache.rb +++ b/actionpack/lib/action_dispatch/http/cache.rb @@ -50,8 +50,7 @@ module ActionDispatch if cache_control = self["Cache-Control"] cache_control.split(/,\s*/).each do |segment| first, last = segment.split("=") - last ||= true - @cache_control[first.to_sym] = last + @cache_control[first.to_sym] = last || true end end end @@ -88,28 +87,9 @@ module ActionDispatch def handle_conditional_get! if etag? || last_modified? || !@cache_control.empty? set_conditional_cache_control! - elsif nonempty_ok_response? - self.etag = body - - if request && request.etag_matches?(etag) - self.status = 304 - self.body = [] - end - - set_conditional_cache_control! - else - headers["Cache-Control"] = "no-cache" end end - def nonempty_ok_response? - @status == 200 && string_body? - end - - def string_body? - !@blank && @body.respond_to?(:all?) && @body.all? { |part| part.is_a?(String) } - end - DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate" def set_conditional_cache_control! diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index 151c90167b..72871e328a 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -132,7 +132,7 @@ module ActionDispatch # :nodoc: # information. attr_accessor :charset, :content_type - CONTENT_TYPE = "Content-Type" + CONTENT_TYPE = "Content-Type" cattr_accessor(:default_charset) { "utf-8" } -- cgit v1.2.3 From 653acac069e66f53b791caa4838a1e25de905f31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 3 Oct 2010 21:45:27 +0200 Subject: Solve some warnings and a failing test. --- actionpack/lib/action_dispatch/http/request.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 09d6ba8223..bbcdefb190 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -199,7 +199,7 @@ module ActionDispatch # TODO This should be broken apart into AD::Request::Session and probably # be included by the session middleware. def reset_session - session.destroy if session + session.destroy if session && session.respond_to?(:destroy) self.session = {} @env['action_dispatch.request.flash_hash'] = nil end -- cgit v1.2.3 From 3986fcb935c8d5b89ecb86b2f1cbb463460182de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 4 Oct 2010 08:47:36 +0200 Subject: Initialize sid should just skip instance variables. --- .../lib/action_dispatch/middleware/session/abstract_store.rb | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index 679ba7fc8e..64d3a87fd0 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -31,6 +31,13 @@ module ActionDispatch def generate_sid ActiveSupport::SecureRandom.hex(16) end + + protected + + def initialize_sid + @default_options.delete(:sidbits) + @default_options.delete(:secure_random) + end end module StaleSessionCheck -- cgit v1.2.3 From 0b51f3cc73ac21ed56b45a15fcce1d31beb7170c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 4 Oct 2010 18:06:04 +0200 Subject: Ensure the proper content type is returned for static files. --- actionpack/lib/action_dispatch/middleware/static.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index cf13938331..913b899e20 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -6,13 +6,13 @@ module ActionDispatch @at, @root = at.chomp('/'), root.chomp('/') @compiled_at = (Regexp.compile(/^#{Regexp.escape(at)}/) unless @at.blank?) @compiled_root = Regexp.compile(/^#{Regexp.escape(root)}/) - @file_server = ::Rack::File.new(root) + @file_server = ::Rack::File.new(@root) end def match?(path) path = path.dup - if @compiled_at.blank? || path.sub!(@compiled_at, '') - full_path = File.join(@root, ::Rack::Utils.unescape(path)) + if !@compiled_at || path.sub!(@compiled_at, '') + full_path = path.empty? ? @root : File.join(@root, ::Rack::Utils.unescape(path)) paths = "#{full_path}#{ext}" matches = Dir[paths] -- cgit v1.2.3 From 28bb1885f5a35d0adecd35d38b73751d737891c4 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 4 Oct 2010 16:08:01 -0700 Subject: avoid method call to compact --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 47aed0273c..bf10f81127 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -171,13 +171,13 @@ module ActionDispatch end def blocks + block = @scope[:blocks] || [] + if @options[:constraints].present? && !@options[:constraints].is_a?(Hash) - block = @options[:constraints] - else - block = nil + block << @options[:constraints] end - ((@scope[:blocks] || []) + [ block ]).compact + block end def constraints -- cgit v1.2.3 From 2a3022db7f2ddc0fc0e678ea757f97902c5f5c01 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 4 Oct 2010 16:56:45 -0700 Subject: delegate to the @tempfile instance variable --- actionpack/lib/action_dispatch/http/upload.rb | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb index 49465d820e..bfbe7c5305 100644 --- a/actionpack/lib/action_dispatch/http/upload.rb +++ b/actionpack/lib/action_dispatch/http/upload.rb @@ -2,27 +2,19 @@ require 'active_support/core_ext/object/blank' module ActionDispatch module Http - class UploadedFile < Tempfile + class UploadedFile attr_accessor :original_filename, :content_type, :tempfile, :headers def initialize(hash) @original_filename = hash[:filename] @content_type = hash[:type] @headers = hash[:head] - - # To the untrained eye, this may appear as insanity. Given the alternatives, - # such as busting the method cache on every request or breaking backwards - # compatibility with is_a?(Tempfile), this solution is the best available - # option. - # - # TODO: Deprecate is_a?(Tempfile) and define a real API for this parameter - tempfile = hash[:tempfile] - tempfile.instance_variables.each do |ivar| - instance_variable_set(ivar, tempfile.instance_variable_get(ivar)) - end + @tempfile = hash[:tempfile] end - alias local_path path + def method_missing(name, *args, &block) + @tempfile.send(name, *args, &block) + end end module Upload -- cgit v1.2.3 From 8a9747021085c569f0118db1093bc12cfa2ba915 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 4 Oct 2010 17:08:25 -0700 Subject: raising an argument error if tempfile is not provided --- actionpack/lib/action_dispatch/http/upload.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb index bfbe7c5305..d4fabe1eaf 100644 --- a/actionpack/lib/action_dispatch/http/upload.rb +++ b/actionpack/lib/action_dispatch/http/upload.rb @@ -10,6 +10,7 @@ module ActionDispatch @content_type = hash[:type] @headers = hash[:head] @tempfile = hash[:tempfile] + raise(ArgumentError, ':tempfile is required') unless @tempfile end def method_missing(name, *args, &block) -- cgit v1.2.3 From 3370ad0b1e883c9ec24c771f6c52b296a71eff40 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 4 Oct 2010 17:11:50 -0700 Subject: making sure respond_to? works properly --- actionpack/lib/action_dispatch/http/upload.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb index d4fabe1eaf..53f8039121 100644 --- a/actionpack/lib/action_dispatch/http/upload.rb +++ b/actionpack/lib/action_dispatch/http/upload.rb @@ -13,7 +13,12 @@ module ActionDispatch raise(ArgumentError, ':tempfile is required') unless @tempfile end + def respond_to?(name) + super || @tempfile.respond_to?(name) + end + def method_missing(name, *args, &block) + return super unless respond_to?(name) @tempfile.send(name, *args, &block) end end -- cgit v1.2.3 From 12173396163616e077f761e190c13beb43d536bd Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 4 Oct 2010 19:28:40 -0700 Subject: only forwarding enough methods to work. People should grab the delegate tempfile if they really need to do hard work --- actionpack/lib/action_dispatch/http/upload.rb | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb index 53f8039121..84e58d7d6a 100644 --- a/actionpack/lib/action_dispatch/http/upload.rb +++ b/actionpack/lib/action_dispatch/http/upload.rb @@ -13,13 +13,16 @@ module ActionDispatch raise(ArgumentError, ':tempfile is required') unless @tempfile end - def respond_to?(name) - super || @tempfile.respond_to?(name) + def read(*args) + @tempfile.read(*args) end - def method_missing(name, *args, &block) - return super unless respond_to?(name) - @tempfile.send(name, *args, &block) + def rewind + @tempfile.rewind + end + + def size + @tempfile.size end end -- cgit v1.2.3 From 067c1aa0e098f293a99953c50babaf201bba60cd Mon Sep 17 00:00:00 2001 From: Andrew White Date: Fri, 8 Oct 2010 22:00:27 +0100 Subject: Refactor resource action scope methods --- actionpack/lib/action_dispatch/routing/mapper.rb | 58 ++++++++---------------- 1 file changed, 20 insertions(+), 38 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index bf10f81127..3c7dcea003 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -735,15 +735,15 @@ module ActionDispatch resource_scope(SingletonResource.new(resources.pop, options)) do yield if block_given? - collection_scope do + collection do post :create end if parent_resource.actions.include?(:create) - new_scope do + new do get :new end if parent_resource.actions.include?(:new) - member_scope do + member do get :edit if parent_resource.actions.include?(:edit) get :show if parent_resource.actions.include?(:show) put :update if parent_resource.actions.include?(:update) @@ -780,16 +780,16 @@ module ActionDispatch resource_scope(Resource.new(resources.pop, options)) do yield if block_given? - collection_scope do + collection do get :index if parent_resource.actions.include?(:index) post :create if parent_resource.actions.include?(:create) end - new_scope do + new do get :new end if parent_resource.actions.include?(:new) - member_scope do + member do get :edit if parent_resource.actions.include?(:edit) get :show if parent_resource.actions.include?(:show) put :update if parent_resource.actions.include?(:update) @@ -813,12 +813,14 @@ module ActionDispatch # create the search_photos_url and search_photos_path # route helpers. def collection - unless @scope[:scope_level] == :resources - raise ArgumentError, "can't use collection outside resources scope" + unless resource_scope? + raise ArgumentError, "can't use collection outside resource(s) scope" end - collection_scope do - yield + with_scope_level(:collection) do + scope(parent_resource.collection_scope) do + yield + end end end @@ -838,8 +840,10 @@ module ActionDispatch raise ArgumentError, "can't use member outside resource(s) scope" end - member_scope do - yield + with_scope_level(:member) do + scope(parent_resource.member_scope) do + yield + end end end @@ -848,8 +852,10 @@ module ActionDispatch raise ArgumentError, "can't use new outside resource(s) scope" end - new_scope do - yield + with_scope_level(:new) do + scope(parent_resource.new_scope(action_path(:new))) do + yield + end end end @@ -1034,30 +1040,6 @@ module ActionDispatch end end - def new_scope - with_scope_level(:new) do - scope(parent_resource.new_scope(action_path(:new))) do - yield - end - end - end - - def collection_scope - with_scope_level(:collection) do - scope(parent_resource.collection_scope) do - yield - end - end - end - - def member_scope - with_scope_level(:member) do - scope(parent_resource.member_scope) do - yield - end - end - end - def nested_options {}.tap do |options| options[:as] = parent_resource.member_name -- cgit v1.2.3 From 3eff729079a1a9e717e7872bdae19c8703b280ac Mon Sep 17 00:00:00 2001 From: Miles Egan Date: Sun, 18 Jul 2010 09:10:20 -0700 Subject: make sure request parameters are accessible after rack throws an exception parsing the query string [#3030 state:resolved] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/request.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index bbcdefb190..55a3166f6d 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -214,13 +214,13 @@ module ActionDispatch # Override Rack's GET method to support indifferent access def GET - @env["action_dispatch.request.query_parameters"] ||= normalize_parameters(super) + @env["action_dispatch.request.query_parameters"] ||= (normalize_parameters(super) || {}) end alias :query_parameters :GET # Override Rack's POST method to support indifferent access def POST - @env["action_dispatch.request.request_parameters"] ||= normalize_parameters(super) + @env["action_dispatch.request.request_parameters"] ||= (normalize_parameters(super) || {}) end alias :request_parameters :POST -- cgit v1.2.3 From dde54f00c6c08d1704d011d8108106076e8ea033 Mon Sep 17 00:00:00 2001 From: Les Hill and Sandro Turriate Date: Mon, 11 Oct 2010 10:55:07 -0400 Subject: Show exceptions rescues the original exception MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [#5784 state:resolved] Signed-off-by: José Valim --- .../lib/action_dispatch/middleware/show_exceptions.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index ef0c9c51f5..71e736ce9f 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -62,6 +62,7 @@ module ActionDispatch private def render_exception(env, exception) log_error(exception) + exception = original_exception(exception) request = Request.new(env) if @consider_all_requests_local || request.local? @@ -154,5 +155,17 @@ module ActionDispatch def logger defined?(Rails.logger) ? Rails.logger : Logger.new($stderr) end + + def original_exception(exception) + if registered_original_exception?(exception) + exception.original_exception + else + exception + end + end + + def registered_original_exception?(exception) + exception.respond_to?(:original_exception) && @@rescue_responses.has_key?(exception.original_exception.class.name) + end end end -- cgit v1.2.3 From 7b2ec381ca5ce88fe62a0a42183b3a5df63ee68b Mon Sep 17 00:00:00 2001 From: Krekoten' Marjan Date: Mon, 18 Oct 2010 00:08:41 +0300 Subject: Change def to attr_reader + alias MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/cache.rb | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb index 4061222d11..1d2f7e4f19 100644 --- a/actionpack/lib/action_dispatch/http/cache.rb +++ b/actionpack/lib/action_dispatch/http/cache.rb @@ -39,7 +39,8 @@ module ActionDispatch end module Response - attr_reader :cache_control + attr_reader :cache_control, :etag + alias :etag? :etag def initialize(*) status, header, body = super @@ -69,14 +70,6 @@ module ActionDispatch headers['Last-Modified'] = utc_time.httpdate end - def etag - @etag - end - - def etag? - @etag - end - def etag=(etag) key = ActiveSupport::Cache.expand_cache_key(etag) @etag = self["ETag"] = %("#{Digest::MD5.hexdigest(key)}") @@ -99,7 +92,7 @@ module ActionDispatch if control.empty? headers["Cache-Control"] = DEFAULT_CACHE_CONTROL - elsif @cache_control[:no_cache] + elsif control[:no_cache] headers["Cache-Control"] = "no-cache" else extras = control[:extras] -- cgit v1.2.3 From a75d21df06d0b7af21921aad38b021056aa15e63 Mon Sep 17 00:00:00 2001 From: Krekoten' Marjan Date: Mon, 18 Oct 2010 22:00:48 +0300 Subject: Fix status initialization when custom status provided Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/http/response.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index 72871e328a..8e03a7879f 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -44,8 +44,8 @@ module ActionDispatch # :nodoc: @block = nil @length = 0 - @status, @header = status, header - self.body = body + @header = header + self.body, self.status = body, status @cookie = [] @sending_file = false -- cgit v1.2.3 From d3d724bb8809906ebae3abbd2c4a11c8a4aec268 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Wed, 20 Oct 2010 12:50:27 -0200 Subject: Remove this require since active_support/testing/default doesn't exist anymore --- actionpack/lib/action_dispatch/testing/performance_test.rb | 1 - 1 file changed, 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/performance_test.rb b/actionpack/lib/action_dispatch/testing/performance_test.rb index d6c98b4db7..e7aeb45fb3 100644 --- a/actionpack/lib/action_dispatch/testing/performance_test.rb +++ b/actionpack/lib/action_dispatch/testing/performance_test.rb @@ -1,5 +1,4 @@ require 'active_support/testing/performance' -require 'active_support/testing/default' begin module ActionDispatch -- cgit v1.2.3 From 2d5a12a50bcd83fcc99865de759b82e661b28698 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Fri, 22 Oct 2010 15:34:45 +0100 Subject: Don't write out secure cookies unless the request is secure --- actionpack/lib/action_dispatch/middleware/cookies.rb | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index 75c8cc3dd0..836416857c 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -98,17 +98,19 @@ module ActionDispatch def self.build(request) secret = request.env[TOKEN_KEY] host = request.host + secure = request.ssl? - new(secret, host).tap do |hash| + new(secret, host, secure).tap do |hash| hash.update(request.cookies) end end - def initialize(secret = nil, host = nil) + def initialize(secret = nil, host = nil, secure = false) @secret = secret @set_cookies = {} @delete_cookies = {} @host = host + @secure = secure super() end @@ -193,9 +195,15 @@ module ActionDispatch end def write(headers) - @set_cookies.each { |k, v| ::Rack::Utils.set_cookie_header!(headers, k, v) } + @set_cookies.each { |k, v| ::Rack::Utils.set_cookie_header!(headers, k, v) if write_cookie?(v) } @delete_cookies.each { |k, v| ::Rack::Utils.delete_cookie_header!(headers, k, v) } end + + private + + def write_cookie?(cookie) + @secure || !cookie[:secure] || Rails.env.development? + end end class PermanentCookieJar < CookieJar #:nodoc: -- cgit v1.2.3 From 69a1a0adb5d4e615f08e8b1d23d9a6b0e2dd6070 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 26 Oct 2010 14:05:06 -0200 Subject: Remove rack-cache-purge. --- actionpack/lib/action_dispatch/http/rack_cache.rb | 9 --------- 1 file changed, 9 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/rack_cache.rb b/actionpack/lib/action_dispatch/http/rack_cache.rb index e5914abc81..b5c1435903 100644 --- a/actionpack/lib/action_dispatch/http/rack_cache.rb +++ b/actionpack/lib/action_dispatch/http/rack_cache.rb @@ -21,11 +21,6 @@ module ActionDispatch @store.write(key, value) end - def purge(key) - @store.delete(key) - nil - end - ::Rack::Cache::MetaStore::RAILS = self end @@ -58,10 +53,6 @@ module ActionDispatch [key, size] end - def purge(key) - @store.delete(key) - end - ::Rack::Cache::EntityStore::RAILS = self end end -- cgit v1.2.3 From 0dfdbdd4f447ada9b4d6653f34f609802ae597a5 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 26 Oct 2010 11:31:05 -0700 Subject: Fix loop introduced by rack:dda892d --- actionpack/lib/action_dispatch/http/url.rb | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index cfee95eb4b..4da82f958a 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -8,11 +8,6 @@ module ActionDispatch protocol + host_with_port + fullpath end - # Returns 'https' if this is an SSL request and 'http' otherwise. - def scheme - ssl? ? 'https' : 'http' - end - # Returns 'https://' if this is an SSL request and 'http://' otherwise. def protocol @protocol ||= ssl? ? 'https://' : 'http://' @@ -99,4 +94,4 @@ module ActionDispatch end end end -end \ No newline at end of file +end -- cgit v1.2.3 From 47ceb135c6b75988f2712bc44db397b992c1c731 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Wed, 27 Oct 2010 10:30:14 +0100 Subject: Ensure that Rails.env is defined first --- actionpack/lib/action_dispatch/middleware/cookies.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index 836416857c..c4c2e1acd7 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -202,7 +202,7 @@ module ActionDispatch private def write_cookie?(cookie) - @secure || !cookie[:secure] || Rails.env.development? + @secure || !cookie[:secure] || defined?(Rails.env) && Rails.env.development? end end -- cgit v1.2.3 From d446392f76c063d9f04396a1d3ca9e314a521671 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Tue, 2 Nov 2010 10:47:32 +0000 Subject: Add additional HTTP request methods from the following RFCs: * Hypertext Transfer Protocol -- HTTP/1.1 http://www.ietf.org/rfc/rfc2616.txt) * HTTP Extensions for Distributed Authoring -- WEBDAV http://www.ietf.org/rfc/rfc2518.txt * Versioning Extensions to WebDAV http://www.ietf.org/rfc/rfc3253.txt * Ordered Collections Protocol (WebDAV) http://www.ietf.org/rfc/rfc3648.txt * Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol http://www.ietf.org/rfc/rfc3744.txt * Web Distributed Authoring and Versioning (WebDAV) SEARCH http://www.ietf.org/rfc/rfc5323.txt * PATCH Method for HTTP http://www.ietf.org/rfc/rfc5789.txt [#2809 state:resolved] [#5895 state:resolved] --- actionpack/lib/action_dispatch/http/request.rb | 21 +++++++++++++++++++-- actionpack/lib/action_dispatch/routing/mapper.rb | 5 +++-- 2 files changed, 22 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 55a3166f6d..08f30e068d 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -4,6 +4,7 @@ require 'strscan' require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/string/access' +require 'active_support/inflector' require 'action_dispatch/http/headers' module ActionDispatch @@ -44,8 +45,24 @@ module ActionDispatch @env.key?(key) end - HTTP_METHODS = %w(get head put post delete options) - HTTP_METHOD_LOOKUP = HTTP_METHODS.inject({}) { |h, m| h[m] = h[m.upcase] = m.to_sym; h } + # List of HTTP request methods from the following RFCs: + # Hypertext Transfer Protocol -- HTTP/1.1 (http://www.ietf.org/rfc/rfc2616.txt) + # HTTP Extensions for Distributed Authoring -- WEBDAV (http://www.ietf.org/rfc/rfc2518.txt) + # Versioning Extensions to WebDAV (http://www.ietf.org/rfc/rfc3253.txt) + # Ordered Collections Protocol (WebDAV) (http://www.ietf.org/rfc/rfc3648.txt) + # Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol (http://www.ietf.org/rfc/rfc3744.txt) + # Web Distributed Authoring and Versioning (WebDAV) SEARCH (http://www.ietf.org/rfc/rfc5323.txt) + # PATCH Method for HTTP (http://www.ietf.org/rfc/rfc5789.txt) + RFC2616 = %w(OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT) + RFC2518 = %w(PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK) + RFC3253 = %w(VERSION-CONTROL REPORT CHECKOUT CHECKIN UNCHECKOUT MKWORKSPACE UPDATE LABEL MERGE BASELINE-CONTROL MKACTIVITY) + RFC3648 = %w(ORDERPATCH) + RFC3744 = %w(ACL) + RFC5323 = %w(SEARCH) + RFC5789 = %w(PATCH) + + HTTP_METHODS = RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC5789 + HTTP_METHOD_LOOKUP = Hash.new { |h, m| h[m] = m.underscore.to_sym if HTTP_METHODS.include?(m) } # Returns the HTTP \method that the application should see. # In the case where the \method was overridden by a middleware diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 3c7dcea003..1bbb4f1f92 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1,6 +1,7 @@ require 'erb' require 'active_support/core_ext/hash/except' require 'active_support/core_ext/object/blank' +require 'active_support/inflector' module ActionDispatch module Routing @@ -186,8 +187,8 @@ module ActionDispatch def request_method_condition if via = @options[:via] - via = Array(via).map { |m| m.to_s.upcase } - { :request_method => Regexp.union(*via) } + via = Array(via).map { |m| m.to_s.dasherize.upcase } + { :request_method => %r[^#{via.join('|')}$] } else { } end -- cgit v1.2.3 From 203e45cd7fcbcb2ca548f778482c3ad0ad82d691 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 10:26:18 +1000 Subject: Add further documentation + examples for the get, post, put and delete methods in ActionDispatch::Routing::Mapper::HttpHelpers --- actionpack/lib/action_dispatch/routing/mapper.rb | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 3c7dcea003..c58562db24 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -323,21 +323,41 @@ module ActionDispatch module HttpHelpers # Define a route that only recognizes HTTP GET. + # For supported arguments, see +match+. + # + # Example: + # + # get 'bacon', :to => 'food#bacon' def get(*args, &block) map_method(:get, *args, &block) end # Define a route that only recognizes HTTP POST. + # For supported arguments, see +match+. + # + # Example: + # + # post 'bacon', :to => 'food#bacon' def post(*args, &block) map_method(:post, *args, &block) end # Define a route that only recognizes HTTP PUT. + # For supported arguments, see +match+. + # + # Example: + # + # put 'bacon', :to => 'food#bacon' def put(*args, &block) map_method(:put, *args, &block) end - # Define a route that only recognizes HTTP DELETE. + # Define a route that only recognizes HTTP PUT. + # For supported arguments, see +match+. + # + # Example: + # + # delete 'broccoli', :to => 'food#broccoli' def delete(*args, &block) map_method(:delete, *args, &block) end -- cgit v1.2.3 From 433e1aca868b148493421b7d3f554c65f50a14ee Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 10:33:06 +1000 Subject: Fix where the documentation says "photos", but the example shows "posts" or "comments" by switching both to simply "posts" --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index c58562db24..9c5fee9914 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -426,22 +426,22 @@ module ActionDispatch # PUT /admin/photos/1 # DELETE /admin/photos/1 # - # If you want to route /photos (without the prefix /admin) to + # If you want to route /posts (without the prefix /admin) to # Admin::PostsController, you could use # # scope :module => "admin" do - # resources :posts, :comments + # resources :posts # end # # or, for a single case # # resources :posts, :module => "admin" # - # If you want to route /admin/photos to PostsController + # If you want to route /admin/posts to PostsController # (without the Admin:: module prefix), you could use # # scope "/admin" do - # resources :posts, :comments + # resources :posts # end # # or, for a single case -- cgit v1.2.3 From 35c7ca5c3728acffad42a9a77b98f4a098114de5 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 10:34:45 +1000 Subject: Separate comments and examples with "Examples" header. --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 9c5fee9914..d21e1285b3 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -468,6 +468,8 @@ module ActionDispatch # Used to route /photos (without the prefix /admin) # to Admin::PostsController: # + # Examples: + # # scope :module => "admin" do # resources :posts # end -- cgit v1.2.3 From 5040ecbfea931ba20439c7e84f2bdf261edd2732 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 10:38:45 +1000 Subject: Document the :module and :path options for the scope method. --- actionpack/lib/action_dispatch/routing/mapper.rb | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index d21e1285b3..9ff7481c1f 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -467,12 +467,21 @@ module ActionDispatch # Used to route /photos (without the prefix /admin) # to Admin::PostsController: + # === Supported options + # [:module] + # If you want to route /posts (without the prefix /admin) to + # Admin::PostsController, you could use # - # Examples: + # scope :module => "admin" do + # resources :posts + # end + # [:path] + # If you want to prefix the route, you could use # - # scope :module => "admin" do - # resources :posts - # end + # scope :path => "/admin" do + # resources :posts + # end + # This will prefix all of the +posts+ resource's requests with '/admin' def scope(*args) options = args.extract_options! options = options.dup -- cgit v1.2.3 From 5f7f3adccd2ddc1d307e4e5ea4a323562b1cf7ff Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 10:42:33 +1000 Subject: Document the defaults method --- actionpack/lib/action_dispatch/routing/mapper.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 9ff7481c1f..e760eb0196 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -534,6 +534,11 @@ module ActionDispatch scope(:constraints => constraints) { yield } 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 + # Using this, the +:id+ parameter here will default to 'home'. def defaults(defaults = {}) scope(:defaults => defaults) { yield } end -- cgit v1.2.3 From e5eece41b5ac740f8a137b3228d052273c641099 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 11:49:57 +1000 Subject: Document the controller method for AD's Mapper --- actionpack/lib/action_dispatch/routing/mapper.rb | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index e760eb0196..48afca56d8 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -518,6 +518,12 @@ module ActionDispatch @scope[:blocks] = recover[:block] end + # Scopes routes to a specific controller + # + # Example: + # controller "food" do + # match "bacon", :action => "bacon" + # end def controller(controller, options={}) options[:controller] = controller scope(options) { yield } -- cgit v1.2.3 From 379939e1e00519e819c71a53c28f9032f473aa04 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 12:04:25 +1000 Subject: Begin to document the namespace method for AD's Mapper --- actionpack/lib/action_dispatch/routing/mapper.rb | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 48afca56d8..10b1342f30 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -529,6 +529,21 @@ module ActionDispatch scope(options) { yield } end + # Scopes routes to a specific namespace. For example: + # + # namespace :admin do + # resources :posts + # end + # + # This generates the following routes: + # + # admin_posts GET /admin/posts(.:format) {:action=>"index", :controller=>"admin/posts"} + # admin_posts POST /admin/posts(.:format) {:action=>"create", :controller=>"admin/posts"} + # new_admin_post GET /admin/posts/new(.:format) {:action=>"new", :controller=>"admin/posts"} + # edit_admin_post GET /admin/posts/:id/edit(.:format) {:action=>"edit", :controller=>"admin/posts"} + # 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"} def namespace(path, options = {}) path = path.to_s options = { :path => path, :as => path, :module => path, -- cgit v1.2.3 From 0eef4e3bfb3435f2906c70c19ff896393f94abdf Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 12:05:14 +1000 Subject: Document the :path option for namespace --- actionpack/lib/action_dispatch/routing/mapper.rb | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 10b1342f30..f0d3ef80ab 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -544,6 +544,17 @@ 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+ all default to the name of the namespace. + # + # [:path] + # The path prefix for the routes. + # + # namespace :admin, :path => "sekret" do + # resources :posts + # end + # def namespace(path, options = {}) path = path.to_s options = { :path => path, :as => path, :module => path, -- cgit v1.2.3 From 66d1276d7f38ddb002f1dd48e77cea383497f57d Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 12:05:55 +1000 Subject: Document the :module option for namespace --- actionpack/lib/action_dispatch/routing/mapper.rb | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f0d3ef80ab..34d49591e2 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -555,6 +555,21 @@ module ActionDispatch # resources :posts # end # + # 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 + # + # The +PostsController+ here should go in the +Sekret+ namespace and so it should be defined like this: + # + # class Sekret::PostsController < ApplicationController + # # code go here + # end + # def namespace(path, options = {}) path = path.to_s options = { :path => path, :as => path, :module => path, -- cgit v1.2.3 From 6ca042b3e4078b694e827e0f3de51712a0cb4420 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 12:07:29 +1000 Subject: Document the :as option for the namespace method --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 34d49591e2..73c2ac3497 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -570,6 +570,14 @@ module ActionDispatch # # code go here # end # + # [:as] + # Changes the name used in routing helpers for this namespace. + # + # namespace :admin, :as => "sekret" do + # resources :posts + # end + # + # Routing helpers such as +admin_posts_path+ will now be +sekret_posts_path+. def namespace(path, options = {}) path = path.to_s options = { :path => path, :as => path, :module => path, -- cgit v1.2.3 From 4a6150a3ebf8e67be4547ac600419d6a68b6ffe1 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 12:09:38 +1000 Subject: Fix indentation on comment for :path option --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 73c2ac3497..939d546f56 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -476,7 +476,7 @@ module ActionDispatch # resources :posts # end # [:path] - # If you want to prefix the route, you could use + # If you want to prefix the route, you could use # # scope :path => "/admin" do # resources :posts -- cgit v1.2.3 From ffe97e338eda6ba2ba946753a8dc4ec64c8968b0 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 12:09:58 +1000 Subject: Space between module option documentation and path documentation --- actionpack/lib/action_dispatch/routing/mapper.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 939d546f56..8244773877 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -475,6 +475,7 @@ module ActionDispatch # scope :module => "admin" do # resources :posts # end + # # [:path] # If you want to prefix the route, you could use # -- cgit v1.2.3 From 7d83673134502b01bcb2fa3be07fdb84c61bb175 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 12:11:39 +1000 Subject: Document the :as option for the scope method --- actionpack/lib/action_dispatch/routing/mapper.rb | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 8244773877..ba0911c635 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -482,7 +482,17 @@ module ActionDispatch # scope :path => "/admin" do # resources :posts # end + # # This will prefix all of the +posts+ resource's requests with '/admin' + # + # [:as] + # Prefixes the routing helpers in this scope with the specified label. + # + # scope :as => "sekret" do + # resources :posts + # end + # + # Helpers such as +posts_path+ will now be +sekret_posts_path+ def scope(*args) options = args.extract_options! options = options.dup -- cgit v1.2.3 From ee646788fc7f8ce0f087dd0afa82fa28cfdffeb9 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 12:17:36 +1000 Subject: Indent code example for :as option --- actionpack/lib/action_dispatch/routing/mapper.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index ba0911c635..b39cc5beb6 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -488,9 +488,9 @@ module ActionDispatch # [:as] # Prefixes the routing helpers in this scope with the specified label. # - # scope :as => "sekret" do - # resources :posts - # end + # scope :as => "sekret" do + # resources :posts + # end # # Helpers such as +posts_path+ will now be +sekret_posts_path+ def scope(*args) -- cgit v1.2.3 From e6aed6b6a8fd03584141c7dffd73c12ed32ce3d4 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 12:18:19 +1000 Subject: Indent final comment for :path option --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index b39cc5beb6..3e0802f3fc 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -483,7 +483,7 @@ module ActionDispatch # resources :posts # end # - # This will prefix all of the +posts+ resource's requests with '/admin' + # This will prefix all of the +posts+ resource's requests with '/admin' # # [:as] # Prefixes the routing helpers in this scope with the specified label. -- cgit v1.2.3 From ff3a494e2e3cf52193d42ba7ed8252759de57c01 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 12:21:56 +1000 Subject: Document the :shallow_path option for scope --- actionpack/lib/action_dispatch/routing/mapper.rb | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 3e0802f3fc..a7d85dd3b5 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -493,6 +493,25 @@ module ActionDispatch # 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 + # + # 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) def scope(*args) options = args.extract_options! options = options.dup -- cgit v1.2.3 From b591989b5ff472301ba0c99d41268e9682a0651f Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 7 Nov 2010 12:22:39 +1000 Subject: Fix indentation for :as option documentation on the namespace method --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index a7d85dd3b5..2b3c20f6b9 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -601,11 +601,11 @@ module ActionDispatch # end # # [:as] - # Changes the name used in routing helpers for this namespace. + # Changes the name used in routing helpers for this namespace. # - # namespace :admin, :as => "sekret" do - # resources :posts - # end + # namespace :admin, :as => "sekret" do + # resources :posts + # end # # Routing helpers such as +admin_posts_path+ will now be +sekret_posts_path+. def namespace(path, options = {}) -- cgit v1.2.3 From 990f52ebd78df77d73a2187751c6e1bb6d4b6033 Mon Sep 17 00:00:00 2001 From: David Trasbo Date: Wed, 13 Oct 2010 20:58:25 +0200 Subject: Make cookies hash in ActionDispatch::TestProcess indifferent access [#5761 state:committed] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/testing/test_process.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb index c56ebc6438..16f3674164 100644 --- a/actionpack/lib/action_dispatch/testing/test_process.rb +++ b/actionpack/lib/action_dispatch/testing/test_process.rb @@ -22,7 +22,7 @@ module ActionDispatch end def cookies - @request.cookies.merge(@response.cookies) + HashWithIndifferentAccess.new(@request.cookies.merge(@response.cookies)) end def redirect_to_url -- cgit v1.2.3 From ef46b9f21a275249d1b0cf9926ffb879b0ae2c44 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Tue, 9 Nov 2010 05:10:39 +0000 Subject: Strip regexp anchors from rake routes output [#5934 state:resolved] --- actionpack/lib/action_dispatch/routing/route.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route.rb b/actionpack/lib/action_dispatch/routing/route.rb index f91a48e16c..08a8408f25 100644 --- a/actionpack/lib/action_dispatch/routing/route.rb +++ b/actionpack/lib/action_dispatch/routing/route.rb @@ -30,7 +30,8 @@ module ActionDispatch if method = conditions[:request_method] case method when Regexp - method.source.upcase + source = method.source.upcase + source =~ /\A\^[-A-Z|]+\$\Z/ ? source[1..-2] : source else method.to_s.upcase end -- cgit v1.2.3 From b235519777b921c0ecf4e20fbeb5f5fe49459775 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sat, 13 Nov 2010 11:15:17 +0800 Subject: Add documentation for the mount method in ActionDispatch's Mapper --- actionpack/lib/action_dispatch/routing/mapper.rb | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 2b3c20f6b9..c3f778a70f 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -262,6 +262,23 @@ module ActionDispatch self end + # Mount a Rack-based application to be used within the application. + # + # mount SomeRackApp, :at => "some_route" + # + # Alternatively: + # + # mount(SomeRackApp => "some_route") + # + # 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+. + # To customize this helper's name, use the +:as+ option: + # + # mount(SomeRackApp => "some_route", :as => "exciting") + # + # This will generate the +exciting_path+ and +exciting_url+ helpers + # which can be used to navigate to this mounted app. def mount(app, options = nil) if options path = options.delete(:at) -- cgit v1.2.3 From 95f41fe12e7680459351be633a171abf26beac1a Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sat, 13 Nov 2010 11:16:06 +0800 Subject: See the scope method for documentation for namespace's shallow_path option --- actionpack/lib/action_dispatch/routing/mapper.rb | 3 +++ 1 file changed, 3 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index c3f778a70f..cc013ac072 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -625,6 +625,9 @@ module ActionDispatch # end # # Routing helpers such as +admin_posts_path+ will now be +sekret_posts_path+. + # + # [:shallow_path] + # See the +scope+ method. def namespace(path, options = {}) path = path.to_s options = { :path => path, :as => path, :module => path, -- cgit v1.2.3 From fe8446fcced912730b068944b2ce152f18046f77 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sat, 13 Nov 2010 11:16:32 +0800 Subject: Add documentation for :path_names option on resources --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index cc013ac072..8b5d7d307b 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -911,6 +911,14 @@ module ActionDispatch # GET /photos/:id/edit # PUT /photos/:id # DELETE /photos/:id + # === Supported options + # [:path_names] + # Allows you to change the paths of the seven default actions. + # Paths not specified are not changed. + # + # resources :posts, :path_names => { :new => "brand_new" } + # + # The above example will now change /posts/new to /posts/brand_new def resources(*resources, &block) options = resources.extract_options! -- cgit v1.2.3 From 74061f55be2ba83f1457369b7e47cab54d26a57f Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 14 Nov 2010 07:32:54 +0800 Subject: Document the constraints method --- actionpack/lib/action_dispatch/routing/mapper.rb | 56 +++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 8b5d7d307b..2eb2af7a11 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -634,7 +634,61 @@ module ActionDispatch :shallow_path => path, :shallow_prefix => path }.merge!(options) scope(options) { yield } end - + + # === Parameter Restriction + # Allows you to constrain the nested routes based on a set of rules. + # For instance, in order to change the routes to allow for a dot character in the +id+ parameter: + # + # constraints(:id => /\d+\.\d+) do + # resources :posts + # end + # + # Now routes such as +/posts/1+ will no longer be valid, but +/posts/1.1+ will be. + # The +id+ parameter must match the constraint passed in for this example. + # + # You may use this to also resrict other parameters: + # + # resources :posts do + # constraints(:post_id => /\d+\.\d+) do + # resources :comments + # end + # + # === Restricting based on IP + # + # Routes can also be constrained to an IP or a certain range of IP addresses: + # + # constraints(:ip => /192.168.\d+.\d+/) do + # resources :posts + # end + # + # Any user connecting from the 192.168.* range will be able to see this resource, + # where as any user connecting outside of this range will be told there is no such route. + # + # === Dynamic request matching + # + # Requests to routes can be constrained based on specific critera: + # + # constraints(lambda { |req| req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do + # resources :iphones + # end + # + # You are able to move this logic out into a class if it is too complex for routes. + # This class must have a +matches?+ method defined on it which either returns +true+ + # if the user should be given access to that route, or +false+ if the user should not. + # + # class Iphone + # def self.matches(request) + # request.env["HTTP_USER_AGENT"] =~ /iPhone/ + # end + # end + # + # An expected place for this code would be +lib/constraints+. + # + # This class is then used like this: + # + # constraints(Iphone) do + # resources :iphones + # end def constraints(constraints = {}) scope(:constraints => constraints) { yield } end -- cgit v1.2.3 From 0be181bfa03f8340fa4945f891409c25a804de7f Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 15 Nov 2010 13:37:05 -0800 Subject: make sure we are only doing sanity checking against regular expressions --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 63a22ad105..729582684e 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -114,7 +114,7 @@ module ActionDispatch requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints] @options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) } - requirements.each do |_, requirement| + requirements.values.grep(Regexp).each do |requirement| if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z} raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}" end -- cgit v1.2.3 From e4591489d13a27e2f905988be02a7d48fb7a0664 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 15 Nov 2010 14:22:06 -0800 Subject: reduce method calls --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 729582684e..bf3110cc66 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -164,10 +164,10 @@ module ActionDispatch raise ArgumentError, "missing :action" end - { :controller => controller, :action => action }.tap do |hash| - hash.delete(:controller) if hash[:controller].blank? - hash.delete(:action) if hash[:action].blank? - end + hash = {} + hash[:controller] = controller if controller + hash[:action] = action if action + hash end end -- cgit v1.2.3 From 2b2082eb091bb5f51757dd5a321dd092733a0450 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 15 Nov 2010 15:02:18 -0800 Subject: rejecting blank strings --- actionpack/lib/action_dispatch/routing/mapper.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index bf3110cc66..53a52b735e 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -165,8 +165,8 @@ module ActionDispatch end hash = {} - hash[:controller] = controller if controller - hash[:action] = action if action + hash[:controller] = controller unless controller.blank? + hash[:action] = action unless action.blank? hash end end -- cgit v1.2.3 From e1e780a31d56f3bf22f13afd92b7e1274bd4b531 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Tue, 16 Nov 2010 18:49:08 +0800 Subject: Brought the domain method in AD http url inline with subdomain where @@tld_length is used by default. Also set the default value of @@tld_length to 1. --- actionpack/lib/action_dispatch/http/url.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 4da82f958a..9c9eed2c6d 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -2,6 +2,7 @@ module ActionDispatch module Http module URL mattr_accessor :tld_length + self.tld_length = 1 # Returns the complete URL used for this request. def url @@ -67,7 +68,7 @@ module ActionDispatch # Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify # a different tld_length, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk". - def domain(tld_length = 1) + def domain(tld_length = @@tld_length) return nil unless named_host?(host) host.split('.').last(1 + tld_length).join('.') -- cgit v1.2.3 From 401c1835afb5af1a6f429061ac8484227c34909d Mon Sep 17 00:00:00 2001 From: Carl Lerche Date: Tue, 16 Nov 2010 21:46:15 -0800 Subject: Anchors should be allowed on constraints that are not on path segments --- actionpack/lib/action_dispatch/routing/mapper.rb | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 53a52b735e..879ccc5791 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -66,6 +66,18 @@ module ActionDispatch end @options.merge!(default_controller_and_action(to_shorthand)) + + requirements.each do |name, requirement| + # segment_keys.include?(k.to_s) || k == :controller + next unless Regexp === requirement && !constraints[name] + + if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z} + raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}" + end + if requirement.multiline? + raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}" + end + end end # match "account/overview" @@ -113,15 +125,6 @@ module ActionDispatch @requirements ||= (@options[:constraints].is_a?(Hash) ? @options[:constraints] : {}).tap do |requirements| requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints] @options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) } - - requirements.values.grep(Regexp).each do |requirement| - if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z} - raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}" - end - if requirement.multiline? - raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}" - end - end end end -- cgit v1.2.3 From c52e2cf4b3ef22fea6989df906a53188e632b9a4 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 18 Nov 2010 10:10:18 -0800 Subject: delegating path and open to internal tempfile --- actionpack/lib/action_dispatch/http/upload.rb | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb index 84e58d7d6a..37effade4f 100644 --- a/actionpack/lib/action_dispatch/http/upload.rb +++ b/actionpack/lib/action_dispatch/http/upload.rb @@ -1,5 +1,3 @@ -require 'active_support/core_ext/object/blank' - module ActionDispatch module Http class UploadedFile @@ -13,6 +11,14 @@ module ActionDispatch raise(ArgumentError, ':tempfile is required') unless @tempfile end + def open + @tempfile.open + end + + def path + @tempfile.path + end + def read(*args) @tempfile.read(*args) end -- cgit v1.2.3 From 7d5b097357c3bbfb86c95271d1bdbe5148a01069 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Sat, 20 Nov 2010 21:00:44 -0500 Subject: use_accept_header is no longer supported --- actionpack/lib/action_dispatch/http/mime_negotiation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb index b959aa258e..5bb42cca3a 100644 --- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb +++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb @@ -36,7 +36,7 @@ module ActionDispatch # # GET /posts/5.xml | request.format => Mime::XML # GET /posts/5.xhtml | request.format => Mime::HTML - # GET /posts/5 | request.format => Mime::HTML or MIME::JS, or request.accepts.first depending on the value of ActionController::Base.use_accept_header + # GET /posts/5 | request.format => Mime::HTML or MIME::JS, or request.accepts.first # def format(view_path = []) formats.first -- cgit v1.2.3 From 61950a4b05ce1b5640ac3f3720f9a3368ce95a29 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Mon, 22 Nov 2010 02:21:57 -0500 Subject: current code ignores http header "Accept" if it has ....,*/* . MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It is possible to a device to send request such that */* appear at the beginning of the "Accept" header. This patch ensures that "Accept" header is ignored for such cases too. Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/mime_negotiation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb index 5bb42cca3a..afce4d9651 100644 --- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb +++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb @@ -48,7 +48,7 @@ module ActionDispatch @env["action_dispatch.request.formats"] ||= if parameters[:format] Array(Mime[parameters[:format]]) - elsif xhr? || (accept && accept !~ /,\s*\*\/\*/) + elsif xhr? || (accept && accept !~ /,\s*\*\/\*|\*\/\*,/) accepts else [Mime::HTML] -- cgit v1.2.3 From eb6ccc9953a5e952737174995b5230f0b2c56b1f Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Mon, 22 Nov 2010 08:58:01 -0500 Subject: do not assume that there is no space between leading */* and comma MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/mime_negotiation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb index afce4d9651..2b401114f0 100644 --- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb +++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb @@ -48,7 +48,7 @@ module ActionDispatch @env["action_dispatch.request.formats"] ||= if parameters[:format] Array(Mime[parameters[:format]]) - elsif xhr? || (accept && accept !~ /,\s*\*\/\*|\*\/\*,/) + elsif xhr? || (accept && accept !~ /,\s*\*\/\*|\*\/\*\s*,/) accepts else [Mime::HTML] -- cgit v1.2.3 From d04a21b36281a0608cdd72c02e4df3b1136f8887 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Mon, 22 Nov 2010 09:07:44 -0500 Subject: declare regex as a constant MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/mime_negotiation.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb index 2b401114f0..68ba1a81b5 100644 --- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb +++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb @@ -42,13 +42,15 @@ module ActionDispatch formats.first end + BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/ + def formats accept = @env['HTTP_ACCEPT'] @env["action_dispatch.request.formats"] ||= if parameters[:format] Array(Mime[parameters[:format]]) - elsif xhr? || (accept && accept !~ /,\s*\*\/\*|\*\/\*\s*,/) + elsif xhr? || (accept && accept !~ BROWSER_LIKE_ACCEPTS) accepts else [Mime::HTML] -- cgit v1.2.3 From 6f6e754bac4c78f657feb0ea119447546aa87197 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Mon, 22 Nov 2010 11:34:37 -0500 Subject: implement code that handles text/*, appplication/*, and image/* MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/mime_type.rb | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 8f1c9b6691..3b5c1d50f2 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -103,9 +103,14 @@ module Mime ([symbol.to_s] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext] = SET.last } end + def parse(accept_header) if accept_header !~ /,/ - [Mime::Type.lookup(accept_header)] + if result = Regexp.new('(\w+)\/\*').match(accept_header) + parse_data_with_trailing_star(result[1]) + else + [Mime::Type.lookup(accept_header)] + end else # keep track of creation order to keep the subsequent sort stable list = [] @@ -160,6 +165,16 @@ module Mime list end end + + # input: 'text' + # returend value: [Mime::JSON, Mime::XML, Mime::ICS, Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT] + # + # input: 'application' + # returend value: [Mime::HTML, Mime::JS, Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM + def parse_data_with_trailing_star(input) + keys = Mime::LOOKUP.keys.select{|k| Regexp.new(input).match(k)} + Mime::LOOKUP.select {|k,_| keys.include?(k)}.collect{|i| i[1]}.inject([]){|all,e| all.include?(e) ? all : all << e} + end end def initialize(string, symbol = nil, synonyms = []) -- cgit v1.2.3 From 8154f4b816ea1bb2489fba1829ee99cb75fdf696 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Mon, 22 Nov 2010 13:32:37 -0500 Subject: Compile regex only once MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/mime_type.rb | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 3b5c1d50f2..f2ccf1784b 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -80,6 +80,9 @@ module Mime end class << self + + TRAILING_STAR_REGEXP = /(\w+)\/\*/ + def lookup(string) LOOKUP[string] end @@ -103,11 +106,10 @@ module Mime ([symbol.to_s] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext] = SET.last } end - def parse(accept_header) if accept_header !~ /,/ - if result = Regexp.new('(\w+)\/\*').match(accept_header) - parse_data_with_trailing_star(result[1]) + if accept_header =~ TRAILING_STAR_REGEXP + parse_data_with_trailing_star($1) else [Mime::Type.lookup(accept_header)] end -- cgit v1.2.3 From c5bfc6abe4fd160814f09b02afe68d7f4e25e3d6 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Mon, 22 Nov 2010 13:38:36 -0500 Subject: string include method is 10x faster than creating a new regex object every single time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/mime_type.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index f2ccf1784b..af7b62b863 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -174,7 +174,7 @@ module Mime # input: 'application' # returend value: [Mime::HTML, Mime::JS, Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM def parse_data_with_trailing_star(input) - keys = Mime::LOOKUP.keys.select{|k| Regexp.new(input).match(k)} + keys = Mime::LOOKUP.keys.select{|k| k.include?(input)} Mime::LOOKUP.select {|k,_| keys.include?(k)}.collect{|i| i[1]}.inject([]){|all,e| all.include?(e) ? all : all << e} end end -- cgit v1.2.3 From 794b34306eea0c7e1e99f5741df16129e8e22b3f Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Mon, 22 Nov 2010 13:55:43 -0500 Subject: remove select, collect and then inject with something better MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/mime_type.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index af7b62b863..2250cfa88a 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -175,7 +175,7 @@ module Mime # returend value: [Mime::HTML, Mime::JS, Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM def parse_data_with_trailing_star(input) keys = Mime::LOOKUP.keys.select{|k| k.include?(input)} - Mime::LOOKUP.select {|k,_| keys.include?(k)}.collect{|i| i[1]}.inject([]){|all,e| all.include?(e) ? all : all << e} + Mime::LOOKUP.values_at(*keys).uniq end end -- cgit v1.2.3 From 5c86286dd6f8b58241492004e1fd872e217aca08 Mon Sep 17 00:00:00 2001 From: Sven Fuchs Date: Sun, 21 Nov 2010 13:46:25 +0100 Subject: add respond_to? to ActionDispatch::Integration::Runner since Runner uses method_missing to delegate to the integration session it also should define respond_to? accordingly --- actionpack/lib/action_dispatch/testing/integration.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index fee8cad9f5..e0a17130f8 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -363,6 +363,10 @@ module ActionDispatch integration_session.url_options end + def respond_to?(method, include_private = false) + @integration_session.respond_to?(method, include_private) || super + end + # Delegate unhandled messages to the current session instance. def method_missing(sym, *args, &block) reset! unless integration_session -- cgit v1.2.3 From 2fe43b694f36ddb2062a91eebe61a035147265b1 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Tue, 23 Nov 2010 00:31:03 +0100 Subject: :subdomain, :domain and :tld_length options can now be used in url_for, allowing for easy manipulation of the host during link generation. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/url.rb | 59 ++++++++++++++-------- .../lib/action_dispatch/routing/route_set.rb | 38 +++++++++++--- actionpack/lib/action_dispatch/routing/url_for.rb | 6 +++ 3 files changed, 77 insertions(+), 26 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 9c9eed2c6d..1f7633cbea 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -4,6 +4,27 @@ module ActionDispatch mattr_accessor :tld_length self.tld_length = 1 + def self.extract_domain(host, tld_length = @@tld_length) + return nil unless named_host?(host) + + host.split('.').last(1 + tld_length).join('.') + end + + def self.extract_subdomains(host, tld_length = @@tld_length) + return [] unless named_host?(host) + parts = host.split('.') + parts[0..-(tld_length+2)] + end + + def self.extract_subdomain(host, tld_length = @@tld_length) + extract_subdomains(host, tld_length).join('.') + end + + def self.named_host?(host) + !(host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host)) + end + + # Returns the complete URL used for this request. def url protocol + host_with_port + fullpath @@ -31,15 +52,18 @@ module ActionDispatch # Returns a \host:\port string for this request, such as "example.com" or # "example.com:8080". def host_with_port - "#{host}#{port_string}" + opt_port = optional_port ? ":#{optional_port}" : nil + "#{host}#{opt_port}" end # Returns the port number of this request as an integer. def port - if raw_host_with_port =~ /:(\d+)$/ - $1.to_i - else - standard_port + @port ||= begin + if raw_host_with_port =~ /:(\d+)$/ + $1.to_i + else + standard_port + end end end @@ -56,10 +80,10 @@ module ActionDispatch port == standard_port end - # Returns a \port suffix like ":8080" if the \port number of this request + # Returns a \port suffix like "8080" if the \port number of this request # is not the default HTTP \port 80 or HTTPS \port 443. - def port_string - port == standard_port ? '' : ":#{port}" + def optional_port + standard_port? ? nil : port end def server_port @@ -69,9 +93,7 @@ module ActionDispatch # Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify # a different tld_length, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk". def domain(tld_length = @@tld_length) - return nil unless named_host?(host) - - host.split('.').last(1 + tld_length).join('.') + ActionDispatch::Http::URL.extract_domain(host, tld_length) end # Returns all the \subdomains as an array, so ["dev", "www"] would be @@ -79,20 +101,17 @@ module ActionDispatch # such as 2 to catch ["www"] instead of ["www", "rubyonrails"] # in "www.rubyonrails.co.uk". def subdomains(tld_length = @@tld_length) - return [] unless named_host?(host) - parts = host.split('.') - parts[0..-(tld_length+2)] + ActionDispatch::Http::URL.extract_subdomains(host, tld_length) end + # Returns all the \subdomains as a string, so "dev.www" would be + # returned for "dev.www.rubyonrails.org". You can specify a different tld_length, + # such as 2 to catch ["www"] instead of "www.rubyonrails" + # in "www.rubyonrails.co.uk". def subdomain(tld_length = @@tld_length) - subdomains(tld_length).join('.') + subdomains(tld_length) end - private - - def named_host?(host) - !(host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host)) - end end end end diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 32f41934f1..d823fd710e 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -485,7 +485,8 @@ module ActionDispatch Generator.new(options, recall, self, extras).generate end - RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :port, :trailing_slash, :script_name] + RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length, + :trailing_slash, :script_name, :anchor, :params, :only_path ] def _generate_prefix(options = {}) nil @@ -504,11 +505,8 @@ module ActionDispatch rewritten_url << (options[:protocol] || "http") rewritten_url << "://" unless rewritten_url.match("://") rewritten_url << rewrite_authentication(options) - - raise "Missing host to link to! Please provide :host parameter or set default_url_options[:host]" unless options[:host] - - rewritten_url << options[:host] - rewritten_url << ":#{options.delete(:port)}" if options.key?(:port) + rewritten_url << host_from_options(options) + rewritten_url << ":#{options.delete(:port)}" if options[:port] end script_name = options.delete(:script_name) @@ -562,6 +560,34 @@ module ActionDispatch end private + + def host_from_options(options) + computed_host = subdomain_and_domain(options) || options[:host] + unless computed_host + raise ArgumentError, "Missing host to link to! Please provide :host parameter or set default_url_options[:host]" + end + computed_host + end + + def subdomain_and_domain(options) + tld_length = options[:tld_length] || ActionDispatch::Http::URL.tld_length + + current_domain = ActionDispatch::Http::URL.extract_domain(options[:host], tld_length) + current_subdomain = ActionDispatch::Http::URL.extract_subdomain(options[:host], tld_length) + + domain_parts = if options[:subdomain] && options[:domain] + [options[:subdomain], options[:domain]] + elsif options[:subdomain] + [options[:subdomain], current_domain] + elsif options[:domain] + [current_subdomain, options[:domain]] + else + nil + end + + domain_parts ? domain_parts.join('.') : nil + end + def handle_positional_args(options) return unless args = options.delete(:_positional_args) diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index bfdea41f60..6c3fc5126a 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -115,6 +115,12 @@ module ActionDispatch # * :host - Specifies the host the link should be targeted at. # If :only_path is false, this option must be # provided either explicitly, or via +default_url_options+. + # * :subdomain - Specifies the subdomain of the link, using the +tld_length+ + # to split the domain from the host. + # * :domain - Specifies the domain of the link, using the +tld_length+ + # to split the subdomain from the host. + # * :tld_length - Optionally specify the tld length (only used if :subdomain + # or :domain are supplied). # * :port - Optionally specify the port to connect to. # * :anchor - An anchor name to be appended to the path. # * :trailing_slash - If true, adds a trailing slash, as in "/archive/2009/" -- cgit v1.2.3 From 56b12140246303440da18c0c5ea139b3b17b0282 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 23 Nov 2010 10:05:47 +0100 Subject: Speed up subdomain and domain calculus. --- actionpack/lib/action_dispatch/routing/route_set.rb | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index d823fd710e..ebced9cabe 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -570,22 +570,14 @@ module ActionDispatch end def subdomain_and_domain(options) + return nil unless options[:subdomain] || options[:domain] tld_length = options[:tld_length] || ActionDispatch::Http::URL.tld_length - current_domain = ActionDispatch::Http::URL.extract_domain(options[:host], tld_length) - current_subdomain = ActionDispatch::Http::URL.extract_subdomain(options[:host], tld_length) - - domain_parts = if options[:subdomain] && options[:domain] - [options[:subdomain], options[:domain]] - elsif options[:subdomain] - [options[:subdomain], current_domain] - elsif options[:domain] - [current_subdomain, options[:domain]] - else - nil - end - - domain_parts ? domain_parts.join('.') : nil + host = "" + host << (options[:subdomain] || ActionDispatch::Http::URL.extract_subdomain(options[:host], tld_length)) + host << "." + host << (options[:domain] || ActionDispatch::Http::URL.extract_domain(options[:host], tld_length)) + host end def handle_positional_args(options) -- cgit v1.2.3 From da583df50c32d50261b682664fe43fd5e2f58f87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Tue, 23 Nov 2010 10:09:24 +0100 Subject: Remove bazillion warnings from AP suite. --- actionpack/lib/action_dispatch/testing/integration.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index e0a17130f8..8fe74c3c80 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -364,7 +364,7 @@ module ActionDispatch end def respond_to?(method, include_private = false) - @integration_session.respond_to?(method, include_private) || super + integration_session.respond_to?(method, include_private) || super end # Delegate unhandled messages to the current session instance. -- cgit v1.2.3 From 0250c3eca40f5f2b3da698b11ff4f01f58db5a69 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Tue, 23 Nov 2010 22:51:51 +0100 Subject: copy-edits RDoc of 2fe43b6 --- actionpack/lib/action_dispatch/routing/url_for.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index 6c3fc5126a..d4db78a25a 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -119,8 +119,9 @@ module ActionDispatch # to split the domain from the host. # * :domain - Specifies the domain of the link, using the +tld_length+ # to split the subdomain from the host. - # * :tld_length - Optionally specify the tld length (only used if :subdomain - # or :domain are supplied). + # * :tld_length - Number of labels the TLD id composed of, only used if + # :subdomain or :domain are supplied. Defaults to + # ActionDispatch::Http::URL.tld_length, which in turn defaults to 1. # * :port - Optionally specify the port to connect to. # * :anchor - An anchor name to be appended to the path. # * :trailing_slash - If true, adds a trailing slash, as in "/archive/2009/" -- cgit v1.2.3 From 769575300acb778ce812208073952109bc45a9fd Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 24 Nov 2010 09:19:27 +1100 Subject: Fix formatting issue with rake routes output for the namespace method --- actionpack/lib/action_dispatch/routing/mapper.rb | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 879ccc5791..432a574419 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -588,13 +588,13 @@ module ActionDispatch # # This generates the following routes: # - # admin_posts GET /admin/posts(.:format) {:action=>"index", :controller=>"admin/posts"} - # admin_posts POST /admin/posts(.:format) {:action=>"create", :controller=>"admin/posts"} - # new_admin_post GET /admin/posts/new(.:format) {:action=>"new", :controller=>"admin/posts"} - # edit_admin_post GET /admin/posts/:id/edit(.:format) {:action=>"edit", :controller=>"admin/posts"} - # 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"} + # admin_posts GET /admin/posts(.:format) {:action=>"index", :controller=>"admin/posts"} + # admin_posts POST /admin/posts(.:format) {:action=>"create", :controller=>"admin/posts"} + # new_admin_post GET /admin/posts/new(.:format) {:action=>"new", :controller=>"admin/posts"} + # edit_admin_post GET /admin/posts/:id/edit(.:format) {:action=>"edit", :controller=>"admin/posts"} + # 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+ all default to the name of the namespace. -- cgit v1.2.3 From 04af510b5678ea7bd4cd170257e7e3ef4423f834 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 24 Nov 2010 09:21:25 +1100 Subject: Paths in ActionDispatch::Scoping documentation should be for /admin/posts, not /admin/photos --- actionpack/lib/action_dispatch/routing/mapper.rb | 28 ++++++++++++------------ 1 file changed, 14 insertions(+), 14 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 432a574419..37d14944d6 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -439,13 +439,13 @@ module ActionDispatch # This will create a number of routes for each of the posts and comments # controller. For Admin::PostsController, Rails will create: # - # GET /admin/photos - # GET /admin/photos/new - # POST /admin/photos - # GET /admin/photos/1 - # GET /admin/photos/1/edit - # PUT /admin/photos/1 - # DELETE /admin/photos/1 + # GET /admin/posts + # GET /admin/posts/new + # POST /admin/posts + # GET /admin/posts/1 + # GET /admin/posts/1/edit + # PUT /admin/posts/1 + # DELETE /admin/posts/1 # # If you want to route /posts (without the prefix /admin) to # Admin::PostsController, you could use @@ -473,13 +473,13 @@ module ActionDispatch # not use scope. In the last case, the following paths map to # PostsController: # - # GET /admin/photos - # GET /admin/photos/new - # POST /admin/photos - # GET /admin/photos/1 - # GET /admin/photos/1/edit - # PUT /admin/photos/1 - # DELETE /admin/photos/1 + # GET /admin/posts + # GET /admin/posts/new + # POST /admin/posts + # GET /admin/posts/1 + # GET /admin/posts/1/edit + # PUT /admin/posts/1 + # DELETE /admin/posts/1 module Scoping def initialize(*args) #:nodoc: @scope = {} -- cgit v1.2.3 From 2974f57aaedd22f44b387ec72ca9f42a2982bb02 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 24 Nov 2010 09:25:01 +1100 Subject: Remove non-sensical first couple of lines for scope method documentation --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 -- 1 file changed, 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 37d14944d6..8b1578769d 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -486,8 +486,6 @@ module ActionDispatch super end - # Used to route /photos (without the prefix /admin) - # to Admin::PostsController: # === Supported options # [:module] # If you want to route /posts (without the prefix /admin) to -- cgit v1.2.3 From 01af50d8b6be7b167c30f29c7407ce88bdfc9b2a Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 24 Nov 2010 09:27:12 +1100 Subject: Add :module option documentation for the resources method --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 8b1578769d..1f3a831b7f 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -967,6 +967,7 @@ module ActionDispatch # GET /photos/:id/edit # PUT /photos/:id # DELETE /photos/:id + # # === Supported options # [:path_names] # Allows you to change the paths of the seven default actions. @@ -975,6 +976,13 @@ module ActionDispatch # resources :posts, :path_names => { :new => "brand_new" } # # 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. + # + # resources :posts, :module => "admin" + # + # All requests to the posts resources will now go to +Admin::PostsController+. def resources(*resources, &block) options = resources.extract_options! -- cgit v1.2.3 From fd47a4bf438e37a20756e0341cd7cd4e472fd3cb Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 24 Nov 2010 09:28:21 +1100 Subject: Document the :path option for resources :posts --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 1f3a831b7f..f4d31eeff1 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -983,6 +983,14 @@ module ActionDispatch # resources :posts, :module => "admin" # # All requests to the posts resources will now go to +Admin::PostsController+. + # + # [:path] + # + # Set a path prefix for this resource. + # + # resources :posts, :path => "admin" + # + # All actions for this resource will now be at +/admin/posts+. def resources(*resources, &block) options = resources.extract_options! -- cgit v1.2.3 From e4a9af186a7316e2de018ff9306442b9fe0f2400 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 24 Nov 2010 09:31:29 +1100 Subject: Add mention of nested resource to resources documentation --- actionpack/lib/action_dispatch/routing/mapper.rb | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f4d31eeff1..fb1f0d3f0c 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -968,6 +968,21 @@ module ActionDispatch # PUT /photos/:id # DELETE /photos/:id # + # Resources can also be nested infinitely by using this block syntax: + # + # resources :photos do + # resources :comments + # end + # + # This generates the following comments routes: + # + # GET /photos/:id/comments/new + # POST /photos/:id/comments + # GET /photos/:id/comments/:id + # GET /photos/:id/comments/:id/edit + # PUT /photos/:id/comments/:id + # DELETE /photos/:id/comments/:id + # # === Supported options # [:path_names] # Allows you to change the paths of the seven default actions. -- cgit v1.2.3 From e39138478b38d7a5e0a13756b1bdfa8b43226846 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Wed, 24 Nov 2010 10:10:38 +0100 Subject: port_string bought back to life as it is part of the public api MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/http/url.rb | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 1f7633cbea..1e7054f381 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -52,8 +52,7 @@ module ActionDispatch # Returns a \host:\port string for this request, such as "example.com" or # "example.com:8080". def host_with_port - opt_port = optional_port ? ":#{optional_port}" : nil - "#{host}#{opt_port}" + "#{host}#{port_string}" end # Returns the port number of this request as an integer. @@ -80,12 +79,18 @@ module ActionDispatch port == standard_port end - # Returns a \port suffix like "8080" if the \port number of this request + # Returns a number \port suffix like 8080 if the \port number of this request # is not the default HTTP \port 80 or HTTPS \port 443. def optional_port standard_port? ? nil : port end + # Returns a string \port suffix, including colon, like ":8080" if the \port + # number of this request is not the default HTTP \port 80 or HTTPS \port 443. + def port_string + standard_port? ? '' : ":#{port}" + end + def server_port @env['SERVER_PORT'].to_i end -- cgit v1.2.3 From e8708836252852d8bae87c80472b865812fa9776 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Tue, 23 Nov 2010 23:28:57 +0800 Subject: unregister method implementation and test --- actionpack/lib/action_dispatch/http/mime_type.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 2250cfa88a..2b8395fc09 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -177,6 +177,18 @@ module Mime keys = Mime::LOOKUP.keys.select{|k| k.include?(input)} Mime::LOOKUP.values_at(*keys).uniq end + + # This method is opposite of register method. + # + # Usage: + # + # Mime::Type.unregister("text/x-mobile", :mobile) + def unregister(string, symbol) + EXTENSION_LOOKUP.delete(symbol.to_s) + LOOKUP.delete(string) + symbol = symbol.to_s.upcase.intern + Mime.module_eval { remove_const(symbol) if const_defined?(symbol) } + end end def initialize(string, symbol = nil, synonyms = []) -- cgit v1.2.3 From 5c9abb6cca4b6de7146c94779a34ae943e4ea4d8 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Thu, 25 Nov 2010 01:19:43 +0800 Subject: processing image/* is an odditity because there is a test case which expects image/* to not to be expanded. So I am leaving image/* as it is and process only text/* and application/* --- actionpack/lib/action_dispatch/http/mime_type.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 2b8395fc09..5ea49a23c7 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -81,7 +81,7 @@ module Mime class << self - TRAILING_STAR_REGEXP = /(\w+)\/\*/ + TRAILING_STAR_REGEXP = /(text|application)\/\*/ def lookup(string) LOOKUP[string] -- cgit v1.2.3 From 18adbe9347727dc3eefe46395d52aafa347a0c73 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Thu, 25 Nov 2010 01:24:45 +0800 Subject: process text/* if it appears in the middle of HTTP_ACCEPT parameter --- actionpack/lib/action_dispatch/http/mime_type.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 5ea49a23c7..08eab5634a 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -120,7 +120,11 @@ module Mime params, q = header.split(/;\s*q=/) if params params.strip! - list << AcceptItem.new(index, params, q) unless params.empty? + if params =~ TRAILING_STAR_REGEXP + parse_data_with_trailing_star($1).each { |m| list << AcceptItem.new(index, m.to_s, q) } + else + list << AcceptItem.new(index, params, q) unless params.empty? + end end end list.sort! -- cgit v1.2.3 From 90b0f6149160e6fedb12ea54f713ec3399bebec8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 25 Nov 2010 10:44:42 +0100 Subject: #:nodoc: internal methods. --- actionpack/lib/action_dispatch/routing/mapper.rb | 62 ++++++++++++------------ 1 file changed, 31 insertions(+), 31 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 879ccc5791..0b5437bd4f 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -707,61 +707,61 @@ module ActionDispatch end private - def scope_options + def scope_options #:nodoc: @scope_options ||= private_methods.grep(/^merge_(.+)_scope$/) { $1.to_sym } end - def merge_path_scope(parent, child) + def merge_path_scope(parent, child) #:nodoc: Mapper.normalize_path("#{parent}/#{child}") end - def merge_shallow_path_scope(parent, child) + def merge_shallow_path_scope(parent, child) #:nodoc: Mapper.normalize_path("#{parent}/#{child}") end - def merge_as_scope(parent, child) + def merge_as_scope(parent, child) #:nodoc: parent ? "#{parent}_#{child}" : child end - def merge_shallow_prefix_scope(parent, child) + def merge_shallow_prefix_scope(parent, child) #:nodoc: parent ? "#{parent}_#{child}" : child end - def merge_module_scope(parent, child) + def merge_module_scope(parent, child) #:nodoc: parent ? "#{parent}/#{child}" : child end - def merge_controller_scope(parent, child) + def merge_controller_scope(parent, child) #:nodoc: child end - def merge_path_names_scope(parent, child) + def merge_path_names_scope(parent, child) #:nodoc: merge_options_scope(parent, child) end - def merge_constraints_scope(parent, child) + def merge_constraints_scope(parent, child) #:nodoc: merge_options_scope(parent, child) end - def merge_defaults_scope(parent, child) + def merge_defaults_scope(parent, child) #:nodoc: merge_options_scope(parent, child) end - def merge_blocks_scope(parent, child) + def merge_blocks_scope(parent, child) #:nodoc: merged = parent ? parent.dup : [] merged << child if child merged end - def merge_options_scope(parent, child) + def merge_options_scope(parent, child) #:nodoc: (parent || {}).except(*override_keys(child)).merge(child) end - def merge_shallow_scope(parent, child) + def merge_shallow_scope(parent, child) #:nodoc: child ? true : false end - def override_keys(child) + def override_keys(child) #:nodoc: child.key?(:only) || child.key?(:except) ? [:only, :except] : [] end end @@ -1167,7 +1167,7 @@ module ActionDispatch @scope[:scope_level_resource] end - def apply_common_behavior_for(method, resources, options, &block) + def apply_common_behavior_for(method, resources, options, &block) #:nodoc: if resources.length > 1 resources.each { |r| send(method, r, options, &block) } return true @@ -1197,23 +1197,23 @@ module ActionDispatch false end - def action_options?(options) + def action_options?(options) #:nodoc: options[:only] || options[:except] end - def scope_action_options? + def scope_action_options? #:nodoc: @scope[:options].is_a?(Hash) && (@scope[:options][:only] || @scope[:options][:except]) end - def scope_action_options + def scope_action_options #:nodoc: @scope[:options].slice(:only, :except) end - def resource_scope? + def resource_scope? #:nodoc: [:resource, :resources].include?(@scope[:scope_level]) end - def resource_method_scope? + def resource_method_scope? #:nodoc: [:collection, :member, :new].include?(@scope[:scope_level]) end @@ -1239,7 +1239,7 @@ module ActionDispatch @scope[:scope_level_resource] = old_resource end - def resource_scope(resource) + def resource_scope(resource) #:nodoc: with_scope_level(resource.is_a?(SingletonResource) ? :resource : :resources, resource) do scope(parent_resource.resource_scope) do yield @@ -1247,30 +1247,30 @@ module ActionDispatch end end - def nested_options + def nested_options #:nodoc: {}.tap do |options| options[:as] = parent_resource.member_name options[:constraints] = { "#{parent_resource.singular}_id".to_sym => id_constraint } if id_constraint? end end - def id_constraint? + def id_constraint? #:nodoc: @scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp) end - def id_constraint + def id_constraint #:nodoc: @scope[:constraints][:id] end - def canonical_action?(action, flag) + def canonical_action?(action, flag) #:nodoc: flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s) end - def shallow_scoping? + def shallow_scoping? #:nodoc: shallow? && @scope[:scope_level] == :member end - def path_for_action(action, path) + def path_for_action(action, path) #:nodoc: prefix = shallow_scoping? ? "#{@scope[:shallow_path]}/#{parent_resource.path}/:id" : @scope[:path] @@ -1281,11 +1281,11 @@ module ActionDispatch end end - def action_path(name, path = nil) + def action_path(name, path = nil) #:nodoc: path || @scope[:path_names][name.to_sym] || name.to_s end - def prefix_name_for_action(as, action) + def prefix_name_for_action(as, action) #:nodoc: if as as.to_s elsif !canonical_action?(action, @scope[:scope_level]) @@ -1293,7 +1293,7 @@ module ActionDispatch end end - def name_for_action(as, action) + def name_for_action(as, action) #:nodoc: prefix = prefix_name_for_action(as, action) prefix = Mapper.normalize_name(prefix) if prefix name_prefix = @scope[:as] @@ -1323,7 +1323,7 @@ module ActionDispatch end end - module Shorthand + module Shorthand #:nodoc: def match(*args) if args.size == 1 && args.last.is_a?(Hash) options = args.pop -- cgit v1.2.3 From 731ca00b484379661786fac36c17db7e085603c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 25 Nov 2010 11:49:51 +0100 Subject: Dynamically generaeted helpers on collection should not clobber resources url helper [#6028 state:resolved] --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 0b5437bd4f..880862c909 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1299,6 +1299,8 @@ module ActionDispatch name_prefix = @scope[:as] if parent_resource + return nil if as.nil? && action.nil? + collection_name = parent_resource.collection_name member_name = parent_resource.member_name end -- cgit v1.2.3 From 5b9f6a74db1a58c5557087cd924fd67dd9cf43e0 Mon Sep 17 00:00:00 2001 From: Aditya Sanghi Date: Fri, 26 Nov 2010 16:41:33 +0530 Subject: Resolving LH #5986, cookies doc updates --- actionpack/lib/action_dispatch/middleware/cookies.rb | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index c4c2e1acd7..b0a4e3d949 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -16,17 +16,23 @@ module ActionDispatch # Examples for writing: # # # Sets a simple session cookie. + # # This cookie will be deleted when the user's browser is closed. # cookies[:user_name] = "david" # + # # Assign an array of values to a cookie. + # cookies[:lat_lon] = [47.68, -122.37] + # # # Sets a cookie that expires in 1 hour. # cookies[:login] = { :value => "XJ-122", :expires => 1.hour.from_now } # # # Sets a signed cookie, which prevents a user from tampering with its value. - # # You must specify a value in ActionController::Base.cookie_verifier_secret. - # cookies.signed[:remember_me] = [current_user.id, current_user.salt] + # # The cookie is signed by your app's config.secret_token value. + # # Rails generates this value by default when you create a new Rails app. + # cookies.signed[:user_id] = current_user.id # # # Sets a "permanent" cookie (which expires in 20 years from now). # cookies.permanent[:login] = "XJ-122" + # # # You can also chain these methods: # cookies.permanent.signed[:login] = "XJ-122" # @@ -34,6 +40,7 @@ module ActionDispatch # # cookies[:user_name] # => "david" # cookies.size # => 2 + # cookies[:lat_lon] # => [47.68, -122.37] # # Example for deleting: # @@ -275,7 +282,7 @@ module ActionDispatch "integrity hash for cookie session data. Use " + "config.secret_token = \"some secret phrase of at " + "least #{SECRET_MIN_LENGTH} characters\"" + - "in config/application.rb" + "in config/initializers/secret_token.rb" end if secret.length < SECRET_MIN_LENGTH -- cgit v1.2.3 From a4c360e8c7b7c2635de3c1172dafff7b7975ecc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 28 Nov 2010 11:48:39 +0100 Subject: trailing star mimes should respect the order in which mime types are defined. --- actionpack/lib/action_dispatch/http/mime_type.rb | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 08eab5634a..3e3478a44e 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -115,15 +115,20 @@ module Mime end else # keep track of creation order to keep the subsequent sort stable - list = [] - accept_header.split(/,/).each_with_index do |header, index| + list, index = [], 0 + accept_header.split(/,/).each do |header| params, q = header.split(/;\s*q=/) - if params + if params.present? params.strip! + if params =~ TRAILING_STAR_REGEXP - parse_data_with_trailing_star($1).each { |m| list << AcceptItem.new(index, m.to_s, q) } + parse_data_with_trailing_star($1).each do |m| + list << AcceptItem.new(index, m.to_s, q) + index += 1 + end else - list << AcceptItem.new(index, params, q) unless params.empty? + list << AcceptItem.new(index, params, q) + index += 1 end end end @@ -178,8 +183,7 @@ module Mime # input: 'application' # returend value: [Mime::HTML, Mime::JS, Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM def parse_data_with_trailing_star(input) - keys = Mime::LOOKUP.keys.select{|k| k.include?(input)} - Mime::LOOKUP.values_at(*keys).uniq + Mime::SET.select { |m| m =~ input } end # This method is opposite of register method. -- cgit v1.2.3 From 31906eecdf7bffc2203379c5d40f1bb77fb35858 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 28 Nov 2010 12:48:50 +0100 Subject: Fix tests on 1.9.2. --- actionpack/lib/action_dispatch/http/mime_type.rb | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 3e3478a44e..c1503c7eeb 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -190,12 +190,15 @@ module Mime # # Usage: # - # Mime::Type.unregister("text/x-mobile", :mobile) - def unregister(string, symbol) - EXTENSION_LOOKUP.delete(symbol.to_s) - LOOKUP.delete(string) - symbol = symbol.to_s.upcase.intern - Mime.module_eval { remove_const(symbol) if const_defined?(symbol) } + # Mime::Type.unregister(:mobile) + def unregister(symbol) + symbol = symbol.to_s.upcase + mime = Mime.const_get(symbol) + Mime.instance_eval { remove_const(symbol) } + + SET.delete_if { |v| v.eql?(mime) } + LOOKUP.delete_if { |k,v| v.eql?(mime) } + EXTENSION_LOOKUP.delete_if { |k,v| v.eql?(mime) } end end -- cgit v1.2.3 From 0bda6f1ec664fcfd1b312492a6419e3d76d5baa7 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Tue, 30 Nov 2010 16:36:01 +0100 Subject: The redirect routing method now allows for a hash of options which only changes the relevant parts of the url, or an object which responds to call can be supplied so common redirect rules can be easily reused. This commit includes a change where url generation from parts has been moved to AD::Http::URL as a class method. --- actionpack/lib/action_dispatch/http/url.rb | 52 ++++++++++++++ actionpack/lib/action_dispatch/routing/mapper.rb | 39 ++--------- .../lib/action_dispatch/routing/redirection.rb | 81 ++++++++++++++++++++++ .../lib/action_dispatch/routing/route_set.rb | 62 +++++------------ 4 files changed, 155 insertions(+), 79 deletions(-) create mode 100644 actionpack/lib/action_dispatch/routing/redirection.rb (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 1e7054f381..51d4766282 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -24,6 +24,58 @@ module ActionDispatch !(host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host)) end + def self.url_for(options = {}) + unless options[:host].present? || options[:only_path].present? + raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true' + end + + rewritten_url = "" + + unless options[:only_path] + rewritten_url << (options[:protocol] || "http") + 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] + end + + path = options.delete(:path) || '' + + params = options[:params] || {} + params.reject! {|k,v| !v } + + rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) + rewritten_url << "?#{params.to_query}" unless params.empty? + rewritten_url << "##{Rack::Mount::Utils.escape_uri(options[:anchor].to_param.to_s)}" if options[:anchor] + rewritten_url + end + + class << self + private + + def rewrite_authentication(options) + if options[:user] && options[:password] + "#{Rack::Utils.escape(options[:user])}:#{Rack::Utils.escape(options[:password])}@" + else + "" + end + end + + def host_or_subdomain_and_domain(options) + return options[:host] unless options[:subdomain] || options[:domain] + + tld_length = options[:tld_length] || @@tld_length + + host = "" + host << (options[:subdomain] || extract_subdomain(options[:host], tld_length)) + host << "." + host << (options[:domain] || extract_domain(options[:host], tld_length)) + host + end + + end + + # Returns the complete URL used for this request. def url diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 880862c909..05b7147c70 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -2,6 +2,7 @@ require 'erb' require 'active_support/core_ext/hash/except' require 'active_support/core_ext/object/blank' require 'active_support/inflector' +require 'action_dispatch/routing/redirection' module ActionDispatch module Routing @@ -383,39 +384,6 @@ module ActionDispatch map_method(:delete, *args, &block) end - # Redirect any path to another path: - # - # match "/stories" => redirect("/posts") - def redirect(*args) - options = args.last.is_a?(Hash) ? args.pop : {} - - path = args.shift || Proc.new - path_proc = path.is_a?(Proc) ? path : proc { |params| (params.empty? || !path.match(/%\{\w*\}/)) ? path : (path % params) } - status = options[:status] || 301 - - lambda do |env| - req = Request.new(env) - - params = [req.symbolized_path_parameters] - params << req if path_proc.arity > 1 - - uri = URI.parse(path_proc.call(*params)) - uri.scheme ||= req.scheme - uri.host ||= req.host - uri.port ||= req.port unless req.standard_port? - - body = %(You are being redirected.) - - headers = { - 'Location' => uri.to_s, - 'Content-Type' => 'text/html', - 'Content-Length' => body.length.to_s - } - - [ status, headers, [body] ] - end - end - private def map_method(method, *args, &block) options = args.extract_options! @@ -638,7 +606,7 @@ module ActionDispatch :shallow_path => path, :shallow_prefix => path }.merge!(options) scope(options) { yield } end - + # === Parameter Restriction # Allows you to constrain the nested routes based on a set of rules. # For instance, in order to change the routes to allow for a dot character in the +id+ parameter: @@ -649,7 +617,7 @@ module ActionDispatch # # Now routes such as +/posts/1+ will no longer be valid, but +/posts/1.1+ will be. # The +id+ parameter must match the constraint passed in for this example. - # + # # You may use this to also resrict other parameters: # # resources :posts do @@ -1340,6 +1308,7 @@ module ActionDispatch include Base include HttpHelpers + include Redirection include Scoping include Resources include Shorthand diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb new file mode 100644 index 0000000000..d9c9a400a7 --- /dev/null +++ b/actionpack/lib/action_dispatch/routing/redirection.rb @@ -0,0 +1,81 @@ +require 'action_dispatch/http/request' + +module ActionDispatch + module Routing + module Redirection + + # Redirect any path to another path: + # + # match "/stories" => redirect("/posts") + def redirect(*args, &block) + options = args.last.is_a?(Hash) ? args.pop : {} + status = options.delete(:status) || 301 + + path = args.shift + + path_proc = if path.is_a?(String) + proc { |params| (params.empty? || !path.match(/%\{\w*\}/)) ? path : (path % params) } + elsif options.any? + options_proc(options) + elsif path.respond_to?(:call) + proc { |params, request| path.call(params, request) } + elsif block + block + else + raise ArgumentError, "redirection argument not supported" + end + + redirection_proc(status, path_proc) + end + + private + + def options_proc(options) + proc do |params, request| + path = if options[:path].nil? + request.path + elsif params.empty? || !options[:path].match(/%\{\w*\}/) + options.delete(:path) + else + (options.delete(:path) % params) + end + + default_options = { + :protocol => request.protocol, + :host => request.host, + :port => request.optional_port, + :path => path, + :params => request.query_parameters + } + + ActionDispatch::Http::URL.url_for(options.reverse_merge(default_options)) + end + end + + def redirection_proc(status, path_proc) + lambda do |env| + req = Request.new(env) + + params = [req.symbolized_path_parameters] + params << req if path_proc.arity > 1 + + uri = URI.parse(path_proc.call(*params)) + uri.scheme ||= req.scheme + uri.host ||= req.host + uri.port ||= req.port unless req.standard_port? + + body = %(You are being redirected.) + + headers = { + 'Location' => uri.to_s, + 'Content-Type' => 'text/html', + 'Content-Length' => body.length.to_s + } + + [ status, headers, [body] ] + end + end + + end + end +end \ No newline at end of file diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index ebced9cabe..03bfe178e5 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -442,12 +442,9 @@ module ActionDispatch raise_routing_error unless path - params.reject! {|k,v| !v } - return [path, params.keys] if @extras - path << "?#{params.to_query}" unless params.empty? - path + [path, params] rescue Rack::Mount::RoutingError raise_routing_error end @@ -486,7 +483,7 @@ module ActionDispatch end RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length, - :trailing_slash, :script_name, :anchor, :params, :only_path ] + :trailing_slash, :anchor, :params, :only_path, :script_name] def _generate_prefix(options = {}) nil @@ -498,29 +495,24 @@ module ActionDispatch handle_positional_args(options) - rewritten_url = "" - - path_segments = options.delete(:_path_segments) - unless options[:only_path] - rewritten_url << (options[:protocol] || "http") - rewritten_url << "://" unless rewritten_url.match("://") - rewritten_url << rewrite_authentication(options) - rewritten_url << host_from_options(options) - rewritten_url << ":#{options.delete(:port)}" if options[:port] - end + user, password = extract_authentication(options) + path_segments = options.delete(:_path_segments) + script_name = options.delete(:script_name) - script_name = options.delete(:script_name) path = (script_name.blank? ? _generate_prefix(options) : script_name.chomp('/')).to_s path_options = options.except(*RESERVED_OPTIONS) path_options = yield(path_options) if block_given? - path << generate(path_options, path_segments || {}) - # ROUTES TODO: This can be called directly, so script_name should probably be set in the routes - rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) - rewritten_url << "##{Rack::Mount::Utils.escape_uri(options[:anchor].to_param.to_s)}" if options[:anchor] + path_addition, params = generate(path_options, path_segments || {}) + path << path_addition - rewritten_url + ActionDispatch::Http::URL.url_for(options.merge({ + :path => path, + :params => params, + :user => user, + :password => password + })) end def call(env) @@ -561,23 +553,12 @@ module ActionDispatch private - def host_from_options(options) - computed_host = subdomain_and_domain(options) || options[:host] - unless computed_host - raise ArgumentError, "Missing host to link to! Please provide :host parameter or set default_url_options[:host]" + def extract_authentication(options) + if options[:user] && options[:password] + [options.delete(:user), options.delete(:password)] + else + nil end - computed_host - end - - def subdomain_and_domain(options) - return nil unless options[:subdomain] || options[:domain] - tld_length = options[:tld_length] || ActionDispatch::Http::URL.tld_length - - host = "" - host << (options[:subdomain] || ActionDispatch::Http::URL.extract_subdomain(options[:host], tld_length)) - host << "." - host << (options[:domain] || ActionDispatch::Http::URL.extract_domain(options[:host], tld_length)) - host end def handle_positional_args(options) @@ -590,13 +571,6 @@ module ActionDispatch options.merge!(Hash[args.zip(keys).map { |v, k| [k, v] }]) end - def rewrite_authentication(options) - if options[:user] && options[:password] - "#{Rack::Utils.escape(options.delete(:user))}:#{Rack::Utils.escape(options.delete(:password))}@" - else - "" - end - end end end end -- cgit v1.2.3 From 1e26bda0959c313ce5c1816bf4958b542050e5e2 Mon Sep 17 00:00:00 2001 From: Josh Kalderimis Date: Tue, 30 Nov 2010 17:55:33 +0100 Subject: Added documentation explaining the new additional supported syntaxes for the routing redirect method, a small changelog note, and two extra tests for path interpolation when using the hash option syntax. --- .../lib/action_dispatch/routing/redirection.rb | 29 ++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb index d9c9a400a7..804991ad5f 100644 --- a/actionpack/lib/action_dispatch/routing/redirection.rb +++ b/actionpack/lib/action_dispatch/routing/redirection.rb @@ -7,6 +7,35 @@ module ActionDispatch # Redirect any path to another path: # # match "/stories" => redirect("/posts") + # + # You can also use interpolation in the supplied redirect argument: + # + # match 'docs/:article', :to => redirect('/wiki/%{article}') + # + # Alternatively you can use one of the other syntaxes: + # + # The block version of redirect allows for the easy encapsulation of any logic associated with + # the redirect in question. Either the params and request are supplied as arguments, or just + # params, depending of how many arguments your block accepts. A string is required as a + # return value. + # + # match 'jokes/:number', :to => redirect do |params, request| + # path = (params[:number].to_i.even? ? "/wheres-the-beef" : "/i-love-lamp") + # "http://#{request.host_with_port}/#{path}" + # end + # + # The options version of redirect allows you to supply only the parts of the url which need + # to change, it also supports interpolation of the path similar to the first example. + # + # match 'stores/:name', :to => redirect(:subdomain => 'stores', :path => '/%{name}') + # match 'stores/:name(*all)', :to => redirect(:subdomain => 'stores', :path => '/%{name}%{all}') + # + # Finally, an object which responds to call can be supplied to redirect, allowing you to reuse + # common redirect routes. The call method must accept two arguments, params and request, and return + # a string. + # + # match 'accounts/:name' => redirect(SubdomainRedirector.new('api')) + # def redirect(*args, &block) options = args.last.is_a?(Hash) ? args.pop : {} status = options.delete(:status) || 301 -- cgit v1.2.3 From 831a2342c69f1d602aca9e894bffa4f6dbf614ed Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 30 Nov 2010 20:04:31 -0800 Subject: just use alias --- actionpack/lib/action_dispatch/testing/integration.rb | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 8fe74c3c80..5c6416a19e 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -235,9 +235,7 @@ module ActionDispatch # Set the host name to use in the next request. # # session.host! "www.example.com" - def host!(name) - @host = name - end + alias :host! :host= private def _mock_session -- cgit v1.2.3 From 226ea0e9e817a2e449d989d925c36cf6a4cfd67b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Fri, 3 Dec 2010 13:27:43 +0100 Subject: Wrap everything in class << self. --- actionpack/lib/action_dispatch/http/url.rb | 79 ++++++++++++++---------------- 1 file changed, 37 insertions(+), 42 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 51d4766282..796cd8c09b 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -4,55 +4,54 @@ module ActionDispatch mattr_accessor :tld_length self.tld_length = 1 - def self.extract_domain(host, tld_length = @@tld_length) - return nil unless named_host?(host) - - host.split('.').last(1 + tld_length).join('.') - end - - def self.extract_subdomains(host, tld_length = @@tld_length) - return [] unless named_host?(host) - parts = host.split('.') - parts[0..-(tld_length+2)] - end - - def self.extract_subdomain(host, tld_length = @@tld_length) - extract_subdomains(host, tld_length).join('.') - end + class << self + def extract_domain(host, tld_length = @@tld_length) + return nil unless named_host?(host) + host.split('.').last(1 + tld_length).join('.') + end - def self.named_host?(host) - !(host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host)) - end + def extract_subdomains(host, tld_length = @@tld_length) + return [] unless named_host?(host) + parts = host.split('.') + parts[0..-(tld_length+2)] + end - def self.url_for(options = {}) - unless options[:host].present? || options[:only_path].present? - raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true' + def extract_subdomain(host, tld_length = @@tld_length) + extract_subdomains(host, tld_length).join('.') end - rewritten_url = "" + def url_for(options = {}) + unless options[:host].present? || options[:only_path].present? + raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true' + end - unless options[:only_path] - rewritten_url << (options[:protocol] || "http") - 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] - end + rewritten_url = "" - path = options.delete(:path) || '' + unless options[:only_path] + rewritten_url << (options[:protocol] || "http") + 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] + end - params = options[:params] || {} - params.reject! {|k,v| !v } + path = options.delete(:path) || '' - rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) - rewritten_url << "?#{params.to_query}" unless params.empty? - rewritten_url << "##{Rack::Mount::Utils.escape_uri(options[:anchor].to_param.to_s)}" if options[:anchor] - rewritten_url - end + params = options[:params] || {} + params.reject! {|k,v| !v } + + rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) + rewritten_url << "?#{params.to_query}" unless params.empty? + rewritten_url << "##{Rack::Mount::Utils.escape_uri(options[:anchor].to_param.to_s)}" if options[:anchor] + rewritten_url + end - class << self private + def named_host?(host) + !(host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host)) + end + def rewrite_authentication(options) if options[:user] && options[:password] "#{Rack::Utils.escape(options[:user])}:#{Rack::Utils.escape(options[:password])}@" @@ -72,11 +71,8 @@ module ActionDispatch host << (options[:domain] || extract_domain(options[:host], tld_length)) host end - end - - # Returns the complete URL used for this request. def url protocol + host_with_port + fullpath @@ -168,7 +164,6 @@ module ActionDispatch def subdomain(tld_length = @@tld_length) subdomains(tld_length) end - end end end -- cgit v1.2.3 From e1d0d5ae81d2b02eebb1afbfb79edf0a2da2d48e Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Sat, 4 Dec 2010 22:40:05 -0200 Subject: Fix mime type doc typos --- actionpack/lib/action_dispatch/http/mime_type.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 08eab5634a..c85aa64572 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -173,10 +173,10 @@ module Mime end # input: 'text' - # returend value: [Mime::JSON, Mime::XML, Mime::ICS, Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT] + # returned value: [Mime::JSON, Mime::XML, Mime::ICS, Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT] # # input: 'application' - # returend value: [Mime::HTML, Mime::JS, Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM + # returned value: [Mime::HTML, Mime::JS, Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM] def parse_data_with_trailing_star(input) keys = Mime::LOOKUP.keys.select{|k| k.include?(input)} Mime::LOOKUP.values_at(*keys).uniq -- cgit v1.2.3 From a47f31c59399204947dacb2b54fccc6987b137ee Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 9 Dec 2010 20:01:42 +1000 Subject: mapper.rb: add "options" to make the default-to-namespace-name line read better --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 5a38158e9f..11ac8fed20 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -563,7 +563,7 @@ module ActionDispatch # admin_post DELETE /admin/posts/:id(.:format) {:action=>"destroy", :controller=>"admin/posts"} # === Supported options # - # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ all default to the name of the namespace. + # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ options all default to the name of the namespace. # # [:path] # The path prefix for the routes. -- cgit v1.2.3 From d2f98e5b556815f7b9cf84d3702d93a0bfb7d433 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 9 Dec 2010 20:03:14 +1000 Subject: indent code samples for mount doc --- actionpack/lib/action_dispatch/routing/mapper.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 11ac8fed20..086366c740 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -269,18 +269,18 @@ module ActionDispatch # Mount a Rack-based application to be used within the application. # - # mount SomeRackApp, :at => "some_route" + # mount SomeRackApp, :at => "some_route" # # Alternatively: # - # mount(SomeRackApp => "some_route") + # mount(SomeRackApp => "some_route") # # 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+. # To customize this helper's name, use the +:as+ option: # - # mount(SomeRackApp => "some_route", :as => "exciting") + # mount(SomeRackApp => "some_route", :as => "exciting") # # This will generate the +exciting_path+ and +exciting_url+ helpers # which can be used to navigate to this mounted app. -- cgit v1.2.3 From fe0e3880e8ce8311882f3856b689c2f79a13ced4 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Thu, 9 Dec 2010 20:21:08 +1000 Subject: root route should go at the *top* of the routes file, because it is the most popular route and should be matched first --- actionpack/lib/action_dispatch/routing/mapper.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 086366c740..cf95f6fa53 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -247,7 +247,9 @@ module ActionDispatch # # root :to => 'pages#main' # - # You should put the root route at the end of config/routes.rb. + # You should put the root route at the top of config/routes.rb, + # because this means it will be matched first. As this is the most popular route + # of most Rails applications, this is beneficial. def root(options = {}) match '/', options.reverse_merge(:as => :root) end -- cgit v1.2.3 From 28cf77203b0b5af648e441b5d9cfb75863ba2f39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 9 Dec 2010 13:15:25 +0100 Subject: Check if the routes object really responds to define_mount_prefix. --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 5a38158e9f..47de5848fa 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -327,7 +327,7 @@ module ActionDispatch end def define_generate_prefix(app, name) - return unless app.respond_to?(:routes) + return unless app.respond_to?(:routes) && app.routes.respond_to?(:define_mounted_helper) _route = @set.named_routes.routes[name.to_sym] _routes = @set -- cgit v1.2.3 From f0d4b7f2a655ca2fb435af798714fee2de232d1e Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 10 Dec 2010 09:34:40 +1000 Subject: root method options are the same as the match method --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index cf95f6fa53..3039f88f71 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -247,6 +247,8 @@ module ActionDispatch # # root :to => 'pages#main' # + # For options, see the +match+ method's documentation, as +root+ uses it internally. + # # You should put the root route at the top of config/routes.rb, # because this means it will be matched first. As this is the most popular route # of most Rails applications, this is beneficial. -- cgit v1.2.3 From dbf955c03b8d185b7977d90281389cf52d546c5d Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 10 Dec 2010 15:55:46 +1000 Subject: Action Controller Overview: Remove dead link to the API docs for filters --- actionpack/lib/action_dispatch/routing/mapper.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 3039f88f71..494cdbf308 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1089,6 +1089,7 @@ module ActionDispatch end end + # See ActionDispatch::Routing::Mapper::Scoping#namespace def namespace(path, options = {}) if resource_scope? nested { super } -- cgit v1.2.3 From 751733ab963cce8780a71185344d8b31ba93c91d Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sat, 11 Dec 2010 17:25:28 +1000 Subject: Provide an example for ActionDispatch::Routing::Mapper#scope --- actionpack/lib/action_dispatch/routing/mapper.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 430fcdbe07..45248cf34c 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -458,6 +458,18 @@ module ActionDispatch super end + # Used to scope a set of routes to particular constraints. + # + # Take the following route definition as an example: + # + # scope :path => ":account_id", :as => "account" do + # resources :projects + # end + # + # This generates helpers such as +account_projects_path+, just like +resources+ does. + # 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 -- cgit v1.2.3 From a81f68e879198cb4e01f3cda2671c93f1ef0bc1a Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Mon, 13 Dec 2010 13:03:41 +1000 Subject: Fix indentation on the namespace method's documentation --- actionpack/lib/action_dispatch/routing/mapper.rb | 32 ++++++++++++------------ 1 file changed, 16 insertions(+), 16 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 45248cf34c..f65a294eca 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -570,13 +570,13 @@ module ActionDispatch # # This generates the following routes: # - # admin_posts GET /admin/posts(.:format) {:action=>"index", :controller=>"admin/posts"} - # admin_posts POST /admin/posts(.:format) {:action=>"create", :controller=>"admin/posts"} - # new_admin_post GET /admin/posts/new(.:format) {:action=>"new", :controller=>"admin/posts"} - # edit_admin_post GET /admin/posts/:id/edit(.:format) {:action=>"edit", :controller=>"admin/posts"} - # 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"} + # admin_posts GET /admin/posts(.:format) {:action=>"index", :controller=>"admin/posts"} + # admin_posts POST /admin/posts(.:format) {:action=>"create", :controller=>"admin/posts"} + # new_admin_post GET /admin/posts/new(.:format) {:action=>"new", :controller=>"admin/posts"} + # edit_admin_post GET /admin/posts/:id/edit(.:format) {:action=>"edit", :controller=>"admin/posts"} + # 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. @@ -584,24 +584,24 @@ module ActionDispatch # [:path] # The path prefix for the routes. # - # namespace :admin, :path => "sekret" do - # resources :posts - # end + # namespace :admin, :path => "sekret" do + # resources :posts + # end # # 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 + # namespace :admin, :module => "sekret" do + # resources :posts + # end # # The +PostsController+ here should go in the +Sekret+ namespace and so it should be defined like this: # - # class Sekret::PostsController < ApplicationController - # # code go here - # end + # class Sekret::PostsController < ApplicationController + # # code go here + # end # # [:as] # Changes the name used in routing helpers for this namespace. -- cgit v1.2.3 From ebc47465a5865ab91dc7d058d2d8a0cc961510d7 Mon Sep 17 00:00:00 2001 From: brainopia Date: Thu, 9 Dec 2010 18:38:52 +0300 Subject: Fix edge cases for domain :all option on cookie store Dont set explicit domain for cookies if host is not a domain name [#6002 state:committed] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/middleware/cookies.rb | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index b0a4e3d949..f369d2d3c2 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -131,8 +131,11 @@ module ActionDispatch options[:path] ||= "/" if options[:domain] == :all - @host =~ DOMAIN_REGEXP - options[:domain] = ".#{$1}.#{$2}" + # 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}" + end end end -- cgit v1.2.3 From 5008d33eee4767cd84b1087ceec827f1eaec90d0 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 17 Dec 2010 11:31:08 -0800 Subject: dry up case / when statement --- actionpack/lib/action_dispatch/routing/polymorphic_routes.rb | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index 49e237f8db..82c4fadb50 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -99,11 +99,9 @@ module ActionDispatch record = extract_record(record_or_hash_or_array) record = record.to_model if record.respond_to?(:to_model) - args = case record_or_hash_or_array - when Hash; [ record_or_hash_or_array ] - when Array; record_or_hash_or_array.dup - else [ record_or_hash_or_array ] - end + args = Array === record_or_hash_or_array ? + record_or_hash_or_array.dup : + [ record_or_hash_or_array ] inflection = if options[:action] && options[:action].to_s == "new" args.pop -- cgit v1.2.3 From 0f7c970e4f1cf0f3bcc01c22a6a3038cb3e34668 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Tue, 23 Nov 2010 18:04:05 -0800 Subject: Introduce ActionDispatch::Reloader MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Based on the implementation on the 2-3-stable branch, patches by Hongli Lai , and helpful suggestions from José Valim. Hongli Lai's patches included locking around the request cycle; this is now handled by Rack::Lock (https://github.com/rack/rack/issues/issue/87/). [#2873] Signed-off-by: José Valim --- .../lib/action_dispatch/middleware/reloader.rb | 82 ++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 actionpack/lib/action_dispatch/middleware/reloader.rb (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb new file mode 100644 index 0000000000..b84410fc62 --- /dev/null +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -0,0 +1,82 @@ +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 + # request is fully complete -- that is, after #close has been called on + # the request body. This is important for streaming responses such as the + # following: + # + # self.response_body = lambda { |response, output| + # # code here which refers to application models + # } + # + # Cleanup callbacks will not be called until after the response_body lambda + # is evaluated, ensuring that it can refer to application models and other + # classes before they are unloaded. + # + # By default, ActionDispatch::Reloader is included in the middleware stack + # only in the development environment. + # + class Reloader + include ActiveSupport::Callbacks + + define_callbacks :prepare, :scope => :name + define_callbacks :cleanup, :scope => :name + + # Add a preparation callback. Preparation callbacks are run before each + # request. + # + # If a symbol with a block is given, the symbol is used as an identifier. + # That allows to_prepare to be called again with the same identifier to + # replace the existing callback. Passing an identifier is a suggested + # practice if the code adding a preparation block may be reloaded. + def self.to_prepare(*args, &block) + first_arg = args.first + if first_arg.is_a?(Symbol) && block_given? + remove_method :"__#{first_arg}" if method_defined?(:"__#{first_arg}") + define_method :"__#{first_arg}", &block + set_callback(:prepare, :"__#{first_arg}") + else + set_callback(:prepare, *args, &block) + end + end + + # Add a cleanup callback. Cleanup callbacks are run after each request is + # complete (after #close is called on the response body). + def self.to_cleanup(&block) + set_callback(:cleanup, &block) + end + + def self.prepare! + new(nil).send(:_run_prepare_callbacks) + end + + def self.cleanup! + new(nil).send(:_run_cleanup_callbacks) + end + + def self.reload! + prepare! + cleanup! + end + + def initialize(app) + @app = app + end + + module CleanupOnClose + def close + super if defined?(super) + ensure + ActionDispatch::Reloader.cleanup! + end + end + + def call(env) + _run_prepare_callbacks + response = @app.call(env) + response[2].extend(CleanupOnClose) + response + end + end +end -- cgit v1.2.3 From 435bccda930e4dde3d0fafca958e1c8330b4c3ca Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Sun, 19 Dec 2010 15:58:58 -0800 Subject: Replace AD::Callbacks.to_prepare with AD::Reloader.to_prepare MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- .../lib/action_dispatch/middleware/callbacks.rb | 31 +++++----------------- 1 file changed, 6 insertions(+), 25 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb index 0bb950d1cc..5776a7bb27 100644 --- a/actionpack/lib/action_dispatch/middleware/callbacks.rb +++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb @@ -1,32 +1,14 @@ module ActionDispatch # Provide callbacks to be executed before and after the request dispatch. - # - # It also provides a to_prepare callback, which is performed in all requests - # in development by only once in production and notification callback for async - # operations. - # class Callbacks include ActiveSupport::Callbacks define_callbacks :call, :rescuable => true - define_callbacks :prepare, :scope => :name - # Add a preparation callback. Preparation callbacks are run before every - # request in development mode, and before the first request in production mode. - # - # If a symbol with a block is given, the symbol is used as an identifier. - # That allows to_prepare to be called again with the same identifier to - # replace the existing callback. Passing an identifier is a suggested - # practice if the code adding a preparation block may be reloaded. def self.to_prepare(*args, &block) - first_arg = args.first - if first_arg.is_a?(Symbol) && block_given? - remove_method :"__#{first_arg}" if method_defined?(:"__#{first_arg}") - define_method :"__#{first_arg}", &block - set_callback(:prepare, :"__#{first_arg}") - else - set_callback(:prepare, *args, &block) - end + ActiveSupport::Deprecation.warn "ActionDispatch::Callbacks.to_prepare is deprecated. " << + "Please use ActionDispatch::Reloader.to_prepare instead." + ActionDispatch::Reloader.to_prepare(*args, &block) end def self.before(*args, &block) @@ -37,14 +19,13 @@ module ActionDispatch set_callback(:call, :after, *args, &block) end - def initialize(app, prepare_each_request = false) - @app, @prepare_each_request = app, prepare_each_request - _run_prepare_callbacks + def initialize(app, unused = nil) + ActiveSupport::Deprecation.warn "Passing a second argument to ActionDispatch::Callbacks.new is deprecated." unless unused.nil? + @app = app end def call(env) _run_call_callbacks do - _run_prepare_callbacks if @prepare_each_request @app.call(env) end end -- cgit v1.2.3 From 0cbfd6c28d327304432f7d0c067662b5c1e41a78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 20 Dec 2010 12:41:49 +0100 Subject: Small changes on AD::Reloader. --- .../lib/action_dispatch/middleware/reloader.rb | 23 +++------------------- 1 file changed, 3 insertions(+), 20 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index b84410fc62..579b5d8a02 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -25,26 +25,14 @@ module ActionDispatch # Add a preparation callback. Preparation callbacks are run before each # request. - # - # If a symbol with a block is given, the symbol is used as an identifier. - # That allows to_prepare to be called again with the same identifier to - # replace the existing callback. Passing an identifier is a suggested - # practice if the code adding a preparation block may be reloaded. def self.to_prepare(*args, &block) - first_arg = args.first - if first_arg.is_a?(Symbol) && block_given? - remove_method :"__#{first_arg}" if method_defined?(:"__#{first_arg}") - define_method :"__#{first_arg}", &block - set_callback(:prepare, :"__#{first_arg}") - else - set_callback(:prepare, *args, &block) - end + set_callback(:prepare, *args, &block) end # Add a cleanup callback. Cleanup callbacks are run after each request is # complete (after #close is called on the response body). - def self.to_cleanup(&block) - set_callback(:cleanup, &block) + def self.to_cleanup(*args, &block) + set_callback(:cleanup, *args, &block) end def self.prepare! @@ -55,11 +43,6 @@ module ActionDispatch new(nil).send(:_run_cleanup_callbacks) end - def self.reload! - prepare! - cleanup! - end - def initialize(app) @app = app end -- cgit v1.2.3 From d4afde9ab025854b35634af51fe2ef4edf1f8549 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Mon, 20 Dec 2010 14:55:21 -0800 Subject: Expand ActionDispatch::Reloader docs --- .../lib/action_dispatch/middleware/reloader.rb | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index 579b5d8a02..efa0bc7129 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -1,7 +1,10 @@ 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 # following: @@ -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,10 +41,12 @@ module ActionDispatch set_callback(:cleanup, *args, &block) end + # Execute all prepare callbacks. def self.prepare! new(nil).send(:_run_prepare_callbacks) end + # Execute all cleanup callbacks. def self.cleanup! new(nil).send(:_run_cleanup_callbacks) end -- cgit v1.2.3 From 0b0e6f13c02a425f60bfed9db401392d72f419c6 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Tue, 21 Dec 2010 19:32:34 -0800 Subject: Typo (request -> response) --- actionpack/lib/action_dispatch/middleware/reloader.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index efa0bc7129..7624a1871a 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -6,7 +6,7 @@ module ActionDispatch # 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| -- cgit v1.2.3 From 819b8cae40623d26ce3c050d482b490539a25b98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 23 Dec 2010 19:17:02 +0100 Subject: Clean up callbacks should also be called on exceptions. --- actionpack/lib/action_dispatch/middleware/reloader.rb | 3 +++ 1 file changed, 3 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index 7624a1871a..f6ab368ad8 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -68,6 +68,9 @@ module ActionDispatch response = @app.call(env) response[2].extend(CleanupOnClose) response + rescue Exception + _run_cleanup_callbacks + raise end end end -- cgit v1.2.3 From d6efd3cfc2c6d6822aeac550852c49135fbe46c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Thu, 23 Dec 2010 19:20:57 +0100 Subject: Don't deprecate to_prepare. --- actionpack/lib/action_dispatch/middleware/callbacks.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb index 5776a7bb27..4d038c29f2 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) -- cgit v1.2.3 From 9bc879d42a39971f26bda182ca01af30fc70a46e Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 1 Jan 2011 13:13:48 -0200 Subject: This is not needed anymore --- .../action_dispatch/middleware/templates/rescues/template_error.erb | 3 --- 1 file changed, 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') 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..303b62c3a7 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,6 @@

<%=h @exception.sub_template_message %>

-<% @real_exception = @exception - @exception = @exception.original_exception || @exception %> <%= render :file => "rescues/_trace.erb" %> -<% @exception = @real_exception %> <%= render :file => "rescues/_request_and_response.erb" %> -- cgit v1.2.3 From 171172f324444a9ea9c98e4f3663c6e401fb3ec7 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 1 Jan 2011 13:44:34 -0200 Subject: render :template is faster than render :file --- .../lib/action_dispatch/middleware/templates/rescues/diagnostics.erb | 4 ++-- .../action_dispatch/middleware/templates/rescues/template_error.erb | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') 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 @@
<%=h @exception.message %>
-<%= 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 303b62c3a7..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,6 +13,5 @@

<%=h @exception.sub_template_message %>

-<%= render :file => "rescues/_trace.erb" %> - -<%= render :file => "rescues/_request_and_response.erb" %> +<%= render :template => "rescues/_trace" %> +<%= render :template => "rescues/_request_and_response" %> -- cgit v1.2.3 From 366e7854ac41699217e8cad1a336ab845c781359 Mon Sep 17 00:00:00 2001 From: Krekoten' Marjan Date: Tue, 19 Oct 2010 00:05:22 +0300 Subject: Refactor to handle the X-Cascade without having to raise an exception --- .../action_dispatch/middleware/show_exceptions.rb | 24 +++++++++++----------- 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 71e736ce9f..936fd548b9 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' + exception = ActionController::RoutingError.new("No route matches #{env['PATH_INFO'].inspect}") + end + rescue Exception => exception 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 -- cgit v1.2.3 From 1d9c555297c15b6d5212e65c1afec718e043ce45 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 12 Jan 2011 10:01:31 -0800 Subject: reraising should be in the rescue block --- actionpack/lib/action_dispatch/middleware/show_exceptions.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 936fd548b9..11739e08d9 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -53,8 +53,8 @@ module ActionDispatch exception = ActionController::RoutingError.new("No route matches #{env['PATH_INFO'].inspect}") end rescue Exception => exception + raise exception if env['action_dispatch.show_exceptions'] == false end - raise exception if env['action_dispatch.show_exceptions'] == false exception ? render_exception(env, exception) : [status, headers, body] end -- cgit v1.2.3 From 16ae08fff0f16b3f0eb7757e01aabb02b257bd35 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 12 Jan 2011 10:28:21 -0800 Subject: use raise to create exceptions and to set the backtrace --- actionpack/lib/action_dispatch/middleware/show_exceptions.rb | 2 +- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 11739e08d9..dbe3206808 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -50,7 +50,7 @@ module ActionDispatch # Only this middleware cares about RoutingError. So, let's just raise # it here. if headers['X-Cascade'] == 'pass' - exception = ActionController::RoutingError.new("No route matches #{env['PATH_INFO'].inspect}") + raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect}" end rescue Exception => exception raise exception if env['action_dispatch.show_exceptions'] == false diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 03bfe178e5..683fa19380 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? -- cgit v1.2.3 From 9702159373a4df8f05d06e79dfa0f57723f8bfc8 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 17 Jan 2011 14:33:34 -0800 Subject: removing more unused variables --- actionpack/lib/action_dispatch/http/cache.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') 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"] -- cgit v1.2.3 From 91a4193ee002d20e1b9bd637a5f14ac6213c8f39 Mon Sep 17 00:00:00 2001 From: brainopia Date: Fri, 21 Jan 2011 14:58:33 +0300 Subject: Support list of possible domains for cookies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/middleware/cookies.rb | 3 +++ 1 file changed, 3 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index f369d2d3c2..0a230fed2c 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -136,6 +136,9 @@ module ActionDispatch options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ DOMAIN_REGEXP) ".#{$1}.#{$2}" 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 -- cgit v1.2.3 From 8491f16e128d2d2cfe53676f36c5d4c281712bde Mon Sep 17 00:00:00 2001 From: brainopia Date: Fri, 21 Jan 2011 14:59:49 +0300 Subject: Add tld_length option when using domain :all in cookies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- actionpack/lib/action_dispatch/middleware/cookies.rb | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index 0a230fed2c..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,10 +128,13 @@ 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 -- cgit v1.2.3 From cc9301f459739e3eb3674b1b2e15057e35d25630 Mon Sep 17 00:00:00 2001 From: Matt Jankowski Date: Thu, 27 Jan 2011 12:25:22 -0500 Subject: clarify what the "they" that are is and what the "are" in question is --- actionpack/lib/action_dispatch/routing/mapper.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f65a294eca..6658af15b0 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -827,7 +827,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 -- cgit v1.2.3 From 49744bdaee899d64f8c70f65b2c1d63ace41cafa Mon Sep 17 00:00:00 2001 From: Jonathan Dance + Gabriel Horner Date: Fri, 28 Jan 2011 16:55:21 -0500 Subject: fix cross-references in HttpHelper methods --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 6658af15b0..af7a2c31f4 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -349,7 +349,7 @@ module ActionDispatch module HttpHelpers # Define a route that only recognizes HTTP GET. - # For supported arguments, see +match+. + # For supported arguments, see Base#match. # # Example: # @@ -359,7 +359,7 @@ module ActionDispatch end # Define a route that only recognizes HTTP POST. - # For supported arguments, see +match+. + # For supported arguments, see Base#match. # # Example: # @@ -369,7 +369,7 @@ module ActionDispatch end # Define a route that only recognizes HTTP PUT. - # For supported arguments, see +match+. + # For supported arguments, see Base#match. # # Example: # @@ -379,7 +379,7 @@ module ActionDispatch end # Define a route that only recognizes HTTP PUT. - # For supported arguments, see +match+. + # For supported arguments, see Base#match. # # Example: # -- cgit v1.2.3 From 38d728fb944b08b7faabf19c8ba5ef2e69e29c16 Mon Sep 17 00:00:00 2001 From: Jonathan Dance + Gabriel Horner Date: Fri, 28 Jan 2011 17:01:48 -0500 Subject: add cross-references and documentation for scope --- actionpack/lib/action_dispatch/routing.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'actionpack/lib/action_dispatch') 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 Routing::Mapper::Resources#resources, + # Routing::Mapper::Scoping#namespace, and + # Routing::Mapper::Scoping#scope. + # # == Named routes # # Routes can be named by passing an :as option, -- cgit v1.2.3 From ef48408a7bed075089999f588250f9710bca8f40 Mon Sep 17 00:00:00 2001 From: misfo Date: Sat, 29 Jan 2011 16:03:40 -0600 Subject: corrected the location of status code symbols --- actionpack/lib/action_dispatch/testing/assertions/response.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') 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 assert_response(501) # or its symbolic equivalent assert_response(:not_implemented). - # See ActionDispatch::StatusCodes for a full list. + # See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list. # # ==== Examples # -- cgit v1.2.3 From fab16fded9a68cd327b6cfc5439ff10eed6df40b Mon Sep 17 00:00:00 2001 From: Jonathan Dance + Gabriel Horner Date: Sat, 29 Jan 2011 10:16:45 -0500 Subject: organize and expand on options for routing methods --- actionpack/lib/action_dispatch/routing/mapper.rb | 242 +++++++++++++++-------- 1 file changed, 161 insertions(+), 81 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index af7a2c31f4..ee0fdce9dd 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -265,6 +265,78 @@ module ActionDispatch # 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. + # + # === Supported options + # + # [: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 Scoping#namespace 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] + # Shorthand for specifying :controller and :action. + # + # match 'path' => 'c#a', :to => 'controller#action' + # + # [:on] + # Shorthand for wrapping routes in a specific RESTful context. Valid + # values are :member, :collection, and :new. Only use within + # resource(s) block. For example: + # + # resource :bar do + # match 'foo' => 'c#a', :on => :member, :via => [:get, :post] + # end + # + # Is equivalent to: + # + # 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 + # + # See Scoping#constraints 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 Scoping#defaults for its scope equivalent. def match(path, options=nil) mapping = Mapping.new(@set, @scope, path, options || {}).to_route @set.add_route(*mapping) @@ -458,7 +530,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: # @@ -471,50 +543,25 @@ module ActionDispatch # 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 # - # This will prefix all of the +posts+ resource's requests with '/admin' + # Takes same options as Base#match and Resources#resources. # - # [:as] - # Prefixes the routing helpers in this scope with the specified label. - # - # 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. + # === Examples # - # 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 +624,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. - # - # [:path] - # The path prefix for the routes. # - # namespace :admin, :path => "sekret" do - # resources :posts - # end - # - # All routes for the above +resources+ will be accessible through +/sekret/posts+, rather than +/admin/posts+ - # - # [:module] - # The namespace for the controllers. + # === Supported options # - # namespace :admin, :module => "sekret" do - # resources :posts - # end + # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ + # options all default to the name of the namespace. # - # The +PostsController+ here should go in the +Sekret+ namespace and so it should be defined like this: + # For options, see Base#match. For +:shallow_path+ option, see + # Resources#resources. # - # class Sekret::PostsController < ApplicationController - # # code go here - # end + # === Examples # - # [: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 +715,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 } @@ -907,6 +942,9 @@ module ActionDispatch # GET /geocoder/edit # PUT /geocoder # DELETE /geocoder + # + # === Supported options + # Takes same options as +resources+. def resource(*resources, &block) options = resources.extract_options! @@ -969,6 +1007,8 @@ module ActionDispatch # DELETE /photos/:id/comments/:id # # === Supported options + # Takes same options as Base#match as well as: + # # [:path_names] # Allows you to change the paths of the seven default actions. # Paths not specified are not changed. @@ -977,20 +1017,60 @@ 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) + # + # === Examples # - # Set a path prefix for this resource. + # # routes call Admin::PostsController + # resources :posts, :module => "admin" # - # resources :posts, :path => "admin" + # # resource actions are at /admin/posts. + # resources :posts, :path => "admin" # - # All actions for this resource will now be at +/admin/posts+. def resources(*resources, &block) options = resources.extract_options! -- cgit v1.2.3 From d1ef543794efdcc1d225055f88cbc88b20e84921 Mon Sep 17 00:00:00 2001 From: Jonathan Dance + Gabriel Horner Date: Sat, 29 Jan 2011 17:24:37 -0500 Subject: explain different ways to use match() --- actionpack/lib/action_dispatch/routing/mapper.rb | 25 +++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index ee0fdce9dd..b28b68ad83 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -256,15 +256,22 @@ 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. - # - # match ':controller/:action/:id/:user_id' - # - # 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. + # Matches a pattern to one or more urls. Any symbols in a pattern are + # interpreted as url parameters: + # + # # sets parameters :controller, :action and :id + # match ':controller/:action/:id' + # + # Two of these symbols are special: :controller maps to the + # controller name and :action to the action name within that + # controller. Anything other than :controller or + # :action will be available to the action as part of +params+. + # If a pattern does not have :controller and :action symbols, then they + # must be set in options or shorthand. For example: + # + # match 'photos/:id' => 'photos#show' + # match 'photos/:id', :to => 'photos#show' + # match 'photos/:id', :controller => 'photos', :action => 'show' # # === Supported options # -- cgit v1.2.3 From 57bc25c5f8129f57b08a2dc7c319b86778dd8a40 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Sun, 9 Jan 2011 10:15:05 -0800 Subject: Use run_callbacks; the generated _run__callbacks method is not a public interface. Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/middleware/callbacks.rb | 2 +- actionpack/lib/action_dispatch/middleware/reloader.rb | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb index 4d038c29f2..1bb2ad7f67 100644 --- a/actionpack/lib/action_dispatch/middleware/callbacks.rb +++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb @@ -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/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index f6ab368ad8..29289a76b4 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -43,12 +43,12 @@ module ActionDispatch # 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) @@ -64,12 +64,12 @@ module ActionDispatch end def call(env) - _run_prepare_callbacks + run_callbacks :prepare response = @app.call(env) response[2].extend(CleanupOnClose) response rescue Exception - _run_cleanup_callbacks + run_callbacks :cleanup raise end end -- cgit v1.2.3 From a0757e00f3ec2925ee6fdd25498725acf66fae98 Mon Sep 17 00:00:00 2001 From: Stephen Celis Date: Sat, 9 Oct 2010 09:13:45 -0500 Subject: Protocol-relative URL support. [#5774 state:committed] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/http/url.rb | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') 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] -- cgit v1.2.3 From ac15647bf0e6ed85714dee4e2b14b2e7e6f29320 Mon Sep 17 00:00:00 2001 From: Gabriel Horner Date: Thu, 3 Feb 2011 23:51:06 -0500 Subject: keep options titles consistent to "Options" --- actionpack/lib/action_dispatch/routing/mapper.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index b28b68ad83..b5ff6e0dcb 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -273,7 +273,7 @@ module ActionDispatch # match 'photos/:id', :to => 'photos#show' # match 'photos/:id', :controller => 'photos', :action => 'show' # - # === Supported options + # === Options # # [:controller] # The route's controller. @@ -549,7 +549,7 @@ module ActionDispatch # The difference here being that the routes generated are like /rails/projects/2, # rather than /accounts/rails/projects/2. # - # === Supported options + # === Options # # Takes same options as Base#match and Resources#resources. # @@ -632,7 +632,7 @@ module ActionDispatch # 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 + # === Options # # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ # options all default to the name of the namespace. @@ -950,7 +950,7 @@ module ActionDispatch # PUT /geocoder # DELETE /geocoder # - # === Supported options + # === Options # Takes same options as +resources+. def resource(*resources, &block) options = resources.extract_options! @@ -1013,7 +1013,7 @@ module ActionDispatch # PUT /photos/:id/comments/:id # DELETE /photos/:id/comments/:id # - # === Supported options + # === Options # Takes same options as Base#match as well as: # # [:path_names] -- cgit v1.2.3 From adbae9aab8a439a824cf1612febb5918d0f4cf87 Mon Sep 17 00:00:00 2001 From: german Date: Fri, 4 Feb 2011 11:51:34 -0500 Subject: fixed bug with nested resources within shallow scope [#6372 state:committed] Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index b28b68ad83..c38e9ef2c4 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1199,7 +1199,7 @@ module ActionDispatch end def shallow - scope(:shallow => true) do + scope(:shallow => true, :shallow_path => @scope[:path]) do yield end end -- cgit v1.2.3 From 277327bb7f389a140eb4ae7722d64d6cf45e06cf Mon Sep 17 00:00:00 2001 From: Gabriel Horner Date: Sat, 5 Feb 2011 13:12:09 -0500 Subject: improve routing docs, mostly for #match --- actionpack/lib/action_dispatch/routing/mapper.rb | 46 +++++++++++++++++------- 1 file changed, 34 insertions(+), 12 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index b5ff6e0dcb..a91b2e88fb 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -247,7 +247,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 config/routes.rb, # because this means it will be matched first. As this is the most popular route @@ -256,25 +256,42 @@ module ActionDispatch match '/', options.reverse_merge(:as => :root) end - # Matches a pattern to one or more urls. Any symbols in a pattern are - # interpreted as url parameters: + # 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 parameters :controller, :action and :id + # # sets :controller, :action and :id in params # match ':controller/:action/:id' # - # Two of these symbols are special: :controller maps to the - # controller name and :action to the action name within that - # controller. Anything other than :controller or - # :action will be available to the action as part of +params+. - # If a pattern does not have :controller and :action symbols, then they - # must be set in options or shorthand. For example: + # 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. # @@ -302,9 +319,12 @@ module ActionDispatch # match 'path' => 'c#a', :via => [:get, :post] # # [:to] - # Shorthand for specifying :controller and :action. + # Points to a +Rack+ endpoint. Can be an object that responds to + # +call+ or a string representing a controller's action. # - # match 'path' => 'c#a', :to => 'controller#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 @@ -358,6 +378,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+. -- cgit v1.2.3 From 6b1018526fb304727ee4191afc2d8a5e29e49eea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Sun, 28 Nov 2010 22:40:32 +0100 Subject: Use Mime::Type references. --- actionpack/lib/action_dispatch/http/mime_type.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') 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) -- cgit v1.2.3 From ae19e4141f27f80013c11e8b1da68e5c52c779ea Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Wed, 5 Jan 2011 13:36:07 +1300 Subject: Change the CSRF whitelisting to only apply to get requests Unfortunately the previous method of browser detection and XHR whitelisting is unable to prevent requests issued from some Flash animations and Java applets. To ease the work required to include the CSRF token in ajax requests rails now supports providing the token in a custom http header: X-CSRF-Token: ... This fixes CVE-2011-0447 --- actionpack/lib/action_dispatch/http/request.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 08f30e068d..a5d4ecbba8 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -133,8 +133,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 -- cgit v1.2.3 From f23bf7dbdbc0e0590083f0f288aa24f5b830e685 Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Fri, 11 Feb 2011 09:33:16 -0200 Subject: Add missing deprecation require Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/http/request.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index a5d4ecbba8..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' -- cgit v1.2.3 From 385be358cfa80cedff113ba57338e83ca8ac2b52 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Sun, 13 Feb 2011 23:24:46 +0000 Subject: Fix assert_recognizes with block constraints [#5805 state:resolved] --- actionpack/lib/action_dispatch/routing/mapper.rb | 12 ++++++++---- actionpack/lib/action_dispatch/routing/route_set.rb | 4 +++- actionpack/lib/action_dispatch/testing/assertions/routing.rb | 3 ++- 3 files changed, 13 insertions(+), 6 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f3f7cb6507..2f12192af4 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 diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 683fa19380..4b4e9da173 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -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/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 1390b74a95..f440e74691 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -124,7 +124,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. -- cgit v1.2.3 From af4fab7d2ed5568b5c998ff5b02c907da4f3a357 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Sun, 13 Feb 2011 23:25:57 +0000 Subject: Remove incorrect assert_recognizes example --- actionpack/lib/action_dispatch/testing/assertions/routing.rb | 3 --- 1 file changed, 3 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index f440e74691..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) -- cgit v1.2.3 From fd7605826a6e4f7590e4abf42c6c9d0923afc4ef Mon Sep 17 00:00:00 2001 From: Andrew White Date: Mon, 14 Feb 2011 00:40:53 +0000 Subject: Add notes on how to override the default :id constraint [#5994 state:resolved] --- actionpack/lib/action_dispatch/routing/mapper.rb | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 2f12192af4..85c09a3fda 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -847,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. @@ -1103,7 +1111,6 @@ module ActionDispatch # # # resource actions are at /admin/posts. # resources :posts, :path => "admin" - # def resources(*resources, &block) options = resources.extract_options! -- cgit v1.2.3 From 460a341682518f554f5466a7b010c2bc51875060 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Mon, 14 Feb 2011 02:56:09 +0000 Subject: Fix named route helper for routes nested inside deeply nested resources [#6416 state:resolved] --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 85c09a3fda..589df218a8 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1442,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 -- cgit v1.2.3 From 2dbb73bdda3b81947fd112486ac4285fb1a6e3a9 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 28 Feb 2011 17:54:00 -0800 Subject: compute ext in initialize, and use an attr_reader --- actionpack/lib/action_dispatch/middleware/static.rb | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index 913b899e20..40c85d420a 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -2,11 +2,16 @@ require 'rack/utils' module ActionDispatch class FileHandler + attr_reader :ext + def initialize(at, root) @at, @root = at.chomp('/'), root.chomp('/') @compiled_at = (Regexp.compile(/^#{Regexp.escape(at)}/) unless @at.blank?) @compiled_root = Regexp.compile(/^#{Regexp.escape(root)}/) @file_server = ::Rack::File.new(@root) + + ext = ::ActionController::Base.page_cache_extension + @ext = "{,#{ext},/index#{ext}}" end def match?(path) @@ -27,13 +32,6 @@ module ActionDispatch def call(env) @file_server.call(env) end - - def ext - @ext ||= begin - ext = ::ActionController::Base.page_cache_extension - "{,#{ext},/index#{ext}}" - end - end end class Static -- cgit v1.2.3 From f279422e3346314ebec6b2156534c0fa5ebd5a98 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 28 Feb 2011 18:03:06 -0800 Subject: no need to pass a regex to Regexp.compile --- actionpack/lib/action_dispatch/middleware/static.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index 40c85d420a..c5598f3e56 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -5,10 +5,10 @@ module ActionDispatch attr_reader :ext def initialize(at, root) - @at, @root = at.chomp('/'), root.chomp('/') - @compiled_at = (Regexp.compile(/^#{Regexp.escape(at)}/) unless @at.blank?) - @compiled_root = Regexp.compile(/^#{Regexp.escape(root)}/) - @file_server = ::Rack::File.new(@root) + @at, @root = at.chomp('/'), root.chomp('/') + @compiled_at = /^#{Regexp.escape(at)}/ unless @at.blank? + @compiled_root = /^#{Regexp.escape(root)}/ + @file_server = ::Rack::File.new(@root) ext = ::ActionController::Base.page_cache_extension @ext = "{,#{ext},/index#{ext}}" -- cgit v1.2.3 From 46bb4242874fe716268e3bb7b1ce3bb3c2d883e4 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 28 Feb 2011 19:47:09 -0800 Subject: Revert "compute ext in initialize, and use an attr_reader" This reverts commit 2dbb73bdda3b81947fd112486ac4285fb1a6e3a9. Conflicts: actionpack/lib/action_dispatch/middleware/static.rb --- actionpack/lib/action_dispatch/middleware/static.rb | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index c5598f3e56..5076567bd4 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -2,16 +2,11 @@ require 'rack/utils' module ActionDispatch class FileHandler - attr_reader :ext - def initialize(at, root) @at, @root = at.chomp('/'), root.chomp('/') @compiled_at = /^#{Regexp.escape(at)}/ unless @at.blank? @compiled_root = /^#{Regexp.escape(root)}/ @file_server = ::Rack::File.new(@root) - - ext = ::ActionController::Base.page_cache_extension - @ext = "{,#{ext},/index#{ext}}" end def match?(path) @@ -32,6 +27,13 @@ module ActionDispatch def call(env) @file_server.call(env) end + + def ext + @ext ||= begin + ext = ::ActionController::Base.page_cache_extension + "{,#{ext},/index#{ext}}" + end + end end class Static -- cgit v1.2.3 From 648fd60ecf72e77c6326aac63244d9305611ed0c Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 1 Mar 2011 10:14:01 -0800 Subject: prefer composition over inheritance with AD::MS --- actionpack/lib/action_dispatch/middleware/stack.rb | 45 ++++++++++++++++++---- 1 file changed, 37 insertions(+), 8 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index e3cd779756..852f697d91 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -2,7 +2,7 @@ require "active_support/inflector/methods" require "active_support/dependencies" module ActionDispatch - class MiddlewareStack < Array + class MiddlewareStack class Middleware attr_reader :args, :block @@ -41,18 +41,43 @@ module ActionDispatch end end - # Use this instead of super to work around a warning. - alias :array_initialize :initialize + include Enumerable + + attr_accessor :middlewares def initialize(*args) - array_initialize(*args) + @middlewares = [] yield(self) if block_given? end + def each + @middlewares.each { |x| yield x } + end + + def size + middlewares.size + end + + def last + middlewares.last + end + + def [](i) + middlewares[i] + end + + def include?(item) + middlewares.include? item + end + + def initialize_copy(other) + self.middlewares = other.middlewares.dup + end + def insert(index, *args, &block) index = assert_index(index, :before) middleware = self.class::Middleware.new(*args, &block) - super(index, middleware) + middlewares.insert(index, middleware) end alias_method :insert_before, :insert @@ -67,21 +92,25 @@ module ActionDispatch delete(target) end + def delete(target) + middlewares.delete target + end + def use(*args, &block) middleware = self.class::Middleware.new(*args, &block) - push(middleware) + middlewares.push(middleware) end def build(app = nil, &block) app ||= block raise "MiddlewareStack#build requires an app" unless app - reverse.inject(app) { |a, e| e.build(a) } + middlewares.reverse.inject(app) { |a, e| e.build(a) } end protected def assert_index(index, where) - i = index.is_a?(Integer) ? index : self.index(index) + i = index.is_a?(Integer) ? index : middlewares.index(index) raise "No such middleware to insert #{where}: #{index.inspect}" unless i i end -- cgit v1.2.3 From fd26afc93be89df62584f6b28bd26ec9eea7ff00 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 1 Mar 2011 10:21:44 -0800 Subject: Enumerable gives us include?, so remove include? --- actionpack/lib/action_dispatch/middleware/stack.rb | 4 ---- 1 file changed, 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 852f697d91..a5f651297a 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -66,10 +66,6 @@ module ActionDispatch middlewares[i] end - def include?(item) - middlewares.include? item - end - def initialize_copy(other) self.middlewares = other.middlewares.dup end -- cgit v1.2.3 From 50ed1a25a4e496a7a67861b1a04d667bd3445bb6 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 1 Mar 2011 13:28:59 -0800 Subject: initialize ivars --- actionpack/lib/action_dispatch/middleware/static.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index 5076567bd4..c57f694c4d 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -4,7 +4,7 @@ module ActionDispatch class FileHandler def initialize(at, root) @at, @root = at.chomp('/'), root.chomp('/') - @compiled_at = /^#{Regexp.escape(at)}/ unless @at.blank? + @compiled_at = @at.blank? ? nil : /^#{Regexp.escape(at)}/ @compiled_root = /^#{Regexp.escape(root)}/ @file_server = ::Rack::File.new(@root) end -- cgit v1.2.3 From 7b6bfe84f332a3c99656f73cf0251bce0a16ba88 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 1 Mar 2011 17:20:10 -0800 Subject: refactor Reference to a ClassCache object, fix lazy lookup in Middleware so that anonymous classes are supported --- actionpack/lib/action_dispatch/middleware/stack.rb | 13 ++++++++++--- actionpack/lib/action_dispatch/routing/route_set.rb | 5 +++-- 2 files changed, 13 insertions(+), 5 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index a5f651297a..fe87abb4d0 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -7,12 +7,19 @@ module ActionDispatch attr_reader :args, :block def initialize(klass_or_name, *args, &block) - @ref = ActiveSupport::Dependencies::Reference.new(klass_or_name) + @klass = nil + @name = klass_or_name + + if klass_or_name.respond_to?(:name) + @klass = klass_or_name + @name = @klass.name + end + @args, @block = args, block end def klass - @ref.get + @klass ||= ActiveSupport::Inflector.constantize(@name) end def ==(middleware) @@ -22,7 +29,7 @@ module ActionDispatch when Class klass == middleware else - normalize(@ref.name) == normalize(middleware) + normalize(@name) == normalize(middleware) end end diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 4b4e9da173..2f764f88dc 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -50,12 +50,13 @@ module ActionDispatch private def controller_reference(controller_param) + controller_name = "#{controller_param.camelize}Controller" + unless controller = @controllers[controller_param] - controller_name = "#{controller_param.camelize}Controller" controller = @controllers[controller_param] = ActiveSupport::Dependencies.ref(controller_name) end - controller.get + controller.get(controller_name) end def dispatch(controller, action, env) -- cgit v1.2.3 From f345e2380cac2560f3bbd80defe1ef485e0d564e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 1 Mar 2011 17:43:45 -0800 Subject: yo dawg, directly use the class cache rather than the cache of the cache --- actionpack/lib/action_dispatch/middleware/stack.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index fe87abb4d0..d9bfd3d573 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -8,11 +8,12 @@ module ActionDispatch def initialize(klass_or_name, *args, &block) @klass = nil - @name = klass_or_name if klass_or_name.respond_to?(:name) @klass = klass_or_name @name = @klass.name + else + @name = klass_or_name.to_s end @args, @block = args, block -- cgit v1.2.3 From dd41387f343e813c40dc997135207f4ac81c58ab Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 2 Mar 2011 09:35:10 -0800 Subject: use newer class cache api --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 2f764f88dc..fc86d52a3a 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -54,7 +54,7 @@ module ActionDispatch unless controller = @controllers[controller_param] controller = @controllers[controller_param] = - ActiveSupport::Dependencies.ref(controller_name) + ActiveSupport::Dependencies.reference(controller_name) end controller.get(controller_name) end -- cgit v1.2.3 From 1f2e7214aaed01f50be12017f0ffbf9fcdbdbb5e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 2 Mar 2011 10:11:28 -0800 Subject: make sure string keys are always looked up from the class cache --- actionpack/lib/action_dispatch/middleware/stack.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index d9bfd3d573..a4308f528c 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -4,7 +4,7 @@ require "active_support/dependencies" module ActionDispatch class MiddlewareStack class Middleware - attr_reader :args, :block + attr_reader :args, :block, :name, :classcache def initialize(klass_or_name, *args, &block) @klass = nil @@ -16,11 +16,12 @@ module ActionDispatch @name = klass_or_name.to_s end + @classcache = ActiveSupport::Dependencies::Reference @args, @block = args, block end def klass - @klass ||= ActiveSupport::Inflector.constantize(@name) + @klass || classcache[@name] end def ==(middleware) -- cgit v1.2.3 From 87e9e3f9afa470df49f2a07af87074b9f4567028 Mon Sep 17 00:00:00 2001 From: "R.T. Lechow" Date: Fri, 4 Mar 2011 00:09:26 -0500 Subject: Action Pack typos. --- actionpack/lib/action_dispatch/routing/mapper.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 589df218a8..1733c8032a 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -700,7 +700,7 @@ module ActionDispatch # Now routes such as +/posts/1+ will no longer be valid, but +/posts/1.1+ will be. # The +id+ parameter must match the constraint passed in for this example. # - # You may use this to also resrict other parameters: + # You may use this to also restrict other parameters: # # resources :posts do # constraints(:post_id => /\d+\.\d+) do @@ -720,7 +720,7 @@ module ActionDispatch # # === Dynamic request matching # - # Requests to routes can be constrained based on specific critera: + # Requests to routes can be constrained based on specific criteria: # # constraints(lambda { |req| req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do # resources :iphones -- cgit v1.2.3 From e00867bc437b6a681491ef59e13423051e6d98f0 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Sun, 6 Mar 2011 07:08:50 +0000 Subject: Raise ArgumentError if route name is invalid [#6517 state:resolved] --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index fc86d52a3a..61053d4464 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -1,5 +1,6 @@ require 'rack/mount' require 'forwardable' +require 'active_support/core_ext/object/blank' require 'active_support/core_ext/object/to_query' require 'active_support/core_ext/hash/slice' @@ -330,6 +331,7 @@ module ActionDispatch end def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true) + raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i) route = Route.new(self, app, conditions, requirements, defaults, name, anchor) @set.add_route(*route) named_routes[name] = route if name -- cgit v1.2.3 From 31f09f9dbc1b8e598fc82d86b622167bfc01d18a Mon Sep 17 00:00:00 2001 From: Andrew White Date: Sun, 6 Mar 2011 12:49:44 +0000 Subject: Improve testing of cookies in functional tests: - cookies can be set using string or symbol keys - cookies are preserved across calls to get, post, etc. - cookie names and values are escaped - cookies can be cleared using @request.cookies.clear [#6272 state:resolved] --- actionpack/lib/action_dispatch/testing/test_process.rb | 2 +- actionpack/lib/action_dispatch/testing/test_request.rb | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb index 16f3674164..d430691429 100644 --- a/actionpack/lib/action_dispatch/testing/test_process.rb +++ b/actionpack/lib/action_dispatch/testing/test_process.rb @@ -22,7 +22,7 @@ module ActionDispatch end def cookies - HashWithIndifferentAccess.new(@request.cookies.merge(@response.cookies)) + @request.cookies.merge(@response.cookies).with_indifferent_access end def redirect_to_url diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb index cf440a1fad..822adb6a47 100644 --- a/actionpack/lib/action_dispatch/testing/test_request.rb +++ b/actionpack/lib/action_dispatch/testing/test_request.rb @@ -1,5 +1,6 @@ require 'active_support/core_ext/object/blank' require 'active_support/core_ext/hash/reverse_merge' +require 'rack/utils' module ActionDispatch class TestRequest < Request @@ -77,10 +78,14 @@ module ActionDispatch private def write_cookies! unless @cookies.blank? - @env['HTTP_COOKIE'] = @cookies.map { |name, value| "#{name}=#{value};" }.join(' ') + @env['HTTP_COOKIE'] = @cookies.map { |name, value| escape_cookie(name, value) }.join('; ') end end + def escape_cookie(name, value) + "#{Rack::Utils.escape(name)}=#{Rack::Utils.escape(value)}" + end + def delete_nil_values! @env.delete_if { |k, v| v.nil? } end -- cgit v1.2.3 From 0c777bace2aed1833e068358461de62bbd59cd0c Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 8 Mar 2011 16:18:27 -0800 Subject: stop being clever and just call methods on the Route object --- actionpack/lib/action_dispatch/routing/route.rb | 3 +++ actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route.rb b/actionpack/lib/action_dispatch/routing/route.rb index 08a8408f25..eae9d4ea6d 100644 --- a/actionpack/lib/action_dispatch/routing/route.rb +++ b/actionpack/lib/action_dispatch/routing/route.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/module/deprecation' + module ActionDispatch module Routing class Route #:nodoc: @@ -45,6 +47,7 @@ module ActionDispatch def to_a [@app, @conditions, @defaults, @name] end + deprecate :to_a def to_s @to_s ||= begin diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 61053d4464..b28f6c2297 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -333,7 +333,7 @@ module ActionDispatch def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true) raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i) route = Route.new(self, app, conditions, requirements, defaults, name, anchor) - @set.add_route(*route) + @set.add_route(route.app, route.conditions, route.defaults, route.name) named_routes[name] = route if name routes << route route -- cgit v1.2.3 From 03cbd9672cfc142842c95aae0fb27b8eb27e6990 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Wed, 9 Mar 2011 14:44:25 +0000 Subject: Filter params that return nil for to_param and allow through false values --- actionpack/lib/action_dispatch/http/url.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 535ff42b90..ac0fd9607d 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -41,7 +41,7 @@ module ActionDispatch path = options.delete(:path) || '' params = options[:params] || {} - params.reject! {|k,v| !v } + params.reject! {|k,v| v.to_param.nil? } rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) rewritten_url << "?#{params.to_query}" unless params.empty? -- cgit v1.2.3 From 68802d0fbe9d20ef8c5f6626d4b3279bd3a42d3e Mon Sep 17 00:00:00 2001 From: Prem Sichanugrist & Xavier Noria Date: Sat, 1 Jan 2011 23:51:05 +0700 Subject: Filter sensitive query string parameters in the log [#6244 state:committed] This provides more safety to applications that put secret information in the query string, such as API keys or SSO tokens. Signed-off-by: Xavier Noria --- .../lib/action_dispatch/http/filter_parameters.rb | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/http/filter_parameters.rb b/actionpack/lib/action_dispatch/http/filter_parameters.rb index 1ab48ae04d..8dd1af7f3d 100644 --- a/actionpack/lib/action_dispatch/http/filter_parameters.rb +++ b/actionpack/lib/action_dispatch/http/filter_parameters.rb @@ -5,10 +5,10 @@ require 'active_support/core_ext/object/duplicable' module ActionDispatch module Http # Allows you to specify sensitive parameters which will be replaced from - # the request log by looking in all subhashes of the param hash for keys - # to filter. If a block is given, each key and value of the parameter - # hash and all subhashes is passed to it, the value or key can be replaced - # using String#replace or similar method. + # the request log by looking in the query string of the request and all + # subhashes of the params hash to filter. If a block is given, each key and + # value of the params hash and all subhashes is passed to it, the value + # or key can be replaced using String#replace or similar method. # # Examples: # @@ -38,6 +38,11 @@ module ActionDispatch @filtered_env ||= env_filter.filter(@env) end + # Reconstructed a path with all sensitive GET parameters replaced. + def filtered_path + @filtered_path ||= query_string.empty? ? path : "#{path}?#{filtered_query_string}" + end + protected def parameter_filter @@ -52,6 +57,14 @@ module ActionDispatch @@parameter_filter_for[filters] ||= ParameterFilter.new(filters) end + KV_RE = '[^&;=]+' + PAIR_RE = %r{(#{KV_RE})=(#{KV_RE})} + def filtered_query_string + query_string.gsub(PAIR_RE) do |_| + parameter_filter.filter([[$1, $2]]).first.join("=") + end + end + end end end -- cgit v1.2.3 From 89c5b9aee7d7db95cec9e5a934c3761872ab107e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 11 Mar 2011 18:06:10 -0800 Subject: do not automatically add format to routes that end in a slash --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 1733c8032a..756a21dcac 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -107,7 +107,7 @@ module ActionDispatch if @options[:format] == false @options.delete(:format) path - elsif path.include?(":format") + elsif path.include?(":format") || path.end_with?('/') path else "#{path}(.:format)" -- cgit v1.2.3 From acd4bfb53764cfea0feaa367cfc8d00dbf9a87c3 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 11 Mar 2011 18:16:47 -0800 Subject: Just define methods directly on the class rather than use the module indirection. clever-- --- actionpack/lib/action_dispatch/routing/mapper.rb | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 756a21dcac..f67708722b 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -243,10 +243,6 @@ module ActionDispatch end module Base - def initialize(set) #:nodoc: - @set = set - end - # You can specify what Rails should route "/" to with the root method: # # root :to => 'pages#main' @@ -558,11 +554,6 @@ module ActionDispatch # PUT /admin/posts/1 # DELETE /admin/posts/1 module Scoping - def initialize(*args) #:nodoc: - @scope = {} - super - end - # Scopes a set of routes to the given default options. # # Take the following route definition as an example: @@ -956,11 +947,6 @@ module ActionDispatch alias :nested_scope :path end - def initialize(*args) #:nodoc: - super - @scope[:path_names] = @set.resources_path_names - end - def resources_path_names(options) @scope[:path_names].merge!(options) end @@ -1473,6 +1459,11 @@ module ActionDispatch end end + def initialize(set) #:nodoc: + @set = set + @scope = { :path_names => @set.resources_path_names } + end + include Base include HttpHelpers include Redirection -- cgit v1.2.3 From 833a90594e9fe25819c5111c853adc91eb6071c2 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 14 Mar 2011 15:15:40 -0700 Subject: RegexpWithNamedGroups is only used for path_info, so only apply to path info --- actionpack/lib/action_dispatch/routing/route.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/route.rb b/actionpack/lib/action_dispatch/routing/route.rb index eae9d4ea6d..0f90b2169d 100644 --- a/actionpack/lib/action_dispatch/routing/route.rb +++ b/actionpack/lib/action_dispatch/routing/route.rb @@ -23,7 +23,8 @@ module ActionDispatch conditions[:path_info] = ::Rack::Mount::Strexp.compile(path, requirements, SEPARATORS, anchor) end - @conditions = Hash[conditions.map { |k,v| [k, Rack::Mount::RegexpWithNamedGroups.new(v)] }] + @conditions = conditions.dup + @conditions[:path_info] = Rack::Mount::RegexpWithNamedGroups.new(@conditions[:path_info]) if @conditions[:path_info] @conditions.delete_if{ |k,v| k != :path_info && !valid_condition?(k) } @requirements.delete_if{ |k,v| !valid_condition?(k) } end -- cgit v1.2.3 From 9ba2d422f58e17b9e3d2a91d9979017aa36d13bd Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 14 Mar 2011 16:17:05 -0700 Subject: stop splatting arguments so that we can understand wtf is going on --- actionpack/lib/action_dispatch/routing/mapper.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f67708722b..e7b267da81 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -365,8 +365,9 @@ module ActionDispatch # # See Scoping#defaults for its scope equivalent. def match(path, options=nil) - mapping = Mapping.new(@set, @scope, path, options || {}).to_route - @set.add_route(*mapping) + mapping = Mapping.new(@set, @scope, path, options || {}) + app, conditions, requirements, defaults, as, anchor = mapping.to_route + @set.add_route(app, conditions, requirements, defaults, as, anchor) self end -- cgit v1.2.3 From 9f2706d770a2a5513d54dac9d0fb536f787a434b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 14 Mar 2011 18:26:30 -0700 Subject: use a list to represent the supported verbs for a route object --- actionpack/lib/action_dispatch/routing/mapper.rb | 4 ++-- actionpack/lib/action_dispatch/routing/route.rb | 20 +++++++++++--------- 2 files changed, 13 insertions(+), 11 deletions(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index e7b267da81..cc6b8aa82d 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -195,8 +195,8 @@ module ActionDispatch def request_method_condition if via = @options[:via] - via = Array(via).map { |m| m.to_s.dasherize.upcase } - { :request_method => %r[^#{via.join('|')}$] } + list = Array(via).map { |m| m.to_s.dasherize.upcase } + { :request_method => list } else { } end diff --git a/actionpack/lib/action_dispatch/routing/route.rb b/actionpack/lib/action_dispatch/routing/route.rb index 0f90b2169d..a049510182 100644 --- a/actionpack/lib/action_dispatch/routing/route.rb +++ b/actionpack/lib/action_dispatch/routing/route.rb @@ -12,6 +12,8 @@ module ActionDispatch @defaults = defaults @name = name + # FIXME: we should not be doing this much work in a constructor. + @requirements = requirements.merge(defaults) @requirements.delete(:controller) if @requirements[:controller].is_a?(Regexp) @requirements.delete_if { |k, v| @@ -23,22 +25,22 @@ module ActionDispatch conditions[:path_info] = ::Rack::Mount::Strexp.compile(path, requirements, SEPARATORS, anchor) end + @verbs = conditions[:request_method] || [] + @conditions = conditions.dup + + # Rack-Mount requires that :request_method be a regular expression. + # :request_method represents the HTTP verb that matches this route. + # + # Here we munge values before they get sent on to rack-mount. + @conditions[:request_method] = %r[^#{verb}$] unless @verbs.empty? @conditions[:path_info] = Rack::Mount::RegexpWithNamedGroups.new(@conditions[:path_info]) if @conditions[:path_info] @conditions.delete_if{ |k,v| k != :path_info && !valid_condition?(k) } @requirements.delete_if{ |k,v| !valid_condition?(k) } end def verb - if method = conditions[:request_method] - case method - when Regexp - source = method.source.upcase - source =~ /\A\^[-A-Z|]+\$\Z/ ? source[1..-2] : source - else - method.to_s.upcase - end - end + @verbs.join '|' end def segment_keys -- cgit v1.2.3 From 61781d84c11c8b5e37ad7cca5c40864759150a33 Mon Sep 17 00:00:00 2001 From: Gabriel Horner Date: Tue, 15 Mar 2011 09:23:17 -0400 Subject: doc :anchor option for #match in routes --- actionpack/lib/action_dispatch/routing/mapper.rb | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index f67708722b..64368ca28f 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -364,6 +364,13 @@ module ActionDispatch # match 'path' => 'c#a', :defaults => { :format => 'jpg' } # # See Scoping#defaults for its scope equivalent. + # + # [:anchor] + # Boolean to anchor a #match pattern. Default is true. When set to + # false, the pattern matches any request prefixed with the given path. + # + # # Matches any request starting with 'path' + # match 'path' => 'c#a', :anchor => false def match(path, options=nil) mapping = Mapping.new(@set, @scope, path, options || {}).to_route @set.add_route(*mapping) -- cgit v1.2.3 From 2ddfdba9a0dab7d8499c3ad0d13583bddbac4f69 Mon Sep 17 00:00:00 2001 From: Prem Sichanugrist Date: Tue, 22 Mar 2011 22:19:31 +0700 Subject: Do not show optional (.:format) block for wildcard route [#6605 state:resolved] This will make the output of `rake routes` to be correctly match to the behavior of the application, as the regular expression used to match the path is greedy and won't capture the format part by default --- actionpack/lib/action_dispatch/routing/mapper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'actionpack/lib/action_dispatch') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index cc6b8aa82d..1dba1d416c 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -107,7 +107,7 @@ module ActionDispatch if @options[:format] == false @options.delete(:format) path - elsif path.include?(":format") || path.end_with?('/') + elsif path.include?(":format") || path.end_with?('/') || path.match(/^\/?\*/) path else "#{path}(.:format)" -- cgit v1.2.3