README.rdoc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. = Action Pack -- From request to response
  2. Action Pack is a framework for handling and responding to web requests. It
  3. provides mechanisms for *routing* (mapping request URLs to actions), defining
  4. *controllers* that implement actions, and generating responses by rendering
  5. *views*, which are templates of various formats. In short, Action Pack
  6. provides the view and controller layers in the MVC paradigm.
  7. It consists of several modules:
  8. * Action Dispatch, which parses information about the web request, handles
  9. routing as defined by the user, and does advanced processing related to HTTP
  10. such as MIME-type negotiation, decoding parameters in POST/PUT bodies,
  11. handling HTTP caching logic, cookies and sessions.
  12. * Action Controller, which provides a base controller class that can be
  13. subclassed to implement filters and actions to handle requests. The result
  14. of an action is typically content generated from views.
  15. * Action View, which handles view template lookup and rendering, and provides
  16. view helpers that assist when building HTML forms, Atom feeds and more.
  17. Template formats that Action View handles are ERB (embedded Ruby, typically
  18. used to inline short Ruby snippets inside HTML), and XML Builder.
  19. With the Ruby on Rails framework, users only directly interface with the
  20. Action Controller module. Necessary Action Dispatch functionality is activated
  21. by default and Action View rendering is implicitly triggered by Action
  22. Controller. However, these modules are designed to function on their own and
  23. can be used outside of Rails.
  24. A short rundown of some of the major features:
  25. * Actions grouped in controller as methods instead of separate command objects
  26. and can therefore share helper methods
  27. class CustomersController < ActionController::Base
  28. def show
  29. @customer = find_customer
  30. end
  31. def update
  32. @customer = find_customer
  33. if @customer.update_attributes(params[:customer])
  34. redirect_to :action => "show"
  35. else
  36. render :action => "edit"
  37. end
  38. end
  39. private
  40. def find_customer
  41. Customer.find params[:id]
  42. end
  43. end
  44. {Learn more}[link:classes/ActionController/Base.html]
  45. * ERB templates (static content mixed with dynamic output from ruby)
  46. <% @posts.each do |post| %>
  47. Title: <%= post.title %>
  48. <% end %>
  49. All post titles: <%= @posts.collect{ |p| p.title }.join(", ") %>
  50. <% unless @person.is_client? %>
  51. Not for clients to see...
  52. <% end %>
  53. {Learn more}[link:classes/ActionView.html]
  54. * "Builder" templates (great for XML content, like RSS)
  55. xml.rss("version" => "2.0") do
  56. xml.channel do
  57. xml.title(@feed_title)
  58. xml.link(@url)
  59. xml.description "Basecamp: Recent items"
  60. xml.language "en-us"
  61. xml.ttl "40"
  62. @recent_items.each do |item|
  63. xml.item do
  64. xml.title(item_title(item))
  65. xml.description(item_description(item))
  66. xml.pubDate(item_pubDate(item))
  67. xml.guid(@recent_items.url(item))
  68. xml.link(@recent_items.url(item))
  69. end
  70. end
  71. end
  72. end
  73. {Learn more}[link:classes/ActionView/Base.html]
  74. * Filters for pre- and post-processing of the response
  75. class WeblogController < ActionController::Base
  76. # filters as methods
  77. before_filter :authenticate, :cache, :audit
  78. # filter as a proc
  79. after_filter { |c| c.response.body = Gzip::compress(c.response.body) }
  80. # class filter
  81. after_filter LocalizeFilter
  82. def index
  83. # Before this action is run, the user will be authenticated, the cache
  84. # will be examined to see if a valid copy of the results already
  85. # exists, and the action will be logged for auditing.
  86. # After this action has run, the output will first be localized then
  87. # compressed to minimize bandwidth usage
  88. end
  89. private
  90. def authenticate
  91. # Implement the filter with full access to both request and response
  92. end
  93. end
  94. {Learn more}[link:classes/ActionController/Filters/ClassMethods.html]
  95. * Helpers for forms, dates, action links, and text
  96. <%= text_field_tag "post", "title", "size" => 30 %>
  97. <%= link_to "New post", :controller => "post", :action => "new" %>
  98. <%= truncate(post.title, :length => 25) %>
  99. {Learn more}[link:classes/ActionView/Helpers.html]
  100. * Layout sharing for template reuse
  101. class WeblogController < ActionController::Base
  102. layout "weblog_layout"
  103. def hello_world
  104. end
  105. end
  106. Layout file (called weblog_layout):
  107. <html><body><%= yield %></body></html>
  108. Template for hello_world action:
  109. <h1>Hello world</h1>
  110. Result of running hello_world action:
  111. <html><body><h1>Hello world</h1></body></html>
  112. {Learn more}[link:classes/ActionController/Layout/ClassMethods.html]
  113. * Routing makes pretty URLs incredibly easy
  114. match 'clients/:client_name/:project_name/:controller/:action'
  115. Accessing "/clients/37signals/basecamp/project/index" calls ProjectController#index with
  116. { "client_name" => "37signals", "project_name" => "basecamp" } in `params`
  117. From that action, you can write the redirect in a number of ways:
  118. redirect_to(:action => "edit") =>
  119. /clients/37signals/basecamp/project/edit
  120. redirect_to(:client_name => "nextangle", :project_name => "rails") =>
  121. /clients/nextangle/rails/project/index
  122. {Learn more}[link:classes/ActionDispatch/Routing.html]
  123. * Easy testing of both controller and rendered template through ActionController::TestCase
  124. class LoginControllerTest < ActionController::TestCase
  125. def test_failing_authenticate
  126. process :authenticate, :user_name => "nop", :password => ""
  127. assert flash.has_key?(:alert)
  128. assert_redirected_to :action => "index"
  129. end
  130. end
  131. {Learn more}[link:classes/ActionController/TestCase.html]
  132. * Automated benchmarking and integrated logging
  133. Started GET "/weblog" for 127.0.0.1 at Fri May 28 00:41:55
  134. Processing by WeblogController#index as HTML
  135. Rendered weblog/index.html.erb within layouts/application (25.7ms)
  136. Completed 200 OK in 29.3ms
  137. If Active Record is used as the model, you'll have the database debugging
  138. as well:
  139. Started POST "/posts" for 127.0.0.1 at Sat Jun 19 14:04:23
  140. Processing by PostsController#create as HTML
  141. Parameters: {"post"=>{"title"=>"this is good"}}
  142. SQL (0.6ms) INSERT INTO posts (title) VALUES('this is good')
  143. Redirected to http://example.com/posts/5
  144. Completed 302 Found in 221ms (Views: 215ms | ActiveRecord: 0.6ms)
  145. You specify a logger through a class method, such as:
  146. ActionController::Base.logger = Logger.new("Application Log")
  147. ActionController::Base.logger = Log4r::Logger.new("Application Log")
  148. * Caching at three levels of granularity (page, action, fragment)
  149. class WeblogController < ActionController::Base
  150. caches_page :show
  151. caches_action :account
  152. def show
  153. # the output of the method will be cached as
  154. # ActionController::Base.page_cache_directory + "/weblog/show.html"
  155. # and the web server will pick it up without even hitting Rails
  156. end
  157. def account
  158. # the output of the method will be cached in the fragment store
  159. # but Rails is hit to retrieve it, so filters are run
  160. end
  161. def update
  162. List.update(params[:list][:id], params[:list])
  163. expire_page :action => "show", :id => params[:list][:id]
  164. expire_action :action => "account"
  165. redirect_to :action => "show", :id => params[:list][:id]
  166. end
  167. end
  168. {Learn more}[link:classes/ActionController/Caching.html]
  169. * Powerful debugging mechanism for local requests
  170. All exceptions raised on actions performed on the request of a local user
  171. will be presented with a tailored debugging screen that includes exception
  172. message, stack trace, request parameters, session contents, and the
  173. half-finished response.
  174. {Learn more}[link:classes/ActionController/Rescue.html]
  175. == Simple example (from outside of Rails)
  176. This example will implement a simple weblog system using inline templates and
  177. an Active Record model. So let's build that WeblogController with just a few
  178. methods:
  179. require 'action_controller'
  180. require 'post'
  181. class WeblogController < ActionController::Base
  182. layout "weblog/layout"
  183. def index
  184. @posts = Post.all
  185. end
  186. def show
  187. @post = Post.find(params[:id])
  188. end
  189. def new
  190. @post = Post.new
  191. end
  192. def create
  193. @post = Post.create(params[:post])
  194. redirect_to :action => "show", :id => @post.id
  195. end
  196. end
  197. WeblogController::Base.view_paths = [ File.dirname(__FILE__) ]
  198. WeblogController.process_cgi if $0 == __FILE__
  199. The last two lines are responsible for telling ActionController where the
  200. template files are located and actually running the controller on a new
  201. request from the web-server (e.g., Apache).
  202. And the templates look like this:
  203. weblog/layout.html.erb:
  204. <html><body>
  205. <%= yield %>
  206. </body></html>
  207. weblog/index.html.erb:
  208. <% @posts.each do |post| %>
  209. <p><%= link_to(post.title, :action => "show", :id => post.id) %></p>
  210. <% end %>
  211. weblog/show.html.erb:
  212. <p>
  213. <b><%= @post.title %></b><br/>
  214. <b><%= @post.content %></b>
  215. </p>
  216. weblog/new.html.erb:
  217. <%= form "post" %>
  218. This simple setup will list all the posts in the system on the index page,
  219. which is called by accessing /weblog/. It uses the form builder for the Active
  220. Record model to make the new screen, which in turn hands everything over to
  221. the create action (that's the default target for the form builder when given a
  222. new model). After creating the post, it'll redirect to the show page using
  223. an URL such as /weblog/5 (where 5 is the id of the post).
  224. == Download and installation
  225. The latest version of Action Pack can be installed with RubyGems:
  226. % [sudo] gem install actionpack
  227. Source code can be downloaded as part of the Rails project on GitHub
  228. * https://github.com/rails/rails/tree/3-2-stable/actionpack
  229. == License
  230. Action Pack is released under the MIT license.
  231. == Support
  232. API documentation is at
  233. * http://api.rubyonrails.org
  234. Bug reports and feature requests can be filed with the rest for the Ruby on Rails project here:
  235. * https://github.com/rails/rails/issues