Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/actionpack/lib/action_controller/polymorphic_routes.rb

Revision 9053, 5.9 kB (checked in by david, 6 months ago)

Fixed that polymorphic routes would modify the input array (closes #11363) [thomas.lee]

Line 
1 module ActionController
2   # Polymorphic URL helpers are methods for smart resolution to a named route call when
3   # given an ActiveRecord model instance. They are to be used in combination with
4   # ActionController::Resources.
5   #
6   # These methods are useful when you want to generate correct URL or path to a RESTful
7   # resource without having to know the exact type of the record in question.
8   #
9   # Nested resources and/or namespaces are also supported, as illustrated in the example:
10   #
11   #   polymorphic_url([:admin, @article, @comment])
12   #   #-> results in:
13   #   admin_article_comment_url(@article, @comment)
14   #
15   # == Usage within the framework
16   #
17   # Polymorphic URL helpers are used in a number of places throughout the Rails framework:
18   #
19   # * <tt>url_for</tt>, so you can use it with a record as the argument, e.g.
20   #   <tt>url_for(@article)</tt>;
21   # * ActionView::Helpers::FormHelper uses <tt>polymorphic_path</tt>, so you can write
22   #   <tt>form_for(@article)</tt> without having to specify :url parameter for the form
23   #   action;
24   # * <tt>redirect_to</tt> (which, in fact, uses <tt>url_for</tt>) so you can write
25   #   <tt>redirect_to(post)</tt> in your controllers;
26   # * ActionView::Helpers::AtomFeedHelper, so you don't have to explicitly specify URLs
27   #   for feed entries.
28   #
29   # == Prefixed polymorphic helpers
30   #
31   # In addition to <tt>polymorphic_url</tt> and <tt>polymorphic_path</tt> methods, a
32   # number of prefixed helpers are available as a shorthand to <tt>:action => "..."</tt>
33   # in options. Those are:
34   #
35   # * <tt>edit_polymorphic_url</tt>, <tt>edit_polymorphic_path</tt>
36   # * <tt>new_polymorphic_url</tt>, <tt>new_polymorphic_path</tt>
37   # * <tt>formatted_polymorphic_url</tt>, <tt>formatted_polymorphic_path</tt>
38   #
39   # Example usage:
40   #
41   #   edit_polymorphic_path(@post)
42   #   #=> /posts/1/edit
43   #
44   #   formatted_polymorphic_path([@post, :pdf])
45   #   #=> /posts/1.pdf
46   module PolymorphicRoutes
47     # Constructs a call to a named RESTful route for the given record and returns the
48     # resulting URL string. For example:
49     #
50     #   polymorphic_url(post)
51     #   # calls post_url(post) #=> "http://example.com/posts/1"
52     #
53     # ==== Options
54     # * <tt>:action</tt> -- specifies the action prefix for the named route:
55     #   <tt>:new</tt>, <tt>:edit</tt> or <tt>:formatted</tt>. Default is no prefix.
56     # * <tt>:routing_type</tt> -- <tt>:path</tt> or <tt>:url</tt> (default <tt>:url</tt>).
57     #
58     # ==== Examples
59     #
60     #   # an Article record
61     #   polymorphic_url(record)  #->  article_url(record)
62     #
63     #   # a Comment record
64     #   polymorphic_url(record)  #->  comment_url(record)
65     #
66     #   # it recognizes new records and maps to the collection
67     #   record = Comment.new
68     #   polymorphic_url(record)  #->  comments_url()
69     #
70     def polymorphic_url(record_or_hash_or_array, options = {})
71       if record_or_hash_or_array.kind_of?(Array)
72         record_or_hash_or_array = record_or_hash_or_array.dup
73       end
74
75       record    = extract_record(record_or_hash_or_array)
76       format    = (options[:action].to_s == "formatted" and record_or_hash_or_array.pop)
77       namespace = extract_namespace(record_or_hash_or_array)
78      
79       args = case record_or_hash_or_array
80         when Hash;  [ record_or_hash_or_array ]
81         when Array; record_or_hash_or_array.dup
82         else        [ record_or_hash_or_array ]
83       end
84
85       args << format if format
86
87       inflection =
88         case
89         when options[:action].to_s == "new"
90           args.pop
91           :singular
92         when record.respond_to?(:new_record?) && record.new_record?
93           args.pop
94           :plural
95         else
96           :singular
97         end
98      
99       named_route = build_named_route_call(record_or_hash_or_array, namespace, inflection, options)
100       send!(named_route, *args)
101     end
102
103     # Returns the path component of a URL for the given record. It uses
104     # <tt>polymorphic_url</tt> with <tt>:routing_type => :path</tt>.
105     def polymorphic_path(record_or_hash_or_array, options = {})
106       options[:routing_type] = :path
107       polymorphic_url(record_or_hash_or_array, options)
108     end
109
110     %w(edit new formatted).each do |action|
111       module_eval <<-EOT, __FILE__, __LINE__
112         def #{action}_polymorphic_url(record_or_hash)
113           polymorphic_url(record_or_hash, :action => "#{action}")
114         end
115
116         def #{action}_polymorphic_path(record_or_hash)
117           polymorphic_url(record_or_hash, :action => "#{action}", :routing_type => :path)
118         end
119       EOT
120     end
121
122     private
123       def action_prefix(options)
124         options[:action] ? "#{options[:action]}_" : ""
125       end
126
127       def routing_type(options)
128         options[:routing_type] || :url
129       end
130
131       def build_named_route_call(records, namespace, inflection, options = {})
132         unless records.is_a?(Array)
133           record = extract_record(records)
134           route  = ''
135         else
136           record = records.pop
137           route = records.inject("") do |string, parent|
138             string << "#{RecordIdentifier.send!("singular_class_name", parent)}_"
139           end
140         end
141
142         route << "#{RecordIdentifier.send!("#{inflection}_class_name", record)}_"
143
144         action_prefix(options) + namespace + route + routing_type(options).to_s
145       end
146
147       def extract_record(record_or_hash_or_array)
148         case record_or_hash_or_array
149           when Array; record_or_hash_or_array.last
150           when Hash;  record_or_hash_or_array[:id]
151           else        record_or_hash_or_array
152         end
153       end
154      
155       def extract_namespace(record_or_hash_or_array)
156         returning "" do |namespace|
157           if record_or_hash_or_array.is_a?(Array)
158             record_or_hash_or_array.delete_if do |record_or_namespace|
159               if record_or_namespace.is_a?(String) || record_or_namespace.is_a?(Symbol)
160                 namespace << "#{record_or_namespace}_"
161               end
162             end
163           end 
164         end
165       end
166   end
167 end
Note: See TracBrowser for help on using the browser.