| Module | Mack::Routes::Urls |
| In: |
lib/mack/routing/urls.rb
|
This module is the repository for named_routes. See Mack::Routes::RouteMap for more information.
# File lib/mack/routing/urls.rb, line 81
81: def self.create_method(n_route, route)
82: define_method("#{n_route}_url") do |*options|
83: options = *options
84: options = options.parse_splat_args if options.is_a?(Array)
85: options = {} if options.nil? || !options.is_a?(Hash)
86: url_for_pattern(route.path, (route.options.reject{|k,v| k.to_sym == :action || k.to_sym == :controller || k.to_sym == :method}).merge(options))
87: end
88:
89: define_method("#{n_route}_full_url") do |*options|
90: options = *options
91: options = {} if options.nil? || !options.is_a?(Hash)
92: if @request
93: options = {:host => @request.host, :scheme => @request.scheme, :port => @request.port}.merge(options)
94: end
95: self.send("#{n_route}_url", options)
96: end
97: end
Takes a url pattern and merges it with the options to hopefully produce a well formed url. Query string parameters will get escaped.
Example:
url_for_pattern("/:controller/:action/:id", {:controller => :blog, :action => :show, :id => 1})
# => "/blog/show/1
url_for_pattern("/:controller/:action/:id", {:controller => :blog, :action => :show})
# => "/blog/show/:id"
url_for_pattern("/blog/:id", {:id => 1})
# => "/blog/1
url_for_pattern("/blog/:id", {:id => 1, :n_id => 2})
# => "/blog/1?n_id=2
# File lib/mack/routing/urls.rb, line 18
18: def url_for_pattern(url, options = {})
19: u = url.dup
20: u = "/" if url.blank?
21: unused_params = []
22: format = nil
23: host_options = {:host => options[:host], :port => options[:port], :scheme => options[:scheme]}
24: options - [:host, :port, :scheme, :runner_block]
25: if host_options[:host]
26: hu = host_options[:host].dup
27: options.each_pair do |k, v|
28: vp = Rack::Utils.escape(v.to_param)
29: unless hu.gsub!(":#{k}", vp).nil?
30: options - [k.to_sym]
31: end
32: end
33: host_options[:host] = hu
34: end
35: options.each_pair do |k, v|
36: unless k.to_sym == :format
37: if u.match(/\*#{k}/)
38: vp = [v].flatten.collect {|c| Rack::Utils.escape(c.to_param)}
39: if u.gsub!("*#{k}", File.join(vp)).nil?
40: unused_params << "#{Rack::Utils.escape(k)}=#{vp}"
41: end
42: else
43: vp = Rack::Utils.escape(v.to_param)
44: if u.gsub!(":#{k}", vp).nil?
45: unused_params << "#{Rack::Utils.escape(k)}=#{vp}"
46: end
47: end
48: else
49: format = v
50: end
51: end
52: if format
53: u << ".#{format}"
54: end
55: unless unused_params.empty?
56: u << "?" << unused_params.sort.join("&")
57: end
58: File.join(build_full_host_from_options(host_options), u)
59: # u
60: end