rails / rails

Ruby on Rails

This URL has Read+Write access

1c16649b » dhh 2006-03-10 Added better support for us... 1 require 'action_controller/mime_type'
db045dbb » dhh 2004-11-23 Initial 2 require 'action_controller/request'
3 require 'action_controller/response'
b1999be5 » dhh 2005-02-14 A hopefully more successful... 4 require 'action_controller/routing'
8e56f5ea » dhh 2005-06-24 Improved performance of Rou... 5 require 'action_controller/code_generation'
db045dbb » dhh 2004-11-23 Initial 6 require 'action_controller/url_rewriter'
df79e135 » dhh 2005-01-08 Added first stab at page an... 7 require 'drb'
22d9bad8 » jeremy 2005-10-20 Expose the session model ba... 8 require 'set'
db045dbb » dhh 2004-11-23 Initial 9
10 module ActionController #:nodoc:
11 class ActionControllerError < StandardError #:nodoc:
12 end
13 class SessionRestoreError < ActionControllerError #:nodoc:
14 end
15 class MissingTemplate < ActionControllerError #:nodoc:
16 end
8e56f5ea » dhh 2005-06-24 Improved performance of Rou... 17 class RoutingError < ActionControllerError #:nodoc:
b1999be5 » dhh 2005-02-14 A hopefully more successful... 18 attr_reader :failures
19 def initialize(message, failures=[])
20 super(message)
21 @failures = failures
22 end
23 end
24 class UnknownController < ActionControllerError #:nodoc:
25 end
db045dbb » dhh 2004-11-23 Initial 26 class UnknownAction < ActionControllerError #:nodoc:
27 end
250a570c » dhh 2005-01-01 Added class declaration for... 28 class MissingFile < ActionControllerError #:nodoc:
29 end
48fd667b » Marcel Molina 2005-10-15 Raise an exception if an at... 30 class SessionOverflowError < ActionControllerError #:nodoc:
31 DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.'
0abaf3a2 » jeremy 2005-11-08 CGI::Session::ActiveRecordS... 32
33 def initialize(message = nil)
34 super(message || DEFAULT_MESSAGE)
35 end
48fd667b » Marcel Molina 2005-10-15 Raise an exception if an at... 36 end
dab360e1 » dhh 2005-05-21 Added DoubleRenderError exc... 37 class DoubleRenderError < ActionControllerError #:nodoc:
82668678 » jamis 2005-07-09 Improved error message for ... 38 DEFAULT_MESSAGE = "Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and only once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirect_to(...) and return\". Finally, note that to cause a before filter to halt execution of the rest of the filter chain, the filter must return false, explicitly, so \"render(...) and return false\"."
39
0abaf3a2 » jeremy 2005-11-08 CGI::Session::ActiveRecordS... 40 def initialize(message = nil)
82668678 » jamis 2005-07-09 Improved error message for ... 41 super(message || DEFAULT_MESSAGE)
42 end
dab360e1 » dhh 2005-05-21 Added DoubleRenderError exc... 43 end
ea30f735 » dhh 2006-01-21 Raise a RedirectBackError i... 44 class RedirectBackError < ActionControllerError #:nodoc:
45 DEFAULT_MESSAGE = 'No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify @request.env["HTTP_REFERER"].'
46
47 def initialize(message = nil)
48 super(message || DEFAULT_MESSAGE)
49 end
50 end
db045dbb » dhh 2004-11-23 Initial 51
52 # Action Controllers are made up of one or more actions that performs its purpose and then either renders a template or
53 # redirects to another action. An action is defined as a public method on the controller, which will automatically be
54 # made accessible to the web-server through a mod_rewrite mapping. A sample controller could look like this:
55 #
56 # class GuestBookController < ActionController::Base
57 # def index
58 # @entries = Entry.find_all
59 # end
60 #
61 # def sign
1c057b72 » jamis 2005-10-16 Update/clean up AP document... 62 # Entry.create(params[:entry])
db045dbb » dhh 2004-11-23 Initial 63 # redirect_to :action => "index"
64 # end
65 # end
66 #
67 # GuestBookController.template_root = "templates/"
68 # GuestBookController.process_cgi
69 #
70 # All actions assume that you want to render a template matching the name of the action at the end of the performance
71 # unless you tell it otherwise. The index action complies with this assumption, so after populating the @entries instance
72 # variable, the GuestBookController will render "templates/guestbook/index.rhtml".
73 #
74 # Unlike index, the sign action isn't interested in rendering a template. So after performing its main purpose (creating a
75 # new entry in the guest book), it sheds the rendering assumption and initiates a redirect instead. This redirect works by
76 # returning an external "302 Moved" HTTP response that takes the user to the index action.
77 #
78 # The index and sign represent the two basic action archetypes used in Action Controllers. Get-and-show and do-and-redirect.
79 # Most actions are variations of these themes.
80 #
81 # Also note that it's the final call to <tt>process_cgi</tt> that actually initiates the action performance. It will extract
82 # request and response objects from the CGI
83 #
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 84 # When Action Pack is used inside of Rails, the template_root is automatically configured and you don't need to call process_cgi
85 # yourself.
86 #
db045dbb » dhh 2004-11-23 Initial 87 # == Requests
88 #
89 # Requests are processed by the Action Controller framework by extracting the value of the "action" key in the request parameters.
90 # This value should hold the name of the action to be performed. Once the action has been identified, the remaining
91 # request parameters, the session (if one is available), and the full request with all the http headers are made available to
92 # the action through instance variables. Then the action is performed.
93 #
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 94 # The full request object is available with the request accessor and is primarily used to query for http headers. These queries
95 # are made by accessing the environment hash, like this:
db045dbb » dhh 2004-11-23 Initial 96 #
97 # def hello_ip
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 98 # location = request.env["REMOTE_IP"]
1c057b72 » jamis 2005-10-16 Update/clean up AP document... 99 # render :text => "Hello stranger from #{location}"
db045dbb » dhh 2004-11-23 Initial 100 # end
101 #
102 # == Parameters
103 #
82f1e19e » dhh 2005-10-26 Fixed docs (closes #2468) 104 # All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params hash.
db045dbb » dhh 2004-11-23 Initial 105 # So an action that was performed through /weblog/list?category=All&limit=5 will include { "category" => "All", "limit" => 5 }
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 106 # in params.
db045dbb » dhh 2004-11-23 Initial 107 #
108 # It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
109 #
110 # <input type="text" name="post[name]" value="david">
111 # <input type="text" name="post[address]" value="hyacintvej">
112 #
e4efcfd4 » dhh 2005-02-23 Updated documentation 113 # A request stemming from a form holding these inputs will include <tt>{ "post" => { "name" => "david", "address" => "hyacintvej" } }</tt>.
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 114 # If the address input had been named "post[address][street]", the params would have included
e4efcfd4 » dhh 2005-02-23 Updated documentation 115 # <tt>{ "post" => { "address" => { "street" => "hyacintvej" } } }</tt>. There's no limit to the depth of the nesting.
db045dbb » dhh 2004-11-23 Initial 116 #
117 # == Sessions
118 #
119 # Sessions allows you to store objects in memory between requests. This is useful for objects that are not yet ready to be persisted,
120 # such as a Signup object constructed in a multi-paged process, or objects that don't change much and are needed all the time, such
121 # as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely
122 # they could be changed unknowingly. It's usually too much work to keep it all synchronized -- something databases already excel at.
123 #
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 124 # You can place objects in the session by using the <tt>session</tt> hash accessor:
db045dbb » dhh 2004-11-23 Initial 125 #
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 126 # session[:person] = Person.authenticate(user_name, password)
db045dbb » dhh 2004-11-23 Initial 127 #
128 # And retrieved again through the same hash:
129 #
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 130 # Hello #{session[:person]}
db045dbb » dhh 2004-11-23 Initial 131 #
132 # Any object can be placed in the session (as long as it can be Marshalled). But remember that 1000 active sessions each storing a
133 # 50kb object could lead to a 50MB memory overhead. In other words, think carefully about size and caching before resorting to the use
134 # of the session.
135 #
46c4fd41 » jamis 2005-09-01 ActionController documentat... 136 # For removing objects from the session, you can either assign a single key to nil, like <tt>session[:person] = nil</tt>, or you can
9c605227 » dhh 2005-03-20 Added a bit more to the ses... 137 # remove the entire session with reset_session.
138 #
db045dbb » dhh 2004-11-23 Initial 139 # == Responses
140 #
141 # Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response
142 # object is generated automatically through the use of renders and redirects, so it's normally nothing you'll need to be concerned about.
143 #
144 # == Renders
145 #
146 # Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering
147 # of a template. Included in the Action Pack is the Action View, which enables rendering of ERb templates. It's automatically configured.
148 # The controller passes objects to the view by assigning instance variables:
149 #
150 # def show
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 151 # @post = Post.find(params[:id])
db045dbb » dhh 2004-11-23 Initial 152 # end
153 #
154 # Which are then automatically available to the view:
155 #
156 # Title: <%= @post.title %>
157 #
158 # You don't have to rely on the automated rendering. Especially actions that could result in the rendering of different templates will use
159 # the manual rendering methods:
160 #
161 # def search
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 162 # @results = Search.find(params[:query])
db045dbb » dhh 2004-11-23 Initial 163 # case @results
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 164 # when 0 then render :action=> "no_results"
165 # when 1 then render :action=> "show"
166 # when 2..10 then render :action=> "show_many"
db045dbb » dhh 2004-11-23 Initial 167 # end
168 # end
169 #
170 # Read more about writing ERb and Builder templates in link:classes/ActionView/Base.html.
171 #
172 # == Redirects
173 #
174 # Redirecting is what actions that update the model do when they're done. The <tt>save_post</tt> method shouldn't be responsible for also
175 # showing the post once it's saved -- that's the job for <tt>show_post</tt>. So once <tt>save_post</tt> has completed its business, it'll
176 # redirect to <tt>show_post</tt>. All redirects are external, which means that when the user refreshes his browser, it's not going to save
177 # the post again, but rather just show it one more time.
178 #
179 # This sounds fairly simple, but the redirection is complicated by the quest for a phenomenon known as "pretty urls". Instead of accepting
82f1e19e » dhh 2005-10-26 Fixed docs (closes #2468) 180 # the dreadful being that is "weblog_controller?action=show&post_id=5", Action Controller goes out of its way to represent the former as
db045dbb » dhh 2004-11-23 Initial 181 # "/weblog/show/5". And this is even the simple case. As an example of a more advanced pretty url consider
182 # "/library/books/ISBN/0743536703/show", which can be mapped to books_controller?action=show&type=ISBN&id=0743536703.
183 #
184 # Redirects work by rewriting the URL of the current action. So if the show action was called by "/library/books/ISBN/0743536703/show",
185 # we can redirect to an edit action simply by doing <tt>redirect_to(:action => "edit")</tt>, which could throw the user to
e4efcfd4 » dhh 2005-02-23 Updated documentation 186 # "/library/books/ISBN/0743536703/edit". Naturally, you'll need to setup the routes configuration file to point to the proper controller
187 # and action in the first place, but once you have, it can be rewritten with ease.
db045dbb » dhh 2004-11-23 Initial 188 #
e4efcfd4 » dhh 2005-02-23 Updated documentation 189 # Let's consider a bunch of examples on how to go from "/clients/37signals/basecamp/project/dash" to somewhere else:
db045dbb » dhh 2004-11-23 Initial 190 #
e4efcfd4 » dhh 2005-02-23 Updated documentation 191 # redirect_to(:action => "edit") =>
192 # /clients/37signals/basecamp/project/dash
193 #
194 # redirect_to(:client_name => "nextangle", :project_name => "rails") =>
195 # /clients/nextangle/rails/project/dash
db045dbb » dhh 2004-11-23 Initial 196 #
e4efcfd4 » dhh 2005-02-23 Updated documentation 197 # Those redirects happen under the configuration of:
db045dbb » dhh 2004-11-23 Initial 198 #
e4efcfd4 » dhh 2005-02-23 Updated documentation 199 # map.connect 'clients/:client_name/:project_name/:controller/:action'
db045dbb » dhh 2004-11-23 Initial 200 #
2ee84cc6 » dhh 2005-01-20 Fixed that all redirect and... 201 # == Calling multiple redirects or renders
202 #
82f1e19e » dhh 2005-10-26 Fixed docs (closes #2468) 203 # An action should conclude with a single render or redirect. Attempting to try to do either again will result in a DoubleRenderError:
2ee84cc6 » dhh 2005-01-20 Fixed that all redirect and... 204 #
205 # def do_something
206 # redirect_to :action => "elsewhere"
14e7c7c2 » dhh 2005-07-09 Better documentation for Ca... 207 # render :action => "overthere" # raises DoubleRenderError
2ee84cc6 » dhh 2005-01-20 Fixed that all redirect and... 208 # end
209 #
14e7c7c2 » dhh 2005-07-09 Better documentation for Ca... 210 # If you need to redirect on the condition of something, then be sure to add "and return" to halt execution.
2ee84cc6 » dhh 2005-01-20 Fixed that all redirect and... 211 #
14e7c7c2 » dhh 2005-07-09 Better documentation for Ca... 212 # def do_something
213 # redirect_to(:action => "elsewhere") and return if monkeys.nil?
214 # render :action => "overthere" # won't be called unless monkeys is nil
46c4fd41 » jamis 2005-09-01 ActionController documentat... 215 # end
216 #
217 # == Environments
db045dbb » dhh 2004-11-23 Initial 218 #
219 # Action Controller works out of the box with CGI, FastCGI, and mod_ruby. CGI and mod_ruby controllers are triggered just the same using:
220 #
221 # WeblogController.process_cgi
222 #
223 # FastCGI controllers are triggered using:
224 #
225 # FCGI.each_cgi{ |cgi| WeblogController.process_cgi(cgi) }
226 class Base
227 DEFAULT_RENDER_STATUS_CODE = "200 OK"
1bce58b3 » seckar 2006-02-01 Add Reloadable::OnlySubclas... 228
5cbc062c » dhh 2006-02-04 Just go with Subclasses ins... 229 include Reloadable::Subclasses
1bce58b3 » seckar 2006-02-01 Add Reloadable::OnlySubclas... 230
db045dbb » dhh 2004-11-23 Initial 231 # Determines whether the view has access to controller internals @request, @response, @session, and @template.
232 # By default, it does.
233 @@view_controller_internals = true
234 cattr_accessor :view_controller_internals
235
b366dbd9 » dhh 2005-07-23 Improved performance with 5... 236 # Protected instance variable cache
237 @@protected_variables_cache = nil
238 cattr_accessor :protected_variables_cache
239
c971c248 » dhh 2005-05-05 Changed RAILS_ASSET_HOST to... 240 # Prepends all the URL-generating helpers from AssetHelper. This makes it possible to easily move javascripts, stylesheets,
241 # and images to a dedicated asset server away from the main web server. Example:
242 # ActionController::Base.asset_host = "http://assets.example.com"
243 @@asset_host = ""
244 cattr_accessor :asset_host
245
db045dbb » dhh 2004-11-23 Initial 246 # All requests are considered local by default, so everyone will be exposed to detailed debugging screens on errors.
247 # When the application is ready to go public, this should be set to false, and the protected method <tt>local_request?</tt>
248 # should instead be implemented in the controller to determine when debugging screens should be shown.
249 @@consider_all_requests_local = true
250 cattr_accessor :consider_all_requests_local
b1999be5 » dhh 2005-02-14 A hopefully more successful... 251
252 # Enable or disable the collection of failure information for RoutingErrors.
253 # This information can be extremely useful when tweaking custom routes, but is
254 # pointless once routes have been tested and verified.
255 @@debug_routes = true
256 cattr_accessor :debug_routes
db045dbb » dhh 2004-11-23 Initial 257
82f1e19e » dhh 2005-10-26 Fixed docs (closes #2468) 258 # Controls whether the application is thread-safe, so multi-threaded servers like WEBrick know whether to apply a mutex
0c3298f2 » dhh 2005-06-22 Added ActionController::Bas... 259 # around the performance of each action. Action Pack and Active Record are by default thread-safe, but many applications
260 # may not be. Turned off by default.
261 @@allow_concurrency = false
262 cattr_accessor :allow_concurrency
263
03d37a2d » Tobias Lütke 2006-03-05 Added new infrastructure su... 264 # Modern REST web services often need to submit complex data to the web application.
c450a36f » dhh 2006-03-05 Doc fixes 265 # The param_parsers hash lets you register handlers wich will process the http body and add parameters to the
03d37a2d » Tobias Lütke 2006-03-05 Added new infrastructure su... 266 # @params hash. These handlers are invoked for post and put requests.
267 #
dc4b5cff » dhh 2006-03-06 XmlSimple _should_ be the d... 268 # By default application/xml is enabled. A XmlSimple class with the same param name as the root
269 # will be instanciated in the @params. This allows XML requests to mask themselves as regular form submissions,
270 # so you can have one action serve both regular forms and web service requests.
03d37a2d » Tobias Lütke 2006-03-05 Added new infrastructure su... 271 #
dc4b5cff » dhh 2006-03-06 XmlSimple _should_ be the d... 272 # Example of doing your own parser for a custom content type:
03d37a2d » Tobias Lütke 2006-03-05 Added new infrastructure su... 273 #
274 # ActionController::Base.param_parsers['application/atom+xml'] = Proc.new do |data|
275 # node = REXML::Document.new(post)
276 # { node.root.name => node.root }
277 # end
278 #
dc4b5cff » dhh 2006-03-06 XmlSimple _should_ be the d... 279 # Note: Up until release 1.1 of Rails, Action Controller would default to using XmlSimple configured to discard the
280 # root node for such requests. The new default is to keep the root, such that "<r><name>David</name></r>" results
281 # in params[:r][:name] for "David" instead of params[:name]. To get the old behavior, you can
282 # re-register XmlSimple as application/xml handler and enable application/x-yaml like this:
03d37a2d » Tobias Lütke 2006-03-05 Added new infrastructure su... 283 #
dc4b5cff » dhh 2006-03-06 XmlSimple _should_ be the d... 284 # ActionController::Base.param_parsers['application/xml'] =
285 # Proc.new { |data| XmlSimple.xml_in(data, 'ForceArray' => false) }
0635f633 » Tobias Lütke 2006-03-05 ActionController::Base.para... 286 # ActionController::Base.param_parsers['application/x-yaml'] = :yaml
dc4b5cff » dhh 2006-03-06 XmlSimple _should_ be the d... 287 @@param_parsers = { 'application/xml' => :xml_simple }
03d37a2d » Tobias Lütke 2006-03-05 Added new infrastructure su... 288 cattr_accessor :param_parsers
289
db045dbb » dhh 2004-11-23 Initial 290 # Template root determines the base from which template references will be made. So a call to render("test/template")
291 # will be converted to "#{template_root}/test/template.rhtml".
12a75736 » dhh 2005-02-20 Added new keyword to specif... 292 class_inheritable_accessor :template_root
03d37a2d » Tobias Lütke 2006-03-05 Added new infrastructure su... 293
db045dbb » dhh 2004-11-23 Initial 294 # The logger is used for generating information on the action run-time (including benchmarking) if available.
295 # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
296 cattr_accessor :logger
297
298 # Determines which template class should be used by ActionController.
299 cattr_accessor :template_class
300
301 # Turn on +ignore_missing_templates+ if you want to unit test actions without making the associated templates.
302 cattr_accessor :ignore_missing_templates
303
304 # Holds the request object that's primarily used to get environment variables through access like
6ee06ebe » dhh 2005-04-16 Changed render_partial to t... 305 # <tt>request.env["REQUEST_URI"]</tt>.
db045dbb » dhh 2004-11-23 Initial 306 attr_accessor :request
307
46c4fd41 » jamis 2005-09-01 ActionController documentat... 308 # Holds a hash of all the GET, POST, and Url parameters passed to the action. Accessed like <tt>params["post_id"]</tt>
db045dbb » dhh 2004-11-23 Initial 309 # to get the post_id. No type casts are made, so all values are returned as strings.
310 attr_accessor :params
311
312 # Holds the response object that's primarily used to set additional HTTP headers through access like
6ee06ebe » dhh 2005-04-16 Changed render_partial to t... 313 # <tt>response.headers["Cache-Control"] = "no-cache"</tt>. Can also be used to access the final body HTML after a template
314 # has been rendered through response.body -- useful for <tt>after_filter</tt>s that wants to manipulate the output,
db045dbb » dhh 2004-11-23 Initial 315 # such as a OutputCompressionFilter.
316 attr_accessor :response
317
6ee06ebe » dhh 2005-04-16 Changed render_partial to t... 318 # Holds a hash of objects in the session. Accessed like <tt>session[:person]</tt> to get the object tied to the "person"
82f1e19e » dhh 2005-10-26 Fixed docs (closes #2468) 319 # key. The session will hold any type of object as values, but the key should be a string or symbol.
db045dbb » dhh 2004-11-23 Initial 320 attr_accessor :session
321
6ee06ebe » dhh 2005-04-16 Changed render_partial to t... 322 # Holds a hash of header names and values. Accessed like <tt>headers["Cache-Control"]</tt> to get the value of the Cache-Control
db045dbb » dhh 2004-11-23 Initial 323 # directive. Values should always be specified as strings.
324 attr_accessor :headers
325
326 # Holds the hash of variables that are passed on to the template class to be made available to the view. This hash
327 # is generated by taking a snapshot of all the instance variables in the current scope just before a template is rendered.
328 attr_accessor :assigns
329
c6f819ed » jeremy 2005-07-04 r2827@asus: jeremy | 2005... 330 # Returns the name of the action this controller is processing.
331 attr_accessor :action_name
03d37a2d » Tobias Lütke 2006-03-05 Added new infrastructure su... 332
db045dbb » dhh 2004-11-23 Initial 333 class << self
334 # Factory for the standard create, process loop where the controller is discarded after processing.
050c3964 » dhh 2006-02-11 Stopped the massive bleedin... 335 def process(request, response) #:nodoc:
336 new.process(request, response)
db045dbb » dhh 2004-11-23 Initial 337 end
0ffb6c16 » dhh 2004-12-06 Syntax errors and other exc... 338
db045dbb » dhh 2004-11-23 Initial 339 # Converts the class name from something like "OneModule::TwoModule::NeatController" to "NeatController".
340 def controller_class_name
d2b9e39c » jeremy 2005-07-04 r2828@asus: jeremy | 2005... 341 @controller_class_name ||= name.demodulize
db045dbb » dhh 2004-11-23 Initial 342 end
343
344 # Converts the class name from something like "OneModule::TwoModule::NeatController" to "neat".
345 def controller_name
d2b9e39c » jeremy 2005-07-04 r2828@asus: jeremy | 2005... 346 @controller_name ||= controller_class_name.sub(/Controller$/, '').underscore
db045dbb » dhh 2004-11-23 Initial 347 end
b1999be5 » dhh 2005-02-14 A hopefully more successful... 348
82f1e19e » dhh 2005-10-26 Fixed docs (closes #2468) 349 # Converts the class name from something like "OneModule::TwoModule::NeatController" to "one_module/two_module/neat".
b1999be5 » dhh 2005-02-14 A hopefully more successful... 350 def controller_path
d2b9e39c » jeremy 2005-07-04 r2828@asus: jeremy | 2005... 351 unless @controller_path
352 components = self.name.to_s.split('::')
353 components[-1] = $1 if /^(.*)Controller$/ =~ components.last
354 @controller_path = components.map { |name| name.underscore }.join('/')
355 end
13779431 » dhh 2006-02-11 The components module shoul... 356
d2b9e39c » jeremy 2005-07-04 r2828@asus: jeremy | 2005... 357 @controller_path
b1999be5 » dhh 2005-02-14 A hopefully more successful... 358 end
04b8bc1b » dhh 2005-02-17 Fixed that a bunch of metho... 359
360 # Return an array containing the names of public methods that have been marked hidden from the action processor.
361 # By default, all methods defined in ActionController::Base and included modules are hidden.
13779431 » dhh 2006-02-11 The components module shoul... 362 # More methods can be hidden using <tt>hide_actions</tt>.
04b8bc1b » dhh 2005-02-17 Fixed that a bunch of metho... 363 def hidden_actions
364 write_inheritable_attribute(:hidden_actions, ActionController::Base.public_instance_methods) unless read_inheritable_attribute(:hidden_actions)
365 read_inheritable_attribute(:hidden_actions)
366 end
367
368 # Hide each of the given methods from being callable as actions.
69f18a7a » dhh 2005-02-23 Keep the singular style, li... 369 def hide_action(*names)
13779431 » dhh 2006-02-11 The components module shoul... 370 write_inheritable_attribute(:hidden_actions, hidden_actions | names.collect { |n| n.to_s })
12a75736 » dhh 2005-02-20 Added new keyword to specif... 371 end
db045dbb » dhh 2004-11-23 Initial 372 end
373
76540822 » jeremy 2006-02-09 Major components cleanup an... 374 public
db045dbb » dhh 2004-11-23 Initial 375 # Extracts the action_name from the request parameters and performs that action.
0ffb6c16 » dhh 2004-12-06 Syntax errors and other exc... 376 def process(request, response, method = :perform_action, *arguments) #:nodoc:
db045dbb » dhh 2004-11-23 Initial 377 initialize_template_class(response)
378 assign_shortcuts(request, response)
379 initialize_current_url
050c3964 » dhh 2006-02-11 Stopped the massive bleedin... 380 action_name(:refresh)
381 forget_variables_added_to_assigns
382
383 log_processing
0ffb6c16 » dhh 2004-12-06 Syntax errors and other exc... 384 send(method, *arguments)
050c3964 » dhh 2006-02-11 Stopped the massive bleedin... 385
386 return response
ddf69109 » jeremy 2005-11-01 ensure close_session in AC:... 387 ensure
050c3964 » dhh 2006-02-11 Stopped the massive bleedin... 388 process_cleanup
db045dbb » dhh 2004-11-23 Initial 389 end
390
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 391 # Returns a URL that has been rewritten according to the options hash and the defined Routes.
392 # (For doing a complete redirect, use redirect_to).
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 393 #  
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 394 # <tt>url_for</tt> is used to:
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 395 #  
82f1e19e » dhh 2005-10-26 Fixed docs (closes #2468) 396 # All keys given to url_for are forwarded to the Route module, save for the following:
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 397 # * <tt>:anchor</tt> -- specifies the anchor name to be appended to the path. For example,
398 # <tt>url_for :controller => 'posts', :action => 'show', :id => 10, :anchor => 'comments'</tt>
399 # will produce "/posts/show/10#comments".
e4efcfd4 » dhh 2005-02-23 Updated documentation 400 # * <tt>:only_path</tt> -- if true, returns the absolute URL (omitting the protocol, host name, and port)
7a6a923f » dhh 2005-03-26 Added trailing_slash option... 401 # * <tt>:trailing_slash</tt> -- if true, adds a trailing slash, as in "/archive/2005/". Note that this
402 # is currently not recommended since it breaks caching.
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 403 # * <tt>:host</tt> -- overrides the default (current) host if provided
404 # * <tt>:protocol</tt> -- overrides the default (current) protocol if provided
e4efcfd4 » dhh 2005-02-23 Updated documentation 405 #
41ea6963 » dhh 2005-02-23 Added Base#render_to_string... 406 # The URL is generated from the remaining keys in the hash. A URL contains two key parts: the <base> and a query string.
407 # Routes composes a query string as the key/value pairs not included in the <base>.
e4efcfd4 » dhh 2005-02-23 Updated documentation 408 #
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 409 # The default Routes setup supports a typical Rails path of "controller/action/id" where action and id are optional, with
410 # action defaulting to 'index' when not given. Here are some typical url_for statements and their corresponding URLs:
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 411 #  
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 412 # url_for :controller => 'posts', :action => 'recent' # => 'proto://host.com/posts/recent'
413 # url_for :controller => 'posts', :action => 'index' # => 'proto://host.com/posts'
414 # url_for :controller => 'posts', :action => 'show', :id => 10 # => 'proto://host.com/posts/show/10'
e4efcfd4 » dhh 2005-02-23 Updated documentation 415 #
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 416 # When generating a new URL, missing values may be filled in from the current request's parameters. For example,
417 # <tt>url_for :action => 'some_action'</tt> will retain the current controller, as expected. This behavior extends to
418 # other parameters, including <tt>:controller</tt>, <tt>:id</tt>, and any other parameters that are placed into a Route's
419 # path.
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 420 #  
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 421 # The URL helpers such as <tt>url_for</tt> have a limited form of memory: when generating a new URL, they can look for
422 # missing values in the current request's parameters. Routes attempts to guess when a value should and should not be
423 # taken from the defaults. There are a few simple rules on how this is performed:
e4efcfd4 » dhh 2005-02-23 Updated documentation 424 #
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 425 # * If the controller name begins with a slash, no defaults are used: <tt>url_for :controller => '/home'</tt>
426 # * If the controller changes, the action will default to index unless provided
e4efcfd4 » dhh 2005-02-23 Updated documentation 427 #
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 428 # The final rule is applied while the URL is being generated and is best illustrated by an example. Let us consider the
429 # route given by <tt>map.connect 'people/:last/:first/:action', :action => 'bio', :controller => 'people'</tt>.
e4efcfd4 » dhh 2005-02-23 Updated documentation 430 #
82f1e19e » dhh 2005-10-26 Fixed docs (closes #2468) 431 # Suppose that the current URL is "people/hh/david/contacts". Let's consider a few different cases of URLs which are generated
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 432 # from this page.
e4efcfd4 » dhh 2005-02-23 Updated documentation 433 #
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 434 # * <tt>url_for :action => 'bio'</tt> -- During the generation of this URL, default values will be used for the first and
537efa36 » dhh 2005-04-30 Doc fix #1200 435 # last components, and the action shall change. The generated URL will be, "people/hh/david/bio".
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 436 # * <tt>url_for :first => 'davids-little-brother'</tt> This generates the URL 'people/hh/davids-little-brother' -- note
437 # that this URL leaves out the assumed action of 'bio'.
e4efcfd4 » dhh 2005-02-23 Updated documentation 438 #
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 439 # However, you might ask why the action from the current request, 'contacts', isn't carried over into the new URL. The
440 # answer has to do with the order in which the parameters appear in the generated path. In a nutshell, since the
441 # value that appears in the slot for <tt>:first</tt> is not equal to default value for <tt>:first</tt> we stop using
442 # defaults. On it's own, this rule can account for much of the typical Rails URL behavior.
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 443 #  
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 444 # Although a convienence, defaults can occasionaly get in your way. In some cases a default persists longer than desired.
445 # The default may be cleared by adding <tt>:name => nil</tt> to <tt>url_for</tt>'s options.
446 # This is often required when writing form helpers, since the defaults in play may vary greatly depending upon where the
447 # helper is used from. The following line will redirect to PostController's default action, regardless of the page it is
448 # displayed on:
db045dbb » dhh 2004-11-23 Initial 449 #
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 450 # url_for :controller => 'posts', :action => nil
451 #
c8e0e10e » dhh 2005-09-09 Added documentation for ove... 452 # If you explicitly want to create a URL that's almost the same as the current URL, you can do so using the
453 # :overwrite_params options. Say for your posts you have different views for showing and printing them.
454 # Then, in the show view, you get the URL for the print view like this
455 #
456 # url_for :overwrite_params => { :action => 'print' }
457 #
458 # This takes the current URL as is and only exchanges the action. In contrast, <tt>url_for :action => 'print'</tt>
82f1e19e » dhh 2005-10-26 Fixed docs (closes #2468) 459 # would have slashed-off the path components after the changed action.
db045dbb » dhh 2004-11-23 Initial 460 def url_for(options = {}, *parameters_for_method_reference) #:doc:
461 case options
462 when String then options
463 when Symbol then send(options, *parameters_for_method_reference)
464 when Hash then @url.rewrite(rewrite_options(options))
465 end
466 end
467
468 # Converts the class name from something like "OneModule::TwoModule::NeatController" to "NeatController".
469 def controller_class_name
470 self.class.controller_class_name
471 end
472
473 # Converts the class name from something like "OneModule::TwoModule::NeatController" to "neat".
474 def controller_name
475 self.class.controller_name
476 end
477
050c3964 » dhh 2006-02-11 Stopped the massive bleedin... 478 # Returns the name of the current action
479 def action_name(refresh = false)
480 if @action_name.nil? || refresh
481 @action_name = (params['action'] || 'index')
482 end
483
484 @action_name
485 end
486
bea737eb » sstephenson 2005-11-22 Make ActionController's ren... 487 def session_enabled?
488 request.session_options[:disabled] != false
489 end
490
db045dbb » dhh 2004-11-23 Initial 491 protected
5cd2f326 » jeremy 2005-11-13 Update documentation for re... 492 # Renders the content that will be returned to the browser as the response body.
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 493 #
494 # === Rendering an action
495 #
496 # Action rendering is the most common form and the type used automatically by Action Controller when nothing else is
497 # specified. By default, actions are rendered within the current layout (if one exists).
498 #
499 # # Renders the template for the action "goal" within the current controller
500 # render :action => "goal"
501 #
502 # # Renders the template for the action "short_goal" within the current controller,
503 # # but without the current active layout
504 # render :action => "short_goal", :layout => false
505 #
506 # # Renders the template for the action "long_goal" within the current controller,
507 # # but with a custom layout
1aab0e2c » dhh 2005-07-21 Doc fixes #1775, #1776 [jon... 508 # render :action => "long_goal", :layout => "spectacular"
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 509 #
510 # _Deprecation_ _notice_: This used to have the signatures <tt>render_action("action", status = 200)</tt>,
511 # <tt>render_without_layout("controller/action", status = 200)</tt>, and
512 # <tt>render_with_layout("controller/action", status = 200, layout)</tt>.
513 #
514 # === Rendering partials
515 #
82f1e19e » dhh 2005-10-26 Fixed docs (closes #2468) 516 # Partial rendering is most commonly used together with Ajax calls that only update one or a few elements on a page
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 517 # without reloading. Rendering of partials from the controller makes it possible to use the same partial template in
518 # both the full-page rendering (by calling it from within the template) and when sub-page updates happen (from the
519 # controller action responding to Ajax calls). By default, the current layout is not used.
520 #
521 # # Renders the partial located at app/views/controller/_win.r(html|xml)
522 # render :partial => "win"
523 #
524 # # Renders the partial with a status code of 500 (internal error)
525 # render :partial => "broken", :status => 500
526 #
527 # # Renders the same partial but also makes a local variable available to it
528 # render :partial => "win", :locals => { :name => "david" }
529 #
530 # # Renders a collection of the same partial by making each element of @wins available through
531 # # the local variable "win" as it builds the complete response
532 # render :partial => "win", :collection => @wins
533 #
534 # # Renders the same collection of partials, but also renders the win_divider partial in between
535 # # each win partial.
536 # render :partial => "win", :collection => @wins, :spacer_template => "win_divider"
537 #
538 # _Deprecation_ _notice_: This used to have the signatures
539 # <tt>render_partial(partial_path = default_template_name, object = nil, local_assigns = {})</tt> and
540 # <tt>render_partial_collection(partial_name, collection, partial_spacer_template = nil, local_assigns = {})</tt>.
541 #
f510b09c » dhh 2005-10-03 Made the documentation abou... 542 # === Rendering a template
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 543 #
f510b09c » dhh 2005-10-03 Made the documentation abou... 544 # Template rendering works just like action rendering except that it takes a path relative to the template root.
545 # The current layout is automatically applied.
fede0f57 » dhh 2005-07-11 Fixed documentation for :ac... 546 #
547 # # Renders the template located in [TEMPLATE_ROOT]/weblog/show.r(html|xml) (in Rails, app/views/weblog/show.rhtml)
f510b09c » dhh 2005-10-03 Made the documentation abou... 548 # render :template => "weblog/show"
549 #
550 # === Rendering a file
551 #
5cd2f326 » jeremy 2005-11-13 Update documentation for re... 552 # File rendering works just like action rendering except that it takes a filesystem path. By default, the path
553 # is assumed to be absolute, and the current layout is not applied.
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 554 #
5cd2f326 » jeremy 2005-11-13 Update documentation for re... 555 # # Renders the template located at the absolute filesystem path
556 # render :file => "/path/to/some/template.rhtml"
557 # render :file => "c:/path/to/some/template.rhtml"
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 558 #
5cd2f326 » jeremy 2005-11-13 Update documentation for re... 559 # # Renders a template within the current layout, and with a 404 status code
560 # render :file => "/path/to/some/template.rhtml", :layout => true, :status => 404
561 # render :file => "c:/path/to/some/template.rhtml", :layout => true, :status => 404
562 #
563 # # Renders a template relative to the template root and chooses the proper file extension
564 # render :file => "some/template", :use_full_path => true
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 565 #
566 # _Deprecation_ _notice_: This used to have the signature <tt>render_file(path, status = 200)</tt>
567 #
568 # === Rendering text
569 #
570 # Rendering of text is usually used for tests or for rendering prepared content, such as a cache. By default, text
571 # rendering is not done within the active layout.
572 #
573 # # Renders the clear text "hello world" with status code 200
574 # render :text => "hello world!"
575 #
576 # # Renders the clear text "Explosion!" with status code 500
577 # render :text => "Explosion!", :status => 500
578 #
579 # # Renders the clear text "Hi there!" within the current active layout (if one exists)
580 # render :text => "Explosion!", :layout => true
581 #
01cfd2b0 » dhh 2005-11-07 Fix docs (closes #2725) 582 # # Renders the clear text "Hi there!" within the layout
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 583 # # placed in "app/views/layouts/special.r(html|xml)"
584 # render :text => "Explosion!", :layout => "special"
585 #
586 # _Deprecation_ _notice_: This used to have the signature <tt>render_text("text", status = 200)</tt>
587 #
588 # === Rendering an inline template
589 #
590 # Rendering of an inline template works as a cross between text and action rendering where the source for the template
591 # is supplied inline, like text, but its interpreted with ERb or Builder, like action. By default, ERb is used for rendering
592 # and the current layout is not used.
593 #
594 # # Renders "hello, hello, hello, again"
595 # render :inline => "<%= 'hello, ' * 3 + 'again' %>"
596 #
597 # # Renders "<p>Good seeing you!</p>" using Builder
598 # render :inline => "xml.p { 'Good seeing you!' }", :type => :rxml
599 #
600 # # Renders "hello david"
601 # render :inline => "<%= 'hello ' + name %>", :locals => { :name => "david" }
602 #
603 # _Deprecation_ _notice_: This used to have the signature <tt>render_template(template, status = 200, type = :rhtml)</tt>
604 #
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 605 # === Rendering inline JavaScriptGenerator page updates
606 #
607 # In addition to rendering JavaScriptGenerator page updates with Ajax in RJS templates (see ActionView::Base for details),
608 # you can also pass the <tt>:update</tt> parameter to +render+, along with a block, to render page updates inline.
609 #
610 # render :update do |page|
611 # page.replace_html 'user_list', :partial => 'user', :collection => @users
612 # page.visual_effect :highlight, 'user_list'
613 # end
614 #
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 615 # === Rendering nothing
616 #
617 # Rendering nothing is often convenient in combination with Ajax calls that perform their effect client-side or
cb0f8fda » dhh 2005-07-12 Worked around a Safari bug ... 618 # when you just want to communicate a status code. Due to a bug in Safari, nothing actually means a single space.
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 619 #
620 # # Renders an empty response with status code 200
621 # render :nothing => true
622 #
623 # # Renders an empty response with status code 401 (access denied)
624 # render :nothing => true, :status => 401
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 625 def render(options = nil, deprecated_status = nil, &block) #:doc:
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 626 raise DoubleRenderError, "Can only render or redirect once per action" if performed?
da0c4c5c » dhh 2005-05-22 Deprecated all render_* met... 627
628 # Backwards compatibility
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 629 unless options.is_a?(Hash)
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 630 if options == :update
631 options = {:update => true}
632 else
633 return render_file(options || default_template_name, deprecated_status, true)
634 end
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 635 end
da0c4c5c » dhh 2005-05-22 Deprecated all render_* met... 636
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 637 if text = options[:text]
638 render_text(text, options[:status])
0367317d » dhh 2005-05-22 Deprecated redirect_to_path... 639
640 else
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 641 if file = options[:file]
bea737eb » sstephenson 2005-11-22 Make ActionController's ren... 642 render_file(file, options[:status], options[:use_full_path], options[:locals] || {})
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 643
644 elsif template = options[:template]
645 render_file(template, options[:status], true)
646
647 elsif inline = options[:inline]
43b6a74f » dhh 2005-10-13 Added :locals support for r... 648 render_template(inline, options[:status], options[:type], options[:locals] || {})
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 649
650 elsif action_name = options[:action]
651 render_action(action_name, options[:status], options[:layout])
1c16649b » dhh 2006-03-10 Added better support for us... 652
653 elsif xml = options[:xml]
654 render_xml(xml, options[:status])
655
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 656 elsif partial = options[:partial]
657 partial = default_template_name if partial == true
658 if collection = options[:collection]
659 render_partial_collection(partial, collection, options[:spacer_template], options[:locals], options[:status])
660 else
e3c02d8c » dhh 2005-09-09 Fixed that render :partial ... 661 render_partial(partial, ActionView::Base::ObjectWrapper.new(options[:object]), options[:locals], options[:status])
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 662 end
663
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 664 elsif options[:update]
d2adec43 » seckar 2006-01-29 Ensure assigns are copied t... 665 add_variables_to_assigns
666 @template.send :evaluate_assigns
667
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 668 generator = ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.new(@template, &block)
669 render_javascript(generator.to_s)
670
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 671 elsif options[:nothing]
672 # Safari doesn't pass the headers of the return if the response is zero length
673 render_text(" ", options[:status])
674
675 else
676 render_file(default_template_name, options[:status], true)
677
678 end
0367317d » dhh 2005-05-22 Deprecated redirect_to_path... 679 end
680 end
db045dbb » dhh 2004-11-23 Initial 681
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 682 # Renders according to the same rules as <tt>render</tt>, but returns the result in a string instead
683 # of sending it as the response body to the browser.
f9937dd0 » sstephenson 2006-01-20 Pass along blocks from rend... 684 def render_to_string(options = nil, &block) #:doc:
685 result = render(options, &block)
050c3964 » dhh 2006-02-11 Stopped the massive bleedin... 686
da0c4c5c » dhh 2005-05-22 Deprecated all render_* met... 687 erase_render_results
050c3964 » dhh 2006-02-11 Stopped the massive bleedin... 688 forget_variables_added_to_assigns
689 reset_variables_added_to_assigns
690
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 691 result
692 end
693
694 def render_action(action_name, status = nil, with_layout = true)
8896efd4 » dhh 2006-02-18 Ensure backwards compatibil... 695 template = default_template_name(action_name.to_s)
62fe5bbf » Marcel Molina 2005-11-18 Make rjs templates always i... 696 if with_layout && !template_exempt_from_layout?(template)
697 render_with_layout(template, status)
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 698 else
62fe5bbf » Marcel Molina 2005-11-18 Make rjs templates always i... 699 render_without_layout(template, status)
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 700 end
701 end
702
bea737eb » sstephenson 2005-11-22 Make ActionController's ren... 703 def render_file(template_path, status = nil, use_full_path = false, locals = {})
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 704 add_variables_to_assigns
705 assert_existance_of_template_file(template_path) if use_full_path
d87618d2 » dhh 2005-09-28 Log request method and resp... 706 logger.info("Rendering #{template_path}" + (status ? " (#{status})" : '')) if logger
bea737eb » sstephenson 2005-11-22 Make ActionController's ren... 707 render_text(@template.render_file(template_path, use_full_path, locals), status)
41ea6963 » dhh 2005-02-23 Added Base#render_to_string... 708 end
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 709
43b6a74f » dhh 2005-10-13 Added :locals support for r... 710 def render_template(template, status = nil, type = :rhtml, local_assigns = {})
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 711 add_variables_to_assigns
43b6a74f » dhh 2005-10-13 Added :locals support for r... 712 render_text(@template.render_template(type, template, nil, local_assigns), status)
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 713 end
714
715 def render_text(text = nil, status = nil)
716 @performed_render = true
717 @response.headers['Status'] = (status || DEFAULT_RENDER_STATUS_CODE).to_s
718 @response.body = text
719 end
720
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 721 def render_javascript(javascript, status = nil)
1c16649b » dhh 2006-03-10 Added better support for us... 722 @response.headers['Content-Type'] = 'text/javascript; charset=UTF-8'
06dd1f2c » sstephenson 2006-01-20 Add render :update for inli... 723 render_text(javascript, status)
724 end
725
1c16649b » dhh 2006-03-10 Added better support for us... 726 def render_xml(xml, status = nil)
727 @response.headers['Content-Type'] = 'text/xml; charset=UTF-8'
728 render_text(xml, status)
729 end
730
4f40b2d8 » dhh 2005-07-24 Improved performance of tes... 731 def render_nothing(status = nil)
732 render_text(' ', status)
733 end
734
735 def render_partial(partial_path = default_template_name, object = nil, local_assigns = nil, status = nil)
736 add_variables_to_assigns
737 render_text(@template.render_partial(partial_path, object, local_assigns), status)
738 end
739
740 def render_partial_collection(partial_name, collection, partial_spacer_template = nil, local_assigns = nil, status = nil)
741 add_variables_to_assigns
742 render_text(@template.render_partial_collection(partial_name, collection, partial_spacer_template, local_assigns), status)
743 end
744
745 def render_with_layout(template_name = default_template_name, status = nil, layout = nil)
746 render_with_a_layout(template_name, status, layout)
747 end
748
749 def render_without_layout(template_name = default_template_name, status = nil)
750 render_with_no_layout(template_name, status)
751 end
752
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 753
62ed6950 » dhh 2005-06-28 Added support for upload pr... 754 # Clears the rendered results, allowing for another render to be performed.
e9cfe955 » dhh 2005-07-25 Add a catch-all eraser 755 def erase_render_results
dab360e1 » dhh 2005-05-21 Added DoubleRenderError exc... 756 @response.body = nil
757 @performed_render = false
758 end
9c52a412 » sstephenson 2006-01-23 Add the ability to call Jav... 759
760
82f1e19e » dhh 2005-10-26 Fixed docs (closes #2468) 761 # Clears the redirected results from the headers, resets the status to 200 and returns
62ed6950 » dhh 2005-06-28 Added support for upload pr... 762 # the URL that was used to redirect or nil if there was no redirected URL
763 # Note that +redirect_to+ will change the body of the response to indicate a redirection.
764 # The response body is not reset here, see +erase_render_results+
e9cfe955 » dhh 2005-07-25 Add a catch-all eraser 765 def erase_redirect_results
62ed6950 » dhh 2005-06-28 Added support for upload pr... 766 @performed_redirect = false
767 response.redirected_to = nil
768 response.redirected_to_method_params = nil
769 response.headers['Status'] = DEFAULT_RENDER_STATUS_CODE
770 response.headers.delete('location')
771 end
772
e9cfe955 » dhh 2005-07-25 Add a catch-all eraser 773 # Erase both render and redirect results
774 def erase_results
775 erase_render_results
776 erase_redirect_results
777 end
93ec99c2 » dhh 2005-07-06 Partly tuned docs for relea... 778
db045dbb » dhh 2004-11-23 Initial 779 def rewrite_options(options)
780 if defaults = default_url_options(options)
781 defaults.merge(options)
782 else
783 options
784 end
785 end
786
787 # Overwrite to implement a number of default options that all url_for-based methods will use. The default options should come in
788 # the form of a hash, just like the one you would use for url_for directly. Example:
789 #
790 # def default_url_options(options)
5c4f1859 » dhh 2005-02-23 Fixed that send_file/data c... 791 # { :project => @project.active? ? @project.url_name : "unknown" }
db045dbb » dhh 2004-11-23 Initial 792 # end
793 #
794 # As you can infer from the example, this is mostly useful for situations where you want to centralize dynamic decisions about the
795 # urls as they stem from the business domain. Please note that any individual url_for call can always override the defaults set
796 # by this method.
797 def default_url_options(options) #:doc:
798 end
799
0367317d » dhh 2005-05-22 Deprecated redirect_to_path... 800 # Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
801 #
802 # * <tt>Hash</tt>: The URL will be generated by calling url_for with the +options+.
803 # * <tt>String starting with protocol:// (like http://)</tt>: Is passed straight through as the target for redirection.
01cfd2b0 » dhh 2005-11-07 Fix docs (closes #2725) 804 # * <tt>String not containing a protocol</tt>: The current protocol and host is prepended to the string.
4f754985 » dhh 2005-11-02 Added redirect_to :back as ... 805 # * <tt>:back</tt>: Back to the page that issued the request. Useful for forms that are triggered from multiple places.
806 # Short-hand for redirect_to(request.env["HTTP_REFERER"])
0367317d » dhh 2005-05-22 Deprecated redirect_to_path... 807 #
808 # Examples:
809 # redirect_to :action => "show", :id => 5
810 # redirect_to "http://www.rubyonrails.org"
811 # redirect_to "/images/screenshot.jpg"
4f754985 » dhh 2005-11-02 Added redirect_to :back as ... 812 # redirect_to :back
0367317d » dhh 2005-05-22 Deprecated redirect_to_path... 813 #
814 # The redirection happens as a "302 Moved" header.
db045dbb » dhh 2004-11-23 Initial 815 def redirect_to(options = {}, *parameters_for_method_reference) #:doc:
0367317d » dhh 2005-05-22 Deprecated redirect_to_path... 816 case options
817 when %r{^\w+://.*}
82668678 » jamis 2005-07-09 Improved error message for ... 818 raise DoubleRenderError if performed?
76540822 » jeremy 2006-02-09 Major components cleanup an... 819 logger.info("Redirected to #{options}") if logger
060ecf1a » dhh 2005-05-22 Set redirected_to proper 820 response.redirect(options)
821 response.redirected_to = options
0367317d » dhh 2005-05-22 Deprecated redirect_to_path... 822 @performed_redirect = true
823
824 when String
825 redirect_to(request.protocol + request.host_with_port + options)
4f754985 » dhh 2005-11-02 Added redirect_to :back as ... 826
827 when :back
ea30f735 » dhh 2006-01-21 Raise a RedirectBackError i... 828 request.env["HTTP_REFERER"] ? redirect_to(request.env["HTTP_REFERER"]) : raise(RedirectBackError)
0367317d » dhh 2005-05-22 Deprecated redirect_to_path... 829
830 else
831 if parameters_for_method_reference.empty?
832 redirect_to(url_for(options))
060ecf1a » dhh 2005-05-22 Set redirected_to proper 833 response.redirected_to = options
0367317d » dhh 2005-05-22 Deprecated redirect_to_path... 834 else
835 redirect_to(url_for(options, *parameters_for_method_reference))
060ecf1a » dhh 2005-05-22 Set redirected_to proper 836 response.redirected_to, response.redirected_to_method_params = options, parameters_for_method_reference
0367317d » dhh 2005-05-22 Deprecated redirect_to_path... 837 end
db045dbb » dhh 2004-11-23 Initial 838 end
839 end
d2d38f67 » dhh 2005-07-17 Added Base#expires_in(secon... 840
841 # Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a "private" instruction, so that
842 # intermediate caches shouldn't cache the response.
843 #
844 # Examples:
845 # expires_in 20.minutes
846 # expires_in 3.hours, :private => false
847 # expires in 3.hours, 'max-stale' => 5.hours, :private => nil, :public => true
848 #
849 # This method will overwrite an existing Cache-Control header.
850 # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities.
d1725929 » dhh 2005-07-23 Added test for template to ... 851 def expires_in(seconds, options = {}) #:doc:
d2d38f67 » dhh 2005-07-17 Added Base#expires_in(secon... 852 cache_options = { 'max-age' => seconds, 'private' => true }.symbolize_keys.merge!(options.symbolize_keys)
853 cache_options.delete_if { |k,v| v.nil? or v == false }
854 cache_control = cache_options.map{ |k,v| v == true ? k.to_s : "#{k.to_s}=#{v.to_s}"}
855 @response.headers["Cache-Control"] = cache_control.join(', ')
856 end
857
858 # Sets a HTTP 1.1 Cache-Control header of "no-cache" so no caching should occur by the browser or
859 # intermediate caches (like caching proxy servers).
d1725929 » dhh 2005-07-23 Added test for template to ... 860 def expires_now #:doc:
d2d38f67 » dhh 2005-07-17 Added Base#expires_in(secon... 861 @response.headers["Cache-Control"] = "no-cache"
862 end
db045dbb » dhh 2004-11-23 Initial 863
098fa943 » dhh 2005-02-07 Fixed documentation snafus ... 864 # Resets the session by clearing out all the objects stored within and initializing a new session object.
db045dbb » dhh 2004-11-23 Initial 865 def reset_session #:doc:
866 @request.reset_session
867 @session = @request.session
868 @response.session = @session
869 end
870
871 private
bf92aacf » seckar 2005-09-08 Avoid extending view instan... 872 def self.view_class
873 unless @view_class
874 # create a new class based on the default template class and include helper methods
875 @view_class = Class.new(ActionView::Base)
876 @view_class.send(:include, master_helper_module)
db045dbb » dhh 2004-11-23 Initial 877 end
bf92aacf » seckar 2005-09-08 Avoid extending view instan... 878 @view_class
879 end
880
881 def self.view_root
882 @view_root ||= template_root
883 end
884
885 def initialize_template_class(response)
886 raise "You must assign a template class through ActionController.template_class= before processing a request" unless @@template_class
db045dbb » dhh 2004-11-23 Initial 887
bf92aacf » seckar 2005-09-08 Avoid extending view instan... 888 response.template = self.class.view_class.new(self.class.view_root, {}, self)
02594910 » Scott Barron 2005-10-30 Fix problem where redirecti... 889 response.redirected_to = nil
db045dbb » dhh 2004-11-23 Initial 890 @performed_render = @performed_redirect = false
891 end
892
893 def assign_shortcuts(request, response)
894 @request, @params, @cookies = request, request.parameters, request.cookies
895
896 @response = response
897 @response.session = request.session
898
899 @session = @response.session
900 @template = @response.template
76540822 » jeremy 2006-02-09 Major components cleanup an... 901 @assigns = @response.template.assigns
902
db045dbb » dhh 2004-11-23 Initial 903 @headers = @response.headers
904 end
905
906 def initialize_current_url
b1999be5 » dhh 2005-02-14 A hopefully more successful... 907 @url = UrlRewriter.new(@request, @params.clone())
db045dbb » dhh 2004-11-23 Initial 908 end
909
910 def log_processing
050c3964 » dhh 2006-02-11 Stopped the massive bleedin... 911 if logger
912 logger.info "\n\nProcessing #{controller_class_name}\##{action_name} (for #{request_origin}) [#{request.method.to_s.upcase}]"
913 logger.info " Session ID: #{@session.session_id}" if @session and @session.respond_to?(:session_id)
914 logger.info " Parameters: #{@params.inspect}"
915 end
db045dbb » dhh 2004-11-23 Initial 916 end
917
918 def perform_action
b366dbd9 » dhh 2005-07-23 Improved performance with 5... 919 if self.class.action_methods.include?(action_name) || self.class.action_methods.include?('method_missing')
db045dbb » dhh 2004-11-23 Initial 920 send(action_name)
2ee84cc6 » dhh 2005-01-20 Fixed that all redirect and... 921 render unless performed?
db045dbb » dhh 2004-11-23 Initial 922 elsif template_exists? && template_public?
923 render
924 else
925 raise UnknownAction, "No action responded to #{action_name}", caller
926 end
927 end
2ee84cc6 » dhh 2005-01-20 Fixed that all redirect and... 928
929 def performed?
930 @performed_render || @performed_redirect
931 end
db045dbb » dhh 2004-11-23 Initial 932
933 def action_methods
b366dbd9 » dhh 2005-07-23 Improved performance with 5... 934 self.class.action_methods
db045dbb » dhh 2004-11-23 Initial 935 end
da0c4c5c » dhh 2005-05-22 Deprecated all render_* met... 936
b366dbd9 » dhh 2005-07-23 Improved performance with 5... 937 def self.action_methods
22d9bad8 » jeremy 2005-10-20 Expose the session model ba... 938 @action_methods ||= Set.new(public_instance_methods - hidden_actions)
b366dbd9 » dhh 2005-07-23 Improved performance with 5... 939 end
da0c4c5c » dhh 2005-05-22 Deprecated all render_* met... 940
db045dbb » dhh 2004-11-23 Initial 941 def add_variables_to_assigns
b366dbd9 » dhh 2005-07-23 Improved performance with 5... 942 unless @variables_added
943 add_instance_variables_to_assigns
944 add_class_variables_to_assigns if view_controller_internals
945 @variables_added = true
946 end
db045dbb » dhh 2004-11-23 Initial 947 end
050c3964 » dhh 2006-02-11 Stopped the massive bleedin... 948
949 def forget_variables_added_to_assigns
950 @variables_added = nil
951 end
952
953 def reset_variables_added_to_assigns
954 @template.instance_variable_set("@assigns_added", nil)
955 end
db045dbb » dhh 2004-11-23 Initial 956
957 def add_instance_variables_to_assigns
b366dbd9 » dhh 2005-07-23 Improved performance with 5... 958 @@protected_variables_cache ||= protected_instance_variables.inject({}) { |h, k| h[k] = true; h }
db045dbb » dhh 2004-11-23 Initial 959 instance_variables.each do |var|
fa158ff0 » jeremy 2005-07-04 r2829@asus: jeremy | 2005... 960 next if @@protected_variables_cache.include?(var)
db045dbb » dhh 2004-11-23 Initial 961 @assigns[var[1..-1]] = instance_variable_get(var)
962 end
963 end
964
965 def add_class_variables_to_assigns
966 %w( template_root logger template_class ignore_missing_templates ).each do |cvar|
967 @assigns[cvar] = self.send(cvar)
968 end
969 end
970
971 def protected_instance_variables
972 if view_controller_internals
973 [ "@assigns", "@performed_redirect", "@performed_render" ]
974 else
76540822 » jeremy 2006-02-09 Major components cleanup an... 975 [ "@assigns", "@performed_redirect", "@performed_render", "@request", "@response", "@session", "@cookies", "@template", "@request_origin", "@parent_controller" ]
db045dbb » dhh 2004-11-23 Initial 976 end
977 end
978
979 def request_origin
76540822 » jeremy 2006-02-09 Major components cleanup an... 980 # this *needs* to be cached!
981 # otherwise you'd get different results if calling it more than once
982 @request_origin ||= "#{@request.remote_ip} at #{Time.now.to_s(:db)}"
db045dbb » dhh 2004-11-23 Initial 983 end
984
977b4be2 » dhh 2005-07-05 Changed logging of SQL stat... 985 def complete_request_uri
76540822 » jeremy 2006-02-09 Major components cleanup an... 986 "#{@request.protocol}#{@request.host}#{@request.request_uri}"
977b4be2 » dhh 2005-07-05 Changed logging of SQL stat... 987 end
988
db045dbb » dhh 2004-11-23 Initial 989 def close_session
990 @session.close unless @session.nil? || Hash === @session
991 end
992
993 def template_exists?(template_name = default_template_name)
994 @template.file_exists?(template_name)
995 end
996
997 def template_public?(template_name = default_template_name)
998 @template.file_public?(template_name)
999 end
1000
62fe5bbf » Marcel Molina 2005-11-18 Make rjs templates always i... 1001 def template_exempt_from_layout?(template_name = default_template_name)
1002 @template.javascript_template_exists?(template_name)
1003 end
1004
db045dbb » dhh 2004-11-23 Initial 1005 def assert_existance_of_template_file(template_name)
1006 unless template_exists?(template_name) || ignore_missing_templates
1007 full_template_path = @template.send(:full_template_path, template_name, 'rhtml')
1008 template_type = (template_name =~ /layouts/i) ? 'layout' : 'template'
1009 raise(MissingTemplate, "Missing #{template_type} #{full_template_path}")
1010 end
1011 end
1012
1013 def default_template_name(default_action_name = action_name)
233208b8 » Marcel Molina 2005-12-19 Don't try to strip out the ... 1014 if default_action_name
1812dbbf » dhh 2006-02-17 Make RJS treat symbolic act... 1015 default_action_name = default_action_name.to_s.dup
233208b8 » Marcel Molina 2005-12-19 Don't try to strip out the ... 1016 strip_out_controller!(default_action_name) if template_path_includes_controller?(default_action_name)
1017 end
b1999be5 » dhh 2005-02-14 A hopefully more successful... 1018 "#{self.class.controller_path}/#{default_action_name}"
db045dbb » dhh 2004-11-23 Initial 1019 end
39766a9b » Marcel Molina 2005-12-16 Don't include a layout when... 1020
1021 def strip_out_controller!(path)
1022 path.replace path.split('/', 2).last
1023 end
1024
1025 def template_path_includes_controller?(path)
1026 path.to_s['/'] && self.class.controller_path.split('/')[-1] == path.split('/')[0]
1027 end
050c3964 » dhh 2006-02-11 Stopped the massive bleedin... 1028
1029 def process_cleanup
1030 close_session
1031 end
db045dbb » dhh 2004-11-23 Initial 1032 end
1033 end