Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 302 lines (280 sloc) 10.159 kB
ddfc072 Added AbstractController::Collector.
José Valim and Mikel Lindsaar authored
1 require 'abstract_controller/collector'
e5ab4b0 @jeremy Convert to class_attribute
jeremy authored
2 require 'active_support/core_ext/class/attribute'
ddfc072 Added AbstractController::Collector.
José Valim and Mikel Lindsaar authored
3
1c16649 @dhh Added better support for using the same actions to output for differe…
dhh authored
4 module ActionController #:nodoc:
5 module MimeResponds #:nodoc:
3e8ba61 @josevalim Refactor even more Responder. Move mime negotiation to request and ad…
josevalim authored
6 extend ActiveSupport::Concern
7
8 included do
e5ab4b0 @jeremy Convert to class_attribute
jeremy authored
9 class_attribute :responder, :mimes_for_respond_to
2e37eff @josevalim Unify class_inheritable_accessor and extlib_inheritable_accessor and …
josevalim authored
10 self.responder = ActionController::Responder
fa0cf66 @josevalim Add a couple more tests to respond_with.
josevalim authored
11 clear_respond_to
3e8ba61 @josevalim Refactor even more Responder. Move mime negotiation to request and ad…
josevalim authored
12 end
13
14 module ClassMethods
15 # Defines mimes that are rendered by default when invoking respond_with.
16 #
17 # Examples:
18 #
19 # respond_to :html, :xml, :json
20 #
21 # All actions on your controller will respond to :html, :xml and :json.
22 #
23 # But if you want to specify it based on your actions, you can use only and
24 # except:
25 #
26 # respond_to :html
27 # respond_to :xml, :json, :except => [ :edit ]
28 #
29 # The definition above explicits that all actions respond to :html. And all
30 # actions except :edit respond to :xml and :json.
31 #
32 # You can specify also only parameters:
33 #
34 # respond_to :rjs, :only => :create
35 #
36 def respond_to(*mimes)
37 options = mimes.extract_options!
38
39 only_actions = Array(options.delete(:only))
40 except_actions = Array(options.delete(:except))
41
e5ab4b0 @jeremy Convert to class_attribute
jeremy authored
42 new = mimes_for_respond_to.dup
3e8ba61 @josevalim Refactor even more Responder. Move mime negotiation to request and ad…
josevalim authored
43 mimes.each do |mime|
44 mime = mime.to_sym
e5ab4b0 @jeremy Convert to class_attribute
jeremy authored
45 new[mime] = {}
46 new[mime][:only] = only_actions unless only_actions.empty?
47 new[mime][:except] = except_actions unless except_actions.empty?
3e8ba61 @josevalim Refactor even more Responder. Move mime negotiation to request and ad…
josevalim authored
48 end
e5ab4b0 @jeremy Convert to class_attribute
jeremy authored
49 self.mimes_for_respond_to = new.freeze
3e8ba61 @josevalim Refactor even more Responder. Move mime negotiation to request and ad…
josevalim authored
50 end
51
52 # Clear all mimes in respond_to.
53 #
fa0cf66 @josevalim Add a couple more tests to respond_with.
josevalim authored
54 def clear_respond_to
e5ab4b0 @jeremy Convert to class_attribute
jeremy authored
55 self.mimes_for_respond_to = ActiveSupport::OrderedHash.new.freeze
3e8ba61 @josevalim Refactor even more Responder. Move mime negotiation to request and ad…
josevalim authored
56 end
57 end
3f445b3 @josevalim Refactor Responder to only calculate available mime types. Those are …
josevalim authored
58
01f032f Added responds_to to new base.
Yehuda Katz + Carl Lerche authored
59 # Without web-service support, an action which collects the data for displaying a list of people
60 # might look something like this:
61 #
62 # def index
63 # @people = Person.find(:all)
64 # end
65 #
66 # Here's the same action, with web-service support baked in:
67 #
68 # def index
69 # @people = Person.find(:all)
70 #
71 # respond_to do |format|
72 # format.html
73 # format.xml { render :xml => @people.to_xml }
74 # end
75 # end
76 #
77 # What that says is, "if the client wants HTML in response to this action, just respond as we
78 # would have before, but if the client wants XML, return them the list of people in XML format."
79 # (Rails determines the desired response format from the HTTP Accept header submitted by the client.)
80 #
81 # Supposing you have an action that adds a new person, optionally creating their company
82 # (by name) if it does not already exist, without web-services, it might look like this:
83 #
84 # def create
85 # @company = Company.find_or_create_by_name(params[:company][:name])
86 # @person = @company.people.create(params[:person])
87 #
88 # redirect_to(person_list_url)
89 # end
90 #
91 # Here's the same action, with web-service support baked in:
92 #
93 # def create
94 # company = params[:person].delete(:company)
95 # @company = Company.find_or_create_by_name(company[:name])
96 # @person = @company.people.create(params[:person])
97 #
98 # respond_to do |format|
99 # format.html { redirect_to(person_list_url) }
100 # format.js
101 # format.xml { render :xml => @person.to_xml(:include => @company) }
102 # end
103 # end
104 #
105 # If the client wants HTML, we just redirect them back to the person list. If they want Javascript
106 # (format.js), then it is an RJS request and we render the RJS template associated with this action.
107 # Lastly, if the client wants XML, we render the created person as XML, but with a twist: we also
108 # include the person's company in the rendered XML, so you get something like this:
109 #
110 # <person>
111 # <id>...</id>
112 # ...
113 # <company>
114 # <id>...</id>
115 # <name>...</name>
116 # ...
117 # </company>
118 # </person>
119 #
120 # Note, however, the extra bit at the top of that action:
121 #
122 # company = params[:person].delete(:company)
123 # @company = Company.find_or_create_by_name(company[:name])
124 #
125 # This is because the incoming XML document (if a web-service request is in process) can only contain a
126 # single root-node. So, we have to rearrange things so that the request looks like this (url-encoded):
127 #
128 # person[name]=...&person[company][name]=...&...
129 #
130 # And, like this (xml-encoded):
131 #
132 # <person>
133 # <name>...</name>
134 # <company>
135 # <name>...</name>
136 # </company>
137 # </person>
138 #
139 # In other words, we make the request so that it operates on a single entity's person. Then, in the action,
140 # we extract the company data from the request, find or create the company, and then create the new person
141 # with the remaining data.
142 #
143 # Note that you can define your own XML parameter parser which would allow you to describe multiple entities
144 # in a single request (i.e., by wrapping them all in a single root node), but if you just go with the flow
145 # and accept Rails' defaults, life will be much easier.
146 #
147 # If you need to use a MIME type which isn't supported by default, you can register your own handlers in
148 # environment.rb as follows.
149 #
150 # Mime::Type.register "image/jpg", :jpg
09de34c @josevalim Added respond_with.
josevalim authored
151 #
152 # Respond to also allows you to specify a common block for different formats by using any:
153 #
154 # def index
155 # @people = Person.find(:all)
156 #
157 # respond_to do |format|
158 # format.html
159 # format.any(:xml, :json) { render request.format.to_sym => @people }
160 # end
161 # end
162 #
163 # In the example above, if the format is xml, it will render:
164 #
165 # render :xml => @people
166 #
167 # Or if the format is json:
168 #
169 # render :json => @people
170 #
171 # Since this is a common pattern, you can use the class method respond_to
172 # with the respond_with method to have the same results:
173 #
174 # class PeopleController < ApplicationController
175 # respond_to :html, :xml, :json
176 #
177 # def index
178 # @people = Person.find(:all)
179 # respond_with(@person)
180 # end
181 # end
182 #
183 # Be sure to check respond_with and respond_to documentation for more examples.
184 #
3f445b3 @josevalim Refactor Responder to only calculate available mime types. Those are …
josevalim authored
185 def respond_to(*mimes, &block)
67b2d08 @josevalim Ensure that the proper accept header value is set during tests.
josevalim authored
186 raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
3f78de6 @josevalim Ensure that blocks are also handled inside the responder.
josevalim authored
187
188 if response = retrieve_response_from_mimes(mimes, &block)
189 response.call
190 end
09de34c @josevalim Added respond_with.
josevalim authored
191 end
672941d @jeremy Introduce a default respond_to block for custom types. Closes #8174.
jeremy authored
192
6e0ac74 @josevalim Renamed ActionController::Renderer to ActionController::Responder and…
josevalim authored
193 # respond_with wraps a resource around a responder for default representation.
1fd65c8 @josevalim Encapsulate respond_with behavior in a presenter.
josevalim authored
194 # First it invokes respond_to, if a response cannot be found (ie. no block
195 # for the request was given and template was not available), it instantiates
6e0ac74 @josevalim Renamed ActionController::Renderer to ActionController::Responder and…
josevalim authored
196 # an ActionController::Responder with the controller and resource.
5b7e81e @josevalim Allow respond_with to deal with http verb accordingly.
josevalim authored
197 #
1fd65c8 @josevalim Encapsulate respond_with behavior in a presenter.
josevalim authored
198 # ==== Example
5b7e81e @josevalim Allow respond_with to deal with http verb accordingly.
josevalim authored
199 #
1fd65c8 @josevalim Encapsulate respond_with behavior in a presenter.
josevalim authored
200 # def index
201 # @users = User.all
202 # respond_with(@users)
09de34c @josevalim Added respond_with.
josevalim authored
203 # end
204 #
1fd65c8 @josevalim Encapsulate respond_with behavior in a presenter.
josevalim authored
205 # It also accepts a block to be given. It's used to overwrite a default
206 # response:
f59984c @josevalim Add nagivational behavior to respond_with.
josevalim authored
207 #
208 # def destroy
1fd65c8 @josevalim Encapsulate respond_with behavior in a presenter.
josevalim authored
209 # @user = User.find(params[:id])
210 # flash[:notice] = "User was successfully created." if @user.save
5b7e81e @josevalim Allow respond_with to deal with http verb accordingly.
josevalim authored
211 #
1fd65c8 @josevalim Encapsulate respond_with behavior in a presenter.
josevalim authored
212 # respond_with(@user) do |format|
213 # format.html { render }
214 # end
7034272 @josevalim Add destroyed? to ActiveRecord, include tests for polymorphic urls fo…
josevalim authored
215 # end
216 #
6e0ac74 @josevalim Renamed ActionController::Renderer to ActionController::Responder and…
josevalim authored
217 # All options given to respond_with are sent to the underlying responder,
218 # except for the option :responder itself. Since the responder interface
aed135d @josevalim Renamed presenter to renderer, added some documentation and defined i…
josevalim authored
219 # is quite simple (it just needs to respond to call), you can even give
220 # a proc to it.
7034272 @josevalim Add destroyed? to ActiveRecord, include tests for polymorphic urls fo…
josevalim authored
221 #
4f9047e @josevalim Ensure collections are not treated as nested resources.
josevalim authored
222 def respond_with(*resources, &block)
d2e7c1b @josevalim Raise an error if respond_with is invoked and no format is declared.
josevalim authored
223 raise "In order to use respond_with, first you need to declare the formats your " <<
e5ab4b0 @jeremy Convert to class_attribute
jeremy authored
224 "controller responds to in the class level" if self.class.mimes_for_respond_to.empty?
d2e7c1b @josevalim Raise an error if respond_with is invoked and no format is declared.
josevalim authored
225
226 if response = retrieve_response_from_mimes(&block)
684a6b3 @josevalim Attempt to render the template inside the responder, so it can be use…
josevalim authored
227 options = resources.extract_options!
3f78de6 @josevalim Ensure that blocks are also handled inside the responder.
josevalim authored
228 options.merge!(:default_response => response)
e5ab4b0 @jeremy Convert to class_attribute
jeremy authored
229 (options.delete(:responder) || self.class.responder).call(self, resources, options)
684a6b3 @josevalim Attempt to render the template inside the responder, so it can be use…
josevalim authored
230 end
aed135d @josevalim Renamed presenter to renderer, added some documentation and defined i…
josevalim authored
231 end
7a4a679 @josevalim Remove any resource logic from respond_to.
josevalim authored
232
233 protected
234
09de34c @josevalim Added respond_with.
josevalim authored
235 # Collect mimes declared in the class method respond_to valid for the
236 # current action.
237 #
238 def collect_mimes_from_class_level #:nodoc:
239 action = action_name.to_sym
3e8ba61 @josevalim Refactor even more Responder. Move mime negotiation to request and ad…
josevalim authored
240
e5ab4b0 @jeremy Convert to class_attribute
jeremy authored
241 self.class.mimes_for_respond_to.keys.select do |mime|
242 config = self.class.mimes_for_respond_to[mime]
09de34c @josevalim Added respond_with.
josevalim authored
243
244 if config[:except]
245 !config[:except].include?(action)
246 elsif config[:only]
247 config[:only].include?(action)
248 else
249 true
3e8ba61 @josevalim Refactor even more Responder. Move mime negotiation to request and ad…
josevalim authored
250 end
251 end
09de34c @josevalim Added respond_with.
josevalim authored
252 end
3e8ba61 @josevalim Refactor even more Responder. Move mime negotiation to request and ad…
josevalim authored
253
3f78de6 @josevalim Ensure that blocks are also handled inside the responder.
josevalim authored
254 # Collects mimes and return the response for the negotiated format. Returns
255 # nil if :not_acceptable was sent to the client.
684a6b3 @josevalim Attempt to render the template inside the responder, so it can be use…
josevalim authored
256 #
d2e7c1b @josevalim Raise an error if respond_with is invoked and no format is declared.
josevalim authored
257 def retrieve_response_from_mimes(mimes=nil, &block)
3f78de6 @josevalim Ensure that blocks are also handled inside the responder.
josevalim authored
258 collector = Collector.new { default_render }
d2e7c1b @josevalim Raise an error if respond_with is invoked and no format is declared.
josevalim authored
259 mimes ||= collect_mimes_from_class_level
684a6b3 @josevalim Attempt to render the template inside the responder, so it can be use…
josevalim authored
260 mimes.each { |mime| collector.send(mime) }
3f78de6 @josevalim Ensure that blocks are also handled inside the responder.
josevalim authored
261 block.call(collector) if block_given?
684a6b3 @josevalim Attempt to render the template inside the responder, so it can be use…
josevalim authored
262
263 if format = request.negotiate_mime(collector.order)
f2c0a35 @josevalim Finish cleaning up rendering stack from views and move assigns evalua…
josevalim authored
264 self.content_type ||= format.to_s
a09e992 @josevalim Ensure details are frozen after @details_keys lookup. The implementat…
josevalim authored
265 lookup_context.freeze_formats([format.to_sym])
3f78de6 @josevalim Ensure that blocks are also handled inside the responder.
josevalim authored
266 collector.response_for(format)
684a6b3 @josevalim Attempt to render the template inside the responder, so it can be use…
josevalim authored
267 else
268 head :not_acceptable
3f78de6 @josevalim Ensure that blocks are also handled inside the responder.
josevalim authored
269 nil
684a6b3 @josevalim Attempt to render the template inside the responder, so it can be use…
josevalim authored
270 end
271 end
272
6e0ac74 @josevalim Renamed ActionController::Renderer to ActionController::Responder and…
josevalim authored
273 class Collector #:nodoc:
ddfc072 Added AbstractController::Collector.
José Valim and Mikel Lindsaar authored
274 include AbstractController::Collector
3e8ba61 @josevalim Refactor even more Responder. Move mime negotiation to request and ad…
josevalim authored
275 attr_accessor :order
3f445b3 @josevalim Refactor Responder to only calculate available mime types. Those are …
josevalim authored
276
3f78de6 @josevalim Ensure that blocks are also handled inside the responder.
josevalim authored
277 def initialize(&block)
278 @order, @responses, @default_response = [], {}, block
7af12d0 @dhh Added synonym and custom type handling to respond_to [DHH]
dhh authored
279 end
6480d49 @jamis Add MimeResponds::Responder#any for managing multiple types with iden…
jamis authored
280
281 def any(*args, &block)
011e469 @lifo Make MimeResponds::Responder#any work without explicit types. Closes …
lifo authored
282 if args.any?
283 args.each { |type| send(type, &block) }
284 else
3e8ba61 @josevalim Refactor even more Responder. Move mime negotiation to request and ad…
josevalim authored
285 custom(Mime::ALL, &block)
011e469 @lifo Make MimeResponds::Responder#any work without explicit types. Closes …
lifo authored
286 end
6dea52c @dhh Finish custom handling [DHH]
dhh authored
287 end
7e280c3 @josevalim Remove Mime::ALL from Mime::SET.
josevalim authored
288 alias :all :any
3f445b3 @josevalim Refactor Responder to only calculate available mime types. Those are …
josevalim authored
289
290 def custom(mime_type, &block)
291 mime_type = mime_type.is_a?(Mime::Type) ? mime_type : Mime::Type.lookup(mime_type.to_s)
292 @order << mime_type
293 @responses[mime_type] ||= block
6dc1288 @wycats Remove method missing use in respond_to
wycats authored
294 end
672941d @jeremy Introduce a default respond_to block for custom types. Closes #8174.
jeremy authored
295
3f445b3 @josevalim Refactor Responder to only calculate available mime types. Those are …
josevalim authored
296 def response_for(mime)
3f78de6 @josevalim Ensure that blocks are also handled inside the responder.
josevalim authored
297 @responses[mime] || @responses[Mime::ALL] || @default_response
3f445b3 @josevalim Refactor Responder to only calculate available mime types. Those are …
josevalim authored
298 end
1c16649 @dhh Added better support for using the same actions to output for differe…
dhh authored
299 end
300 end
0ee1cb2 @jeremy Ruby 1.9 compat, consistent load paths
jeremy authored
301 end
Something went wrong with that request. Please try again.