Action Controllers are made up of one or more actions that performs its purpose and then either renders a template or redirects to another action. An action is defined as a public method on the controller, which will automatically be made accessible to the web-server through a mod_rewrite mapping. A sample controller could look like this:
class GuestBookController < ActionController::Base
def index
@entries = Entry.find_all
end
def sign
Entry.create(@params["entry"])
redirect_to :action => "index"
end
end
GuestBookController.template_root = "templates/"
GuestBookController.process_cgi
All actions assume that you want to render a template matching the name of the action at the end of the performance unless you tell it otherwise. The index action complies with this assumption, so after populating the @entries instance variable, the GuestBookController will render "templates/guestbook/index.rhtml".
Unlike index, the sign action isn’t interested in rendering a template. So after performing its main purpose (creating a new entry in the guest book), it sheds the rendering assumption and initiates a redirect instead. This redirect works by returning an external "302 Moved" HTTP response that takes the user to the index action.
The index and sign represent the two basic action archetypes used in Action Controllers. Get-and-show and do-and-redirect. Most actions are variations of these themes.
Also note that it’s the final call to process_cgi that actually initiates the action performance. It will extract request and response objects from the CGI
Requests
Requests are processed by the Action Controller framework by extracting the value of the "action" key in the request parameters. This value should hold the name of the action to be performed. Once the action has been identified, the remaining request parameters, the session (if one is available), and the full request with all the http headers are made available to the action through instance variables. Then the action is performed.
The full request object is available in @request and is primarily used to query for http headers. These queries are made by accessing the environment hash, like this:
def hello_ip
location = @request.env["REMOTE_ADDRESS"]
render_text "Hello stranger from #{location}"
end
Parameters
All request parameters whether they come from a GET or POST request, or from the URL, are available through the @params hash. So an action that was performed through /weblog/list?category=All&limit=5 will include { "category" => "All", "limit" => 5 } in @params.
It’s also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
<input type="text" name="post[name]" value="david"> <input type="text" name="post[address]" value="hyacintvej">
A request steeming from a form holding these inputs will include { "post" => { "name" => "david", "address" => "hyacintvej" }. If the address input had been named "post[address][street]", the @params would have included { "post" => { "address" => { "street" => "hyacintvej" } } }. There’s no limit to the depth of the nesting.
Sessions
Sessions allows you to store objects in memory between requests. This is useful for objects that are not yet ready to be persisted, 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 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 they could be changed unknowingly. It’s usually too much work to keep it all synchronized — something databases already excel at.
You can place objects in the session by using the @session hash:
@session["person"] = Person.authenticate(user_name, password)
And retrieved again through the same hash:
Hello #{@session["person"]}
Any object can be placed in the session (as long as it can be Marshalled). But remember that 1000 active sessions each storing a 50kb object could lead to a 50MB memory overhead. In other words, think carefully about size and caching before resorting to the use of the session.
Responses
Each action results in a response, which holds the headers and document to be sent to the user’s browser. The actual response object is generated automatically through the use of renders and redirects, so it’s normally nothing you’ll need to be concerned about.
Renders
Action Controllers sends content to the user by using one of five rendering methods. The most versatile and common is the rendering of a template. Included in the Action Pack is the Action View, which enables rendering of eRuby templates. It’s automatically configgured. The controller passes objects to the view by assigning instance variables:
def show
@post = Post.find(@params["id"]
end
Which are then automatically available to the view:
Title: <%= @post.title %>
You don’t have to rely the automated rendering. Especially actions that could result in the rendering of different templates will use the manual rendering methods:
def search
@results = Search.find(@params["query"])
case @results
when 0 then render "weblog/no_results"
when 1 then render_action "show"
when 2..10 then render_action "show_many"
end
end
Read more about writing eRuby templates in classes/ActionView/ERbTemplate.html.
Redirects
Redirecting is what actions that update the model do when they’re done. The save_post method shouldn’t be responsible for also showing the post once it’s saved — that’s the job for show_post. So once save_post has completed its business, it’ll redirect to show_post. All redirects are external, which means that when the user refreshes his browser, it’s not going to save the post again, but rather just show it one more time.
This sounds fairly simple, but the redirection is complicated by the quest for a phenomenon known as "pretty urls". Instead of accepting the dreadful beings that is "weblog_controller?action=show&post_id=5", Action Controller goes out of its way to represent the former as "/weblog/show/5". And this is even the simple case. As an example of a more advanced pretty url consider "/library/books/ISBN/0743536703/show", which can be mapped to books_controller?action=show&type=ISBN&id=0743536703.
Redirects work by rewriting the URL of the current action. So if the show action was called by "/library/books/ISBN/0743536703/show", we can redirect to an edit action simply by doing redirect_to(:action => "edit"), which could throw the user to "/library/books/ISBN/0743536703/edit". Naturally, you’ll need to setup the .htaccess (or other mean of URL rewriting for the web server) to point to the proper controller and action in the first place, but once you have, it can be rewritten with ease.
Let’s consider a bunch of examples on how to go from "/library/books/ISBN/0743536703/edit" to somewhere else:
redirect_to(:action => "show", :action_prefix => "XTC/123") =>
"http://www.singlefile.com/library/books/XTC/123/show"
redirect_to(:path_params => {"type" => "EXBC"}) =>
"http://www.singlefile.com/library/books/EXBC/0743536703/show"
redirect_to(:controller => "settings") =>
"http://www.singlefile.com/library/settings/"
For more examples of redirecting options, have a look at the unit test in test/controller/url_test.rb. It’s very readable and will give you an excellent understanding of the different options and what they do.
Environments
Action Controller works out of the box with CGI, FastCGI, and mod_ruby. CGI and mod_ruby controllers are triggered just the same using:
WeblogController.process_cgi
FastCGI controllers are triggered using:
FCGI.each_cgi{ |cgi| WeblogController.process_cgi(cgi) }
- action_methods
- action_name
- add_class_variables_to_assigns
- add_instance_variables_to_assigns
- add_template_helper
- add_variables_to_assigns
- assert_existance_of_template_file
- assign_shortcuts
- close_session
- controller_class_name
- controller_name
- cookie
- initialize_current_url
- initialize_template_class
- log_processing
- perform_action
- process_cgi
- process_test
- protected_instance_variables
- redirect_to
- redirect_to_path
- redirect_to_url
- render
- render_action
- render_file
- render_template
- render_text
- request_origin
- template_exists?
- url_for
- ClassInheritableAttributes
| DEFAULT_RENDER_STATUS_CODE | = | "200 OK" |
| [RW] | assigns | Holds the hash of variables that are passed on to the template class to be made available to the view. This hash is generated by taking a snapshot of all the instance variables in the current scope just before a template is rendered. |
| [RW] | cookies | Holds a hash of cookie names and values. Accessed like @cookies["user_name"] to get the value of the user_name cookie. This hash is read-only. You set new cookies using the cookie method. |
| [RW] | headers | Holds a hash of header names and values. Accessed like @headers["Cache-Control"] to get the value of the Cache-Control directive. Values should always be specified as strings. |
| [RW] | params | Holds a hash of all the GET, POST, and Url parameters passed to the action. Accessed like @params["post_id"] to get the post_id. No type casts are made, so all values are returned as strings. |
| [RW] | request | Holds the request object that’s primarily used to get environment variables through access like @request.env["REQUEST_URI"]. |
| [RW] | response | Holds the response object that’s primarily used to set additional HTTP headers through access like @response.headers["Cache-Control"] = "no-cache". Can also be used to access the final body HTML after a template has been rendered through @response.body — useful for after_filters that wants to manipulate the output, such as a OutputCompressionFilter. |
| [RW] | session | Holds a hash of objects in the session. Accessed like @session["person"] to get the object tied to the "person" key. The session will hold any type of object as values, but the key should be a string. |
Makes all the (instance) methods in the helper module available to templates rendered through this controller. See ActionView::Helpers (classes/ActionView/Helpers.html) for more about making your own helper modules available to the templates.
[ show source ]
# File lib/action_controller/base.rb, line 232
232: def add_template_helper(helper_module)
233: template_class.class_eval "include #{helper_module}"
234: end
Process a request extracted from an CGI object and return a response. Pass false as session_options to disable sessions (large performance increase if sessions are not needed). The session_options are the same as for CGI::Session:
- :database_manager - options are CGI::Session::FileStore, CGI::Session::MemoryStore, and CGI::Session::PStore (default)
- :session_key - the parameter name used for the session id. Defaults to ‘_session_id’.
- :session_id - the session id to use. If not provided, then it is retrieved from the session_key parameter of the request, or automatically generated for a new session.
- :new_session - if true, force creation of a new session. If not set, a new session is only created if none currently exists. If false, a new session is never created, and if none currently exists and the session_id option is not set, an ArgumentError is raised.
- :session_expires - the time the current session expires, as a Time object. If not set, the session will continue indefinitely.
- :session_domain - the hostname domain for which this session is valid. If not set, defaults to the hostname of the server.
- :session_secure - if true, this session will only work over HTTPS.
- :session_path - the path for which this session applies. Defaults to the directory of the CGI script.
[ show source ]
# File lib/action_controller/cgi_process.rb, line 22
22: def self.process_cgi(cgi = CGI.new, session_options = {})
23: new.process_cgi(cgi, session_options)
24: end
Process a test request called with a TestRequest object.
[ show source ]
# File lib/action_controller/test_process.rb, line 4 4: def self.process_test(request) 5: new.process_test(request) 6: end
Returns the name of the action this controller is processing.
[ show source ]
# File lib/action_controller/base.rb, line 378
378: def action_name
379: @params["action"] || "index"
380: end
Converts the class name from something like "OneModule::TwoModule::NeatController" to "NeatController".
[ show source ]
# File lib/action_controller/base.rb, line 368
368: def controller_class_name
369: self.class.name.split("::").last
370: end
Converts the class name from something like "OneModule::TwoModule::NeatController" to "neat".
[ show source ]
# File lib/action_controller/base.rb, line 373
373: def controller_name
374: controller_class_name.sub(/Controller/, "").gsub(/([a-z])([A-Z])/) { |s| $1 + "_" + $2.downcase }.downcase
375: end
Creates a new cookie that is sent along-side the next render or redirect command. API is the same as for CGI::Cookie. Examples:
cookie("name", "value1", "value2", ...)
cookie("name" => "name", "value" => "value")
cookie('name' => 'name',
'value' => ['value1', 'value2', ...],
'path' => 'path', # optional
'domain' => 'domain', # optional
'expires' => Time.now, # optional
'secure' => true # optional
)
[ show source ]
# File lib/action_controller/base.rb, line 363
363: def cookie(*options) #:doc:
364: @response.headers["cookie"] << CGI::Cookie.new(*options)
365: end
Redirects the browser to an URL that has been rewritten according to the hash of options using a "302 Moved" HTTP header. See url_for for a description of the valid options.
[ show source ]
# File lib/action_controller/base.rb, line 333
333: def redirect_to(options = {}) #:doc:
334: redirect_to_url(url_for(options))
335: end
Redirects the browser to the specified path within the current host (specified with a leading /). Used to sidestep the URL rewriting and go directly to a known path. Example: redirect_to_path "/images/screenshot.jpg".
[ show source ]
# File lib/action_controller/base.rb, line 339
339: def redirect_to_path(path) #:doc:
340: redirect_to_url("http://" + @request.host + path)
341: end
Redirects the browser to the specified url. Used to redirect outside of the current application. Example: redirect_to_url "www.rubyonrails.org".
[ show source ]
# File lib/action_controller/base.rb, line 345
345: def redirect_to_url(url) #:doc:
346: logger.info("Redirected to #{url}") unless logger.nil?
347: @response.redirect(url)
348: @performed_redirect = true
349: end
Renders the template specified by template_name, which defaults to the name of the current controller and action. So calling render in WeblogController#show will attempt to render "#{template_root}/weblog/show.rhtml". The template_root is set on the ActionController::Base class and is shared by all controllers. It’s also possible to pass a status code using the second parameter. This defaults to "200 OK", but can be changed, such as by calling render("weblog/error", "500 Error").
[ show source ]
# File lib/action_controller/base.rb, line 255
255: def render(template_name = nil, status = nil) #:doc:
256: render_file(template_name || "#{controller_name}/#{action_name}", status, true)
257: end
Works like render, but instead of requiring a full template name, you can get by with specifying the action name. So calling render_action "show_many" in WeblogController#display will render "#{template_root}/weblog/show_many.rhtml".
[ show source ]
# File lib/action_controller/base.rb, line 261
261: def render_action(action_name, status = nil) #:doc:
262: render "#{controller_name}/#{action_name}", status
263: end
Works like render, but disregards the template_root and requires a full path to the template that needs to be rendered. Can be used like render_file "/Users/david/Code/Ruby/template" to render "/Users/david/Code/Ruby/template.rhtml".
[ show source ]
# File lib/action_controller/base.rb, line 267
267: def render_file(template_path, status = nil, use_full_path = false) #:doc:
268: assert_existance_of_template_file(template_path) if use_full_path
269: logger.info("Rendering #{template_path} (#{status || DEFAULT_RENDER_STATUS_CODE})") unless logger.nil?
270:
271: add_variables_to_assigns
272: render_text(@template.render_file(template_path, use_full_path), status)
273: end
Renders the template string, which is useful for rendering short templates you don’t want to bother having a file for. So you’d call render_template "Hello, <%= @user.name %>" to greet the current user.
[ show source ]
# File lib/action_controller/base.rb, line 277
277: def render_template(template, status = nil) #:doc:
278: add_variables_to_assigns
279: render_text(@template.render_template(template), status)
280: end
Renders the text string without parsing it through any template engine. Useful for rendering static information as it’s considerably faster than rendering through the template engine.
[ show source ]
# File lib/action_controller/base.rb, line 284
284: def render_text(text, status = nil) #:doc:
285: add_variables_to_assigns
286: @response.headers["Status"] = status || DEFAULT_RENDER_STATUS_CODE
287: @response.body = text
288: @performed_render = true
289: end
Returns an URL that has been rewritten according to the hash of options (for doing a complete redirect, use redirect_to). The valid keys in options are specified below with an example going from "/library/books/ISBN/0743536703/show" (mapped to books_controller?action=show&type=ISBN&id=0743536703):
.---> controller .--> action
/library/books/ISBN/0743536703/show
'------> '--------------> action_prefix
controller_prefix
- :controller_prefix - specifies the string before the controller name, which would be "/library" for the example. Called with "/shop" gives "/shop/books/ISBN/0743536703/show".
- :controller - specifies a new controller and clears out everything after the controller name (including the action, the pre- and suffix, and all params), so called with "settings" gives "/library/settings/".
- :action_prefix - specifies the string between the controller name and the action name, which would be "/ISBN/0743536703" for the example. Called with "/XTC/123/" gives "/library/books/XTC/123/show".
- :action - specifies a new action, so called with "edit" gives "/library/books/ISBN/0743536703/edit"
- :action_suffix - specifies the string after the action name, which would be empty for the example. Called with "/detailed" gives "/library/books/ISBN/0743536703/detailed".
- :path_params - specifies a hash that contains keys mapping to the request parameter names. In the example, { "type" => "ISBN", "id" => "0743536703" } would be the path_params. It serves as another way of replacing part of the action_prefix or action_suffix. So passing { "type" => "XTC" } would give "/library/books/XTC/0743536703/show".
- :id - shortcut where ":id => 5" can be used instead of specifying :path_params => { "id" => 5 }. Called with "123" gives "/library/books/ISBN/123/show".
- :params - specifies a hash that represents the regular request parameters, such as { "cat" => 1, "origin" => "there"} that would give "?cat=1&origin=there". Called with { "temporary" => 1 } in the example would give "/library/books/ISBN/0743536703/show?temporary=1"
- :anchor - specifies the anchor name to be appended to the path. Called with "x14" would give "/library/books/ISBN/0743536703/show#x14"
Naturally, you can combine multiple options in a single redirect. Examples:
redirect_to(:controller_prefix => "/shop", :controller => "settings")
redirect_to(:action => "edit", :id => 3425)
redirect_to(:action => "edit", :path_params => { "type" => "XTC"}, :params => { "temp" => 1})
redirect_to(:action => "publish", :action_prefix => "/published", :anchor => "x14")
[ show source ]
# File lib/action_controller/base.rb, line 327
327: def url_for(options = {}) #:doc:
328: @url.rewrite(options)
329: end
[ show source ]
# File lib/action_controller/base.rb, line 434
434: def action_methods
435: action_controller_classes = self.class.ancestors.reject{ |a| [Object, Kernel].include?(a) }
436: action_controller_classes.inject([]) { |action_methods, klass| action_methods + klass.instance_methods(false) }
437: end
[ show source ]
# File lib/action_controller/base.rb, line 452
452: def add_class_variables_to_assigns
453: %w( template_root logger template_class ignore_missing_templates ).each do |cvar|
454: @assigns[cvar] = self.send(cvar)
455: end
456: end
[ show source ]
# File lib/action_controller/base.rb, line 444
444: def add_instance_variables_to_assigns
445: protected_variables_cache = protected_instance_variables
446: instance_variables.each do |var|
447: next if protected_variables_cache.include?(var)
448: @assigns[var[1..-1]] = instance_variable_get(var)
449: end
450: end
[ show source ]
# File lib/action_controller/base.rb, line 439
439: def add_variables_to_assigns
440: add_instance_variables_to_assigns
441: add_class_variables_to_assigns if view_controller_internals
442: end
[ show source ]
# File lib/action_controller/base.rb, line 479
479: def assert_existance_of_template_file(template_name)
480: unless template_exists?(template_name) || ignore_missing_templates
481: raise(MissingTemplate, "Couldn't find #{template_name}")
482: end
483: end
[ show source ]
# File lib/action_controller/base.rb, line 393
393: def assign_shortcuts(request, response)
394: @request, @params, @cookies = request, request.parameters, request.cookies
395:
396: @response = response
397: @response.session = request.session
398:
399: @session = @response.session
400: @template = @response.template
401: @assigns = @response.template.assigns
402: @headers = @response.headers
403: end
[ show source ]
# File lib/action_controller/base.rb, line 470
470: def close_session
471: @session.update unless @session.nil? || Hash === @session
472: @session.close unless @session.nil? || Hash === @session
473: end
[ show source ]
# File lib/action_controller/base.rb, line 405
405: def initialize_current_url
406: if @request.respond_to?("env") && @request.env["SERVER_PORT"]
407: @url = UrlRewriter.new(
408: @request.env["SERVER_PORT"] == 443 ? "https://" : "http://", @request.host, @request.env["SERVER_PORT"],
409: @request.request_uri.split("?").first, controller_name, action_name, @params
410: )
411: else
412: @url = UrlRewriter.new("http://", "test", 80, "/", controller_name, action_name, @params)
413: end
414: end
[ show source ]
# File lib/action_controller/base.rb, line 383
383: def initialize_template_class(response)
384: begin
385: response.template = template_class.new(template_root, {}, self)
386: rescue
387: raise "You must assign a template class through ActionController.template_class= before processing a request"
388: end
389:
390: @performed_render = @performed_redirect = false
391: end
[ show source ]
# File lib/action_controller/base.rb, line 416
416: def log_processing
417: logger.info "\n\nProcessing #{controller_class_name}\##{action_name} (for #{request_origin})"
418: logger.info " Parameters: #{@params.inspect}"
419: end
[ show source ]
# File lib/action_controller/base.rb, line 421
421: def perform_action
422: if action_methods.include?(action_name)
423: send(action_name)
424: render unless @performed_render || @performed_redirect
425: elsif template_exists?
426: render
427: else
428: raise UnknownAction, "No action responded to #{action_name}", caller
429: end
430:
431: close_session
432: end
[ show source ]
# File lib/action_controller/base.rb, line 458
458: def protected_instance_variables
459: if view_controller_internals
460: [ "@assigns", "@performed_redirect", "@performed_render" ]
461: else
462: [ "@assigns", "@performed_redirect", "@performed_render", "@request", "@response", "@session", "@cookies", "@template" ]
463: end
464: end
[ show source ]
# File lib/action_controller/base.rb, line 466
466: def request_origin
467: "#{@request.remote_addr} at #{Time.now.to_s}"
468: end
[ show source ]
# File lib/action_controller/base.rb, line 475
475: def template_exists?(template_name = "#{controller_name}/#{action_name}")
476: @template.file_exists?(template_name)
477: end