rails 2.3.8 → 2.3.9.pre

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

Files changed (119) hide show
  1. data/CHANGELOG +3 -2
  2. data/Rakefile +6 -7
  3. data/builtin/rails_info/rails/info.rb +1 -1
  4. data/environments/boot.rb +6 -2
  5. data/environments/environment.rb +1 -1
  6. data/lib/initializer.rb +44 -20
  7. data/lib/rails/plugin.rb +1 -1
  8. data/lib/rails/plugin/loader.rb +3 -3
  9. data/lib/rails/version.rb +1 -1
  10. data/lib/rails_generator/generators/components/migration/migration_generator.rb +1 -1
  11. data/lib/rails_generator/generators/components/plugin/templates/test_helper.rb +2 -1
  12. metadata +25 -124
  13. data/guides/files/javascripts/code_highlighter.js +0 -188
  14. data/guides/files/javascripts/guides.js +0 -8
  15. data/guides/files/javascripts/highlighters.js +0 -90
  16. data/guides/files/stylesheets/main.css +0 -441
  17. data/guides/files/stylesheets/print.css +0 -52
  18. data/guides/files/stylesheets/reset.css +0 -43
  19. data/guides/files/stylesheets/style.css +0 -13
  20. data/guides/files/stylesheets/syntax.css +0 -31
  21. data/guides/images/belongs_to.png +0 -0
  22. data/guides/images/book_icon.gif +0 -0
  23. data/guides/images/bullet.gif +0 -0
  24. data/guides/images/chapters_icon.gif +0 -0
  25. data/guides/images/check_bullet.gif +0 -0
  26. data/guides/images/credits_pic_blank.gif +0 -0
  27. data/guides/images/csrf.png +0 -0
  28. data/guides/images/customized_error_messages.png +0 -0
  29. data/guides/images/error_messages.png +0 -0
  30. data/guides/images/feature_tile.gif +0 -0
  31. data/guides/images/footer_tile.gif +0 -0
  32. data/guides/images/fxn.jpg +0 -0
  33. data/guides/images/grey_bullet.gif +0 -0
  34. data/guides/images/habtm.png +0 -0
  35. data/guides/images/has_many.png +0 -0
  36. data/guides/images/has_many_through.png +0 -0
  37. data/guides/images/has_one.png +0 -0
  38. data/guides/images/has_one_through.png +0 -0
  39. data/guides/images/header_backdrop.png +0 -0
  40. data/guides/images/header_tile.gif +0 -0
  41. data/guides/images/i18n/demo_localized_pirate.png +0 -0
  42. data/guides/images/i18n/demo_translated_en.png +0 -0
  43. data/guides/images/i18n/demo_translated_pirate.png +0 -0
  44. data/guides/images/i18n/demo_translation_missing.png +0 -0
  45. data/guides/images/i18n/demo_untranslated.png +0 -0
  46. data/guides/images/icons/README +0 -5
  47. data/guides/images/icons/callouts/1.png +0 -0
  48. data/guides/images/icons/callouts/10.png +0 -0
  49. data/guides/images/icons/callouts/11.png +0 -0
  50. data/guides/images/icons/callouts/12.png +0 -0
  51. data/guides/images/icons/callouts/13.png +0 -0
  52. data/guides/images/icons/callouts/14.png +0 -0
  53. data/guides/images/icons/callouts/15.png +0 -0
  54. data/guides/images/icons/callouts/2.png +0 -0
  55. data/guides/images/icons/callouts/3.png +0 -0
  56. data/guides/images/icons/callouts/4.png +0 -0
  57. data/guides/images/icons/callouts/5.png +0 -0
  58. data/guides/images/icons/callouts/6.png +0 -0
  59. data/guides/images/icons/callouts/7.png +0 -0
  60. data/guides/images/icons/callouts/8.png +0 -0
  61. data/guides/images/icons/callouts/9.png +0 -0
  62. data/guides/images/icons/caution.png +0 -0
  63. data/guides/images/icons/example.png +0 -0
  64. data/guides/images/icons/home.png +0 -0
  65. data/guides/images/icons/important.png +0 -0
  66. data/guides/images/icons/next.png +0 -0
  67. data/guides/images/icons/note.png +0 -0
  68. data/guides/images/icons/prev.png +0 -0
  69. data/guides/images/icons/tip.png +0 -0
  70. data/guides/images/icons/up.png +0 -0
  71. data/guides/images/icons/warning.png +0 -0
  72. data/guides/images/nav_arrow.gif +0 -0
  73. data/guides/images/polymorphic.png +0 -0
  74. data/guides/images/posts_index.png +0 -0
  75. data/guides/images/rails_guides_logo.gif +0 -0
  76. data/guides/images/rails_logo_remix.gif +0 -0
  77. data/guides/images/rails_welcome.png +0 -0
  78. data/guides/images/session_fixation.png +0 -0
  79. data/guides/images/tab_grey.gif +0 -0
  80. data/guides/images/tab_info.gif +0 -0
  81. data/guides/images/tab_note.gif +0 -0
  82. data/guides/images/tab_red.gif +0 -0
  83. data/guides/images/tab_yellow.gif +0 -0
  84. data/guides/images/tab_yellow.png +0 -0
  85. data/guides/images/validation_error_messages.png +0 -0
  86. data/guides/rails_guides.rb +0 -42
  87. data/guides/rails_guides/generator.rb +0 -138
  88. data/guides/rails_guides/helpers.rb +0 -34
  89. data/guides/rails_guides/indexer.rb +0 -55
  90. data/guides/rails_guides/textile_extensions.rb +0 -41
  91. data/guides/source/2_2_release_notes.textile +0 -422
  92. data/guides/source/2_3_release_notes.textile +0 -610
  93. data/guides/source/action_controller_overview.textile +0 -776
  94. data/guides/source/action_mailer_basics.textile +0 -424
  95. data/guides/source/active_record_basics.textile +0 -135
  96. data/guides/source/active_record_querying.textile +0 -969
  97. data/guides/source/activerecord_validations_callbacks.textile +0 -1086
  98. data/guides/source/association_basics.textile +0 -1781
  99. data/guides/source/caching_with_rails.textile +0 -524
  100. data/guides/source/command_line.textile +0 -589
  101. data/guides/source/configuring.textile +0 -234
  102. data/guides/source/contribute.textile +0 -71
  103. data/guides/source/contributing_to_rails.textile +0 -239
  104. data/guides/source/credits.erb.textile +0 -52
  105. data/guides/source/debugging_rails_applications.textile +0 -709
  106. data/guides/source/form_helpers.textile +0 -766
  107. data/guides/source/getting_started.textile +0 -1297
  108. data/guides/source/i18n.textile +0 -912
  109. data/guides/source/index.erb.textile +0 -124
  110. data/guides/source/layout.html.erb +0 -103
  111. data/guides/source/layouts_and_rendering.textile +0 -979
  112. data/guides/source/migrations.textile +0 -591
  113. data/guides/source/nested_model_forms.textile +0 -222
  114. data/guides/source/performance_testing.textile +0 -531
  115. data/guides/source/plugins.textile +0 -1512
  116. data/guides/source/rails_on_rack.textile +0 -309
  117. data/guides/source/routing.textile +0 -903
  118. data/guides/source/security.textile +0 -986
  119. data/guides/source/testing.textile +0 -951
@@ -1,776 +0,0 @@
1
- h2. Action Controller Overview
2
-
3
- In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will be able to:
4
-
5
- * Follow the flow of a request through a controller
6
- * Understand why and how to store data in the session or cookies
7
- * Work with filters to execute code during request processing
8
- * Use Action Controller's built-in HTTP authentication
9
- * Stream data directly to the user's browser
10
- * Filter sensitive parameters so they do not appear in the application's log
11
- * Deal with exceptions that may be raised during request processing
12
-
13
- endprologue.
14
-
15
- h3. What Does a Controller Do?
16
-
17
- Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straightforward as possible.
18
-
19
- For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
20
-
21
- A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
22
-
23
- NOTE: For more details on the routing process, see "Rails Routing from the Outside In":routing.html.
24
-
25
- h3. Methods and Actions
26
-
27
- A controller is a Ruby class which inherits from +ApplicationController+ and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.
28
-
29
- <ruby>
30
- class ClientsController < ApplicationController
31
- def new
32
- end
33
- end
34
- </ruby>
35
-
36
- As an example, if a user goes to +/clients/new+ in your application to add a new client, Rails will create an instance of +ClientsController+ and run the +new+ method. Note that the empty method from the example above could work just fine because Rails will by default render the +new.html.erb+ view unless the action says otherwise. The +new+ method could make available to the view a +@client+ instance variable by creating a new +Client+:
37
-
38
- <ruby>
39
- def new
40
- @client = Client.new
41
- end
42
- </ruby>
43
-
44
- The "Layouts & rendering guide":layouts_and_rendering.html explains this in more detail.
45
-
46
- +ApplicationController+ inherits from +ActionController::Base+, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
47
-
48
- Only public methods are callable as actions. It is a best practice to lower the visibility of methods which are not intended to be actions, like auxiliary methods or filters.
49
-
50
- h3. Parameters
51
-
52
- You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the +params+ hash in your controller:
53
-
54
- <ruby>
55
- class ClientsController < ActionController::Base
56
- # This action uses query string parameters because it gets run
57
- # by an HTTP GET request, but this does not make any difference
58
- # to the way in which the parameters are accessed. The URL for
59
- # this action would look like this in order to list activated
60
- # clients: /clients?status=activated
61
- def index
62
- if params[:status] == "activated"
63
- @clients = Client.activated
64
- else
65
- @clients = Client.unactivated
66
- end
67
- end
68
-
69
- # This action uses POST parameters. They are most likely coming
70
- # from an HTML form which the user has submitted. The URL for
71
- # this RESTful request will be "/clients", and the data will be
72
- # sent as part of the request body.
73
- def create
74
- @client = Client.new(params[:client])
75
- if @client.save
76
- redirect_to @client
77
- else
78
- # This line overrides the default rendering behavior, which
79
- # would have been to render the "create" view.
80
- render :action => "new"
81
- end
82
- end
83
- end
84
- </ruby>
85
-
86
- h4. Hash and Array Parameters
87
-
88
- The +params+ hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name:
89
-
90
- <pre>
91
- GET /clients?ids[]=1&ids[]=2&ids[]=3
92
- </pre>
93
-
94
- NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as "[" and "]" are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
95
-
96
- The value of +params[:ids]+ will now be +["1", "2", "3"]+. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
97
-
98
- To send a hash you include the key name inside the brackets:
99
-
100
- <html>
101
- <form action="/clients" method="post">
102
- <input type="text" name="client[name]" value="Acme" />
103
- <input type="text" name="client[phone]" value="12345" />
104
- <input type="text" name="client[address][postcode]" value="12345" />
105
- <input type="text" name="client[address][city]" value="Carrot City" />
106
- </form>
107
- </html>
108
-
109
- When this form is submitted, the value of +params[:client]+ will be <tt>{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}</tt>. Note the nested hash in +params[:client][:address]+.
110
-
111
- Note that the +params+ hash is actually an instance of +HashWithIndifferentAccess+ from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys.
112
-
113
- h4. Routing Parameters
114
-
115
- The +params+ hash will always contain the +:controller+ and +:action+ keys, but you should use the methods +controller_name+ and +action_name+ instead to access these values. Any other parameters defined by the routing, such as +:id+ will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the +:status+ parameter in a "pretty" URL:
116
-
117
- <ruby>
118
- map.connect "/clients/:status",
119
- :controller => "clients",
120
- :action => "index",
121
- :foo => "bar"
122
- </ruby>
123
-
124
- In this case, when a user opens the URL +/clients/active+, +params[:status]+ will be set to "active". When this route is used, +params[:foo]+ will also be set to "bar" just like it was passed in the query string. In the same way +params[:action]+ will contain "index".
125
-
126
- h4. +default_url_options+
127
-
128
- You can set global default parameters that will be used when generating URLs with +default_url_options+. To do this, define a method with that name in your controller:
129
-
130
- <ruby>
131
- class ApplicationController < ActionController::Base
132
- # The options parameter is the hash passed in to 'url_for'
133
- def default_url_options(options)
134
- {:locale => I18n.locale}
135
- end
136
- end
137
- </ruby>
138
-
139
- These options will be used as a starting-point when generating URLs, so it's possible they'll be overridden by +url_for+. Because this method is defined in the controller, you can define it on +ApplicationController+ so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.
140
-
141
-
142
- h3. Session
143
-
144
- Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
145
-
146
- * CookieStore - Stores everything on the client.
147
- * DRbStore - Stores the data on a DRb server.
148
- * MemCacheStore - Stores the data in a memcache.
149
- * ActiveRecordStore - Stores the data in a database using Active Record.
150
-
151
- All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
152
-
153
- For most stores this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).
154
-
155
- The CookieStore can store around 4kB of data -- much less than the others -- but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
156
-
157
- Read more about session storage in the "Security Guide":security.html.
158
-
159
- If you need a different session storage mechanism, you can change it in the +config/initializers/session_store.rb+ file:
160
-
161
- <ruby>
162
- # Use the database for sessions instead of the cookie-based default,
163
- # which shouldn't be used to store highly confidential information
164
- # (create the session table with "rake db:sessions:create")
165
- # ActionController::Base.session_store = :active_record_store
166
- </ruby>
167
-
168
- Rails sets up a session key (the name of the cookie) and (for the CookieStore) a secret key used when signing the session data. These can also be changed in +config/initializers/session_store.rb+:
169
-
170
- <ruby>
171
- # Your secret key for verifying cookie session data integrity.
172
- # If you change this key, all old sessions will become invalid!
173
- # Make sure the secret is at least 30 characters and all random,
174
- # no regular words or you'll be exposed to dictionary attacks.
175
- ActionController::Base.session = {
176
- :key => '_yourappname_session',
177
- :secret => '4f50711b8f0f49572...'
178
- }
179
- </ruby>
180
-
181
- NOTE: Changing the secret when using the CookieStore will invalidate all existing sessions.
182
-
183
- h4. Accessing the Session
184
-
185
- In your controller you can access the session through the +session+ instance method.
186
-
187
- NOTE: Sessions are lazily loaded. If you don't access sessions in your action's code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.
188
-
189
- Session values are stored using key/value pairs like a hash:
190
-
191
- <ruby>
192
- class ApplicationController < ActionController::Base
193
-
194
- private
195
-
196
- # Finds the User with the ID stored in the session with the key
197
- # :current_user_id This is a common way to handle user login in
198
- # a Rails application; logging in sets the session value and
199
- # logging out removes it.
200
- def current_user
201
- @_current_user ||= session[:current_user_id] &&
202
- User.find(session[:current_user_id])
203
- end
204
- end
205
- </ruby>
206
-
207
- To store something in the session, just assign it to the key like a hash:
208
-
209
- <ruby>
210
- class LoginsController < ApplicationController
211
- # "Create" a login, aka "log the user in"
212
- def create
213
- if user = User.authenticate(params[:username], params[:password])
214
- # Save the user ID in the session so it can be used in
215
- # subsequent requests
216
- session[:current_user_id] = user.id
217
- redirect_to root_url
218
- end
219
- end
220
- end
221
- </ruby>
222
-
223
- To remove something from the session, assign that key to be +nil+:
224
-
225
- <ruby>
226
- class LoginsController < ApplicationController
227
- # "Delete" a login, aka "log the user out"
228
- def destroy
229
- # Remove the user id from the session
230
- session[:current_user_id] = nil
231
- redirect_to root_url
232
- end
233
- end
234
- </ruby>
235
-
236
- To reset the entire session, use +reset_session+.
237
-
238
- h4. The Flash
239
-
240
- The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
241
-
242
- <ruby>
243
- class LoginsController < ApplicationController
244
- def destroy
245
- session[:current_user_id] = nil
246
- flash[:notice] = "You have successfully logged out"
247
- redirect_to root_url
248
- end
249
- end
250
- </ruby>
251
-
252
- The +destroy+ action redirects to the application's +root_url+, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:
253
-
254
- <ruby>
255
- <html>
256
- <!-- <head/> -->
257
- <body>
258
- <% if flash[:notice] -%>
259
- <p class="notice"><%= flash[:notice] %></p>
260
- <% end -%>
261
- <% if flash[:error] -%>
262
- <p class="error"><%= flash[:error] %></p>
263
- <% end -%>
264
- <!-- more content -->
265
- </body>
266
- </html>
267
- </ruby>
268
-
269
- This way, if an action sets an error or a notice message, the layout will display it automatically.
270
-
271
- If you want a flash value to be carried over to another request, use the +keep+ method:
272
-
273
- <ruby>
274
- class MainController < ApplicationController
275
- # Let's say this action corresponds to root_url, but you want
276
- # all requests here to be redirected to UsersController#index.
277
- # If an action sets the flash and redirects here, the values
278
- # would normally be lost when another redirect happens, but you
279
- # can use 'keep' to make it persist for another request.
280
- def index
281
- # Will persist all flash values.
282
- flash.keep
283
-
284
- # You can also use a key to keep only some kind of value.
285
- # flash.keep(:notice)
286
- redirect_to users_url
287
- end
288
- end
289
- </ruby>
290
-
291
- h5. +flash.now+
292
-
293
- By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the +create+ action fails to save a resource and you render the +new+ template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use +flash.now+ in the same way you use the normal +flash+:
294
-
295
- <ruby>
296
- class ClientsController < ApplicationController
297
- def create
298
- @client = Client.new(params[:client])
299
- if @client.save
300
- # ...
301
- else
302
- flash.now[:error] = "Could not save client"
303
- render :action => "new"
304
- end
305
- end
306
- end
307
- </ruby>
308
-
309
- h3. Cookies
310
-
311
- Your application can store small amounts of data on the client -- called cookies -- that will be persisted across requests and even sessions. Rails provides easy access to cookies via the +cookies+ method, which -- much like the +session+ -- works like a hash:
312
-
313
- <ruby>
314
- class CommentsController < ApplicationController
315
- def new
316
- # Auto-fill the commenter's name if it has been stored in a cookie
317
- @comment = Comment.new(:name => cookies[:commenter_name])
318
- end
319
-
320
- def create
321
- @comment = Comment.new(params[:comment])
322
- if @comment.save
323
- flash[:notice] = "Thanks for your comment!"
324
- if params[:remember_name]
325
- # Remember the commenter's name.
326
- cookies[:commenter_name] = @comment.name
327
- else
328
- # Delete cookie for the commenter's name cookie, if any.
329
- cookies.delete(:commenter_name)
330
- end
331
- redirect_to @comment.article
332
- else
333
- render :action => "new"
334
- end
335
- end
336
- end
337
- </ruby>
338
-
339
- Note that while for session values you set the key to +nil+, to delete a cookie value you should use +cookies.delete(:key)+.
340
-
341
- h3. Filters
342
-
343
- Filters are methods that are run before, after or "around" a controller action.
344
-
345
- Filters are inherited, so if you set a filter on +ApplicationController+, it will be run on every controller in your application.
346
-
347
- Before filters may halt the request cycle. A common before filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
348
-
349
- <ruby>
350
- class ApplicationController < ActionController::Base
351
- before_filter :require_login
352
-
353
- private
354
- def require_login
355
- unless logged_in?
356
- flash[:error] = "You must be logged in to access this section"
357
- redirect_to new_login_url # halts request cycle
358
- end
359
- end
360
-
361
- # The logged_in? method simply returns true if the user is logged
362
- # in and false otherwise. It does this by "booleanizing" the
363
- # current_user method we created previously using a double ! operator.
364
- # Note that this is not common in Ruby and is discouraged unless you
365
- # really mean to convert something into true or false.
366
- def logged_in?
367
- !!current_user
368
- end
369
- end
370
- </ruby>
371
-
372
- The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter they are also cancelled.
373
-
374
- In this example the filter is added to +ApplicationController+ and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with +skip_before_filter+:
375
-
376
- <ruby>
377
- class LoginsController < Application
378
- skip_before_filter :require_login, :only => [:new, :create]
379
- end
380
- </ruby>
381
-
382
- Now, the +LoginsController+'s +new+ and +create+ actions will work as before without requiring the user to be logged in. The +:only+ option is used to only skip this filter for these actions, and there is also an +:except+ option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
383
-
384
- h4. After Filters and Around Filters
385
-
386
- In addition to before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running.
387
-
388
- Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.
389
-
390
- <ruby>
391
- # Example taken from the Rails API filter documentation:
392
- # http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
393
- class ApplicationController < Application
394
- around_filter :catch_exceptions
395
-
396
- private
397
- def catch_exceptions
398
- yield
399
- rescue => exception
400
- logger.debug "Caught exception! #{exception}"
401
- raise
402
- end
403
- end
404
- </ruby>
405
-
406
- h4. Other Ways to Use Filters
407
-
408
- While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
409
-
410
- The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the +require_login+ filter from above could be rewritten to use a block:
411
-
412
- <ruby>
413
- class ApplicationController < ActionController::Base
414
- before_filter do |controller|
415
- redirect_to new_login_url unless controller.send(:logged_in?)
416
- end
417
- end
418
- </ruby>
419
-
420
- Note that the filter in this case uses +send+ because the +logged_in?+ method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
421
-
422
- The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
423
-
424
- <ruby>
425
- class ApplicationController < ActionController::Base
426
- before_filter LoginFilter
427
- end
428
-
429
- class LoginFilter
430
- def self.filter(controller)
431
- unless controller.send(:logged_in?)
432
- controller.flash[:error] = "You must be logged in"
433
- controller.redirect_to controller.new_login_url
434
- end
435
- end
436
- end
437
- </ruby>
438
-
439
- Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method +filter+ which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same +filter+ method, which will get run in the same way. The method must +yield+ to execute the action. Alternatively, it can have both a +before+ and an +after+ method that are run before and after the action.
440
-
441
- The Rails API documentation has "more information on using filters":http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html.
442
-
443
- h3. Verification
444
-
445
- Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using +XMLHTTPRequest+ (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the "API documentation":http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html as "essentially a special kind of before_filter".
446
-
447
- Here's an example of using verification to make sure the user supplies a username and a password in order to log in:
448
-
449
- <ruby>
450
- class LoginsController < ApplicationController
451
- verify :params => [:username, :password],
452
- :render => {:action => "new"},
453
- :add_flash => {
454
- :error => "Username and password required to log in"
455
- }
456
-
457
- def create
458
- @user = User.authenticate(params[:username], params[:password])
459
- if @user
460
- flash[:notice] = "You're logged in"
461
- redirect_to root_url
462
- else
463
- render :action => "new"
464
- end
465
- end
466
- end
467
- </ruby>
468
-
469
- Now the +create+ action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the +new+ action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the +:only+ and +:except+ options just like a filter:
470
-
471
- <ruby>
472
- class LoginsController < ApplicationController
473
- verify :params => [:username, :password],
474
- :render => {:action => "new"},
475
- :add_flash => {
476
- :error => "Username and password required to log in"
477
- },
478
- :only => :create # Run only for the "create" action
479
- end
480
- </ruby>
481
-
482
- h3. Request Forgery Protection
483
-
484
- Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission.
485
-
486
- The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests.
487
-
488
- The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
489
-
490
- If you generate a form like this:
491
-
492
- <ruby>
493
- <% form_for @user do |f| -%>
494
- <%= f.text_field :username %>
495
- <%= f.text_field :password -%>
496
- <% end -%>
497
- </ruby>
498
-
499
- You will see how the token gets added as a hidden field:
500
-
501
- <html>
502
- <form action="/users/1" method="post">
503
- <input type="hidden"
504
- value="67250ab105eb5ad10851c00a5621854a23af5489"
505
- name="authenticity_token"/>
506
- <!-- fields -->
507
- </form>
508
- </html>
509
-
510
- Rails adds this token to every form that's generated using the "form helpers":form_helpers.html, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method +form_authenticity_token+:
511
-
512
- The +form_authenticity_token+ generates a valid authentication token. That's useful in places where Rails does not add it automatically, like in custom Ajax calls.
513
-
514
- The "Security Guide":security.html has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
515
-
516
- h3. The Request and Response Objects
517
-
518
- In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The +request+ method contains an instance of +AbstractRequest+ and the +response+ method returns a response object representing what is going to be sent back to the client.
519
-
520
- h4. The +request+ Object
521
-
522
- The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html. Among the properties that you can access on this object are:
523
-
524
- |_.Property of +request+|_.Purpose|
525
- |host|The hostname used for this request.|
526
- |domain(n=2)|The hostname's first +n+ segments, starting from the right (the TLD).|
527
- |format|The content type requested by the client.|
528
- |method|The HTTP method used for the request.|
529
- |get?, post?, put?, delete?, head?|Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD.|
530
- |headers|Returns a hash containing the headers associated with the request.|
531
- |port|The port number (integer) used for the request.|
532
- |protocol|Returns a string containing the protocol used plus "://", for example "http://".|
533
- |query_string|The query string part of the URL, i.e., everything after "?".|
534
- |remote_ip|The IP address of the client.|
535
- |url|The entire URL used for the request.|
536
-
537
- h5. +path_parameters+, +query_parameters+, and +request_parameters+
538
-
539
- Rails collects all of the parameters sent along with the request in the +params+ hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The +query_parameters+ hash contains parameters that were sent as part of the query string while the +request_parameters+ hash contains parameters sent as part of the post body. The +path_parameters+ hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
540
-
541
- h4. The +response+ Object
542
-
543
- The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
544
-
545
- |_.Property of +response+|_.Purpose|
546
- |body|This is the string of data being sent back to the client. This is most often HTML.|
547
- |status|The HTTP status code for the response, like 200 for a successful request or 404 for file not found.|
548
- |location|The URL the client is being redirected to, if any.|
549
- |content_type|The content type of the response.|
550
- |charset|The character set being used for the response. Default is "utf-8".|
551
- |headers|Headers used for the response.|
552
-
553
- h5. Setting Custom Headers
554
-
555
- If you want to set custom headers for a response then +response.headers+ is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them automatically. If you want to add or change a header, just assign it to +response.headers+ this way:
556
-
557
- <ruby>
558
- response.headers["Content-Type"] = "application/pdf"
559
- </ruby>
560
-
561
- h3. HTTP Authentications
562
-
563
- Rails comes with two built-in HTTP authentication mechanisms:
564
-
565
- * Basic Authentication
566
- * Digest Authentication
567
-
568
- h4. HTTP Basic Authentication
569
-
570
- HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, +authenticate_or_request_with_http_basic+.
571
-
572
- <ruby>
573
- class AdminController < ApplicationController
574
- USERNAME, PASSWORD = "humbaba", "5baa61e4"
575
-
576
- before_filter :authenticate
577
-
578
- private
579
- def authenticate
580
- authenticate_or_request_with_http_basic do |username, password|
581
- username == USERNAME &&
582
- Digest::SHA1.hexdigest(password) == PASSWORD
583
- end
584
- end
585
- end
586
- </ruby>
587
-
588
- With this in place, you can create namespaced controllers that inherit from +AdminController+. The before filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
589
-
590
- h4. HTTP Digest Authentication
591
-
592
- HTTP digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+.
593
-
594
- <ruby>
595
- class AdminController < ApplicationController
596
- USERS = { "lifo" => "world" }
597
-
598
- before_filter :authenticate
599
-
600
- private
601
- def authenticate
602
- authenticate_or_request_with_http_digest do |username|
603
- USERS[username]
604
- end
605
- end
606
- end
607
- </ruby>
608
-
609
- As seen in the example above, the +authenticate_or_request_with_http_digest+ block takes only one argument - the username. And the block returns the password. Returning +false+ or +nil+ from the +authenticate_or_request_with_http_digest+ will cause authentication failure.
610
-
611
- h3. Streaming and File Downloads
612
-
613
- Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the +send_data+ and the +send_file+ methods, which will both stream data to the client. +send_file+ is a convenience method that lets you provide the name of a file on the disk and it will stream the contents of that file for you.
614
-
615
- To stream data to the client, use +send_data+:
616
-
617
- <ruby>
618
- require "prawn"
619
- class ClientsController < ApplicationController
620
- # Generates a PDF document with information on the client and
621
- # returns it. The user will get the PDF as a file download.
622
- def download_pdf
623
- client = Client.find(params[:id])
624
- send_data(generate_pdf,
625
- :filename => "#{client.name}.pdf",
626
- :type => "application/pdf")
627
- end
628
-
629
- private
630
-
631
- def generate_pdf(client)
632
- Prawn::Document.new do
633
- text client.name, :align => :center
634
- text "Address: #{client.address}"
635
- text "Email: #{client.email}"
636
- end.render
637
- end
638
- end
639
- </ruby>
640
-
641
- The +download_pdf+ action in the example above will call a private method which actually generates the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the +:disposition+ option to "inline". The opposite and default value for this option is "attachment".
642
-
643
- h4. Sending Files
644
-
645
- If you want to send a file that already exists on disk, use the +send_file+ method.
646
-
647
- <ruby>
648
- class ClientsController < ApplicationController
649
- # Stream a file that has already been generated and stored on disk.
650
- def download_pdf
651
- client = Client.find(params[:id])
652
- send_data("#{RAILS_ROOT}/files/clients/#{client.id}.pdf",
653
- :filename => "#{client.name}.pdf",
654
- :type => "application/pdf")
655
- end
656
- end
657
- </ruby>
658
-
659
- This will read and stream the file 4kB at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the +:stream+ option or adjust the block size with the +:buffer_size+ option.
660
-
661
- WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
662
-
663
- TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the +:x_sendfile+ option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the +X-Sendfile+ header for this to work.
664
-
665
- h4. RESTful Downloads
666
-
667
- While +send_data+ works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the +show+ action, without any streaming:
668
-
669
- <ruby>
670
- class ClientsController < ApplicationController
671
- # The user can request to receive this resource as HTML or PDF.
672
- def show
673
- @client = Client.find(params[:id])
674
-
675
- respond_to do |format|
676
- format.html
677
- format.pdf { render :pdf => generate_pdf(@client) }
678
- end
679
- end
680
- end
681
- </ruby>
682
-
683
- In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file +config/initializers/mime_types.rb+:
684
-
685
- <ruby>
686
- Mime::Type.register "application/pdf", :pdf
687
- </ruby>
688
-
689
- NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
690
-
691
- Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
692
-
693
- <shell>
694
- GET /clients/1.pdf
695
- </shell>
696
-
697
- h3. Parameter Filtering
698
-
699
- Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
700
-
701
- <ruby>
702
- class ApplicationController < ActionController::Base
703
- filter_parameter_logging :password
704
- end
705
- </ruby>
706
-
707
- The method works recursively through all levels of the +params+ hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.
708
-
709
- h3. Rescue
710
-
711
- Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the +ActiveRecord::RecordNotFound+ exception.
712
-
713
- Rails' default exception handling displays a "500 Server Error" message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
714
-
715
- h4. The Default 500 and 404 Templates
716
-
717
- By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the +public+ folder, in +404.html+ and +500.html+ respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.
718
-
719
- h4. +rescue_from+
720
-
721
- If you want to do something a bit more elaborate when catching errors, you can use +rescue_from+, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses.
722
-
723
- When an exception occurs which is caught by a +rescue_from+ directive, the exception object is passed to the handler. The handler can be a method or a +Proc+ object passed to the +:with+ option. You can also use a block directly instead of an explicit +Proc+ object.
724
-
725
- Here's how you can use +rescue_from+ to intercept all +ActiveRecord::RecordNotFound+ errors and do something with them.
726
-
727
- <ruby>
728
- class ApplicationController < ActionController::Base
729
- rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
730
-
731
- private
732
- def record_not_found
733
- render :text => "404 Not Found", :status => 404
734
- end
735
- end
736
- </ruby>
737
-
738
- Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:
739
-
740
- <ruby>
741
- class ApplicationController < ActionController::Base
742
- rescue_from User::NotAuthorized, :with => :user_not_authorized
743
-
744
- private
745
- def user_not_authorized
746
- flash[:error] = "You don't have access to this section."
747
- redirect_to :back
748
- end
749
- end
750
-
751
- class ClientsController < ApplicationController
752
- # Check that the user has the right authorization to access clients.
753
- before_filter :check_authorization
754
-
755
- # Note how the actions don't have to worry about all the auth stuff.
756
- def edit
757
- @client = Client.find(params[:id])
758
- end
759
-
760
- private
761
- # If the user is not authorized, just throw the exception.
762
- def check_authorization
763
- raise User::NotAuthorized unless current_user.admin?
764
- end
765
- end
766
- </ruby>
767
-
768
- NOTE: Certain exceptions are only rescuable from the +ApplicationController+ class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's "article":http://m.onkey.org/2008/7/20/rescue-from-dispatching on the subject for more information.
769
-
770
- h3. Changelog
771
-
772
- "Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17
773
-
774
- * February 17, 2009: Yet another proofread by Xavier Noria.
775
-
776
- * November 4, 2008: First release version by Tore Darell