Skip to content

Commit

Permalink
Add parameter defaults support to new routing DSL [#4265 state:resolved]
Browse files Browse the repository at this point in the history
Signed-off-by: wycats <wycats@gmail.com>
  • Loading branch information
pixeltrix authored and wycats committed Mar 27, 2010
1 parent b20a105 commit 3d746fc
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
20 changes: 19 additions & 1 deletion actionpack/lib/action_dispatch/routing/mapper.rb
Expand Up @@ -32,6 +32,8 @@ def call(env)
end

class Mapping
IGNORE_OPTIONS = [:to, :as, :controller, :action, :via, :on, :constraints, :defaults, :only, :except, :anchor]

def initialize(set, scope, args)
@set, @scope = set, scope
@path, @options = extract_path_and_options(args)
Expand Down Expand Up @@ -96,7 +98,15 @@ def requirements
end

def defaults
@defaults ||= if to.respond_to?(:call)
@defaults ||= (@options[:defaults] || {}).tap do |defaults|
defaults.merge!(default_controller_and_action)
defaults.reverse_merge!(@scope[:defaults]) if @scope[:defaults]
@options.each { |k, v| defaults[k] = v unless v.is_a?(Regexp) || IGNORE_OPTIONS.include?(k.to_sym) }
end
end

def default_controller_and_action
if to.respond_to?(:call)
{ }
else
defaults = case to
Expand Down Expand Up @@ -299,6 +309,10 @@ def constraints(constraints = {})
scope(:constraints => constraints) { yield }
end

def defaults(defaults = {})
scope(:defaults => defaults) { yield }
end

def match(*args)
options = args.extract_options!

Expand Down Expand Up @@ -343,6 +357,10 @@ def merge_constraints_scope(parent, child)
merge_options_scope(parent, child)
end

def merge_defaults_scope(parent, child)
merge_options_scope(parent, child)
end

def merge_blocks_scope(parent, child)
(parent || []) + [child]
end
Expand Down
20 changes: 20 additions & 0 deletions actionpack/test/dispatch/routing_test.rb
Expand Up @@ -121,6 +121,13 @@ def self.matches?(request)
# misc
match 'articles/:year/:month/:day/:title', :to => "articles#show", :as => :article

# default params
match 'inline_pages/(:id)', :to => 'pages#show', :id => 'home'
match 'default_pages/(:id)', :to => 'pages#show', :defaults => { :id => 'home' }
defaults :id => 'home' do
match 'scoped_pages/(:id)', :to => 'pages#show'
end

namespace :account do
match 'shorthand'
match 'description', :to => "account#description", :as => "description"
Expand Down Expand Up @@ -769,6 +776,19 @@ def test_nested_optional_scoped_path
end
end

def test_default_params
with_test_routes do
get '/inline_pages'
assert_equal 'home', @request.params[:id]

get '/default_pages'
assert_equal 'home', @request.params[:id]

get '/scoped_pages'
assert_equal 'home', @request.params[:id]
end
end

private
def with_test_routes
yield
Expand Down

0 comments on commit 3d746fc

Please sign in to comment.