Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/branches/1-2-stable/actionpack/lib/action_controller/filters.rb

Revision 7178, 28.4 kB (checked in by nzkoz, 1 year ago)

Merge [7177] to release. [skaes] References #8891

Line 
1 module ActionController #:nodoc:
2   module Filters #:nodoc:
3     def self.included(base)
4       base.extend(ClassMethods)
5       base.send(:include, ActionController::Filters::InstanceMethods)
6     end
7
8     # Filters enable controllers to run shared pre and post processing code for its actions. These filters can be used to do
9     # authentication, caching, or auditing before the intended action is performed. Or to do localization or output
10     # compression after the action has been performed. Filters have access to the request, response, and all the instance
11     # variables set by other filters in the chain or by the action (in the case of after filters).
12     #
13     # == Filter inheritance
14     #
15     # Controller inheritance hierarchies share filters downwards, but subclasses can also add or skip filters without
16     # affecting the superclass. For example:
17     #
18     #   class BankController < ActionController::Base
19     #     before_filter :audit
20     #
21     #     private
22     #       def audit
23     #         # record the action and parameters in an audit log
24     #       end
25     #   end
26     #
27     #   class VaultController < BankController
28     #     before_filter :verify_credentials
29     #
30     #     private
31     #       def verify_credentials
32     #         # make sure the user is allowed into the vault
33     #       end
34     #   end
35     #
36     # Now any actions performed on the BankController will have the audit method called before. On the VaultController,
37     # first the audit method is called, then the verify_credentials method. If the audit method returns false, then
38     # verify_credentials and the intended action are never called.
39     #
40     # == Filter types
41     #
42     # A filter can take one of three forms: method reference (symbol), external class, or inline method (proc). The first
43     # is the most common and works by referencing a protected or private method somewhere in the inheritance hierarchy of
44     # the controller by use of a symbol. In the bank example above, both BankController and VaultController use this form.
45     #
46     # Using an external class makes for more easily reused generic filters, such as output compression. External filter classes
47     # are implemented by having a static +filter+ method on any class and then passing this class to the filter method. Example:
48     #
49     #   class OutputCompressionFilter
50     #     def self.filter(controller)
51     #       controller.response.body = compress(controller.response.body)
52     #     end
53     #   end
54     #
55     #   class NewspaperController < ActionController::Base
56     #     after_filter OutputCompressionFilter
57     #   end
58     #
59     # The filter method is passed the controller instance and is hence granted access to all aspects of the controller and can
60     # manipulate them as it sees fit.
61     #
62     # The inline method (using a proc) can be used to quickly do something small that doesn't require a lot of explanation.
63     # Or just as a quick test. It works like this:
64     #
65     #   class WeblogController < ActionController::Base
66     #     before_filter { |controller| false if controller.params["stop_action"] }
67     #   end
68     #
69     # As you can see, the block expects to be passed the controller after it has assigned the request to the internal variables.
70     # This means that the block has access to both the request and response objects complete with convenience methods for params,
71     # session, template, and assigns. Note: The inline method doesn't strictly have to be a block; any object that responds to call
72     # and returns 1 or -1 on arity will do (such as a Proc or an Method object).
73     #
74     # Please note that around_filters function a little differently than the normal before and after filters with regard to filter
75     # types. Please see the section dedicated to around_filters below.
76     #
77     # == Filter chain ordering
78     #
79     # Using <tt>before_filter</tt> and <tt>after_filter</tt> appends the specified filters to the existing chain. That's usually
80     # just fine, but some times you care more about the order in which the filters are executed. When that's the case, you
81     # can use <tt>prepend_before_filter</tt> and <tt>prepend_after_filter</tt>. Filters added by these methods will be put at the
82     # beginning of their respective chain and executed before the rest. For example:
83     #
84     #   class ShoppingController < ActionController::Base
85     #     before_filter :verify_open_shop
86     #
87     #   class CheckoutController < ShoppingController
88     #     prepend_before_filter :ensure_items_in_cart, :ensure_items_in_stock
89     #
90     # The filter chain for the CheckoutController is now <tt>:ensure_items_in_cart, :ensure_items_in_stock,</tt>
91     # <tt>:verify_open_shop</tt>. So if either of the ensure filters return false, we'll never get around to see if the shop
92     # is open or not.
93     #
94     # You may pass multiple filter arguments of each type as well as a filter block.
95     # If a block is given, it is treated as the last argument.
96     #
97     # == Around filters
98     #
99     # Around filters wrap an action, executing code both before and after.
100     # They may be declared as method references, blocks, or objects responding
101     # to #filter or to both #before and #after.
102     #
103     # To use a method as an around_filter, pass a symbol naming the Ruby method.
104     # Yield (or block.call) within the method to run the action.
105     #
106     #   around_filter :catch_exceptions
107     #
108     #   private
109     #     def catch_exceptions
110     #       yield
111     #     rescue => exception
112     #       logger.debug "Caught exception! #{exception}"
113     #       raise
114     #     end
115     #
116     # To use a block as an around_filter, pass a block taking as args both
117     # the controller and the action block. You can't call yield directly from
118     # an around_filter block; explicitly call the action block instead:
119     #
120     #   around_filter do |controller, action|
121     #     logger.debug "before #{controller.action_name}"
122     #     action.call
123     #     logger.debug "after #{controller.action_name}"
124     #   end
125     #
126     # To use a filter object with around_filter, pass an object responding
127     # to :filter or both :before and :after. With a filter method, yield to
128     # the block as above:
129     #
130     #   around_filter BenchmarkingFilter
131     #
132     #   class BenchmarkingFilter
133     #     def self.filter(controller, &block)
134     #       Benchmark.measure(&block)
135     #     end
136     #   end
137     #
138     # With before and after methods:
139     #
140     #   around_filter Authorizer.new
141     #
142     #   class Authorizer
143     #     # This will run before the action. Returning false aborts the action.
144     #     def before(controller)
145     #       if user.authorized?
146     #         return true
147     #       else
148     #         redirect_to login_url
149     #         return false
150     #       end
151     #     end
152     #
153     #     # This will run after the action if and only if before returned true.
154     #     def after(controller)
155     #     end
156     #   end
157     #
158     # If the filter has before and after methods, the before method will be
159     # called before the action. If before returns false, the filter chain is
160     # halted and after will not be run. See Filter Chain Halting below for
161     # an example.
162     #
163     # == Filter chain skipping
164     #
165     # Declaring a filter on a base class conveniently applies to its subclasses,
166     # but sometimes a subclass should skip some of its superclass' filters:
167     #
168     #   class ApplicationController < ActionController::Base
169     #     before_filter :authenticate
170     #     around_filter :catch_exceptions
171     #   end
172     #
173     #   class WeblogController < ApplicationController
174     #     # Will run the :authenticate and :catch_exceptions filters.
175     #   end
176     #
177     #   class SignupController < ApplicationController
178     #     # Skip :authenticate, run :catch_exceptions.
179     #     skip_before_filter :authenticate
180     #   end
181     #
182     #   class ProjectsController < ApplicationController
183     #     # Skip :catch_exceptions, run :authenticate.
184     #     skip_filter :catch_exceptions
185     #   end
186     #
187     #   class ClientsController < ApplicationController
188     #     # Skip :catch_exceptions and :authenticate unless action is index.
189     #     skip_filter :catch_exceptions, :authenticate, :except => :index
190     #   end
191     #
192     # == Filter conditions
193     #
194     # Filters may be limited to specific actions by declaring the actions to
195     # include or exclude. Both options accept single actions (:only => :index)
196     # or arrays of actions (:except => [:foo, :bar]).
197     #
198     #   class Journal < ActionController::Base
199     #     # Require authentication for edit and delete.
200     #     before_filter :authorize, :only => [:edit, :delete]
201     #
202     #     # Passing options to a filter with a block.
203     #     around_filter(:except => :index) do |controller, action_block|
204     #       results = Profiler.run(&action_block)
205     #       controller.response.sub! "</body>", "#{results}</body>"
206     #     end
207     #
208     #     private
209     #       def authorize
210     #         # Redirect to login unless authenticated.
211     #       end
212     #   end
213     #
214     # == Filter Chain Halting
215     #
216     # <tt>before_filter</tt> and <tt>around_filter</tt> may halt the request
217     # before a controller action is run. This is useful, for example, to deny
218     # access to unauthenticated users or to redirect from http to https.
219     # Simply return false from the filter or call render or redirect.
220     # After filters will not be executed if the filter chain is halted.
221     #
222     # Around filters halt the request unless the action block is called.
223     # Given these filters
224     #   after_filter :after
225     #   around_filter :around
226     #   before_filter :before
227     #
228     # The filter chain will look like:
229     #
230     #   ...
231     #   . \
232     #   .  #around (code before yield)
233     #   .  .  \
234     #   .  .  #before (actual filter code is run)
235     #   .  .  .  \
236     #   .  .  .  execute controller action
237     #   .  .  .  /
238     #   .  .  ...
239     #   .  .  /
240     #   .  #around (code after yield)
241     #   . /
242     #   #after (actual filter code is run, unless the around filter does not yield)
243     #
244     # If #around returns before yielding, #after will still not be run. The #before
245     # filter and controller action will not be run. If #before returns false,
246     # the second half of #around and will still run but #after and the
247     # action will not. If #around does not yield, #after will not be run.
248     module ClassMethods
249       # The passed <tt>filters</tt> will be appended to the filter_chain and
250       # will execute before the action on this controller is performed.
251       def append_before_filter(*filters, &block)
252         append_filter_to_chain(filters, :before, &block)
253       end
254
255       # The passed <tt>filters</tt> will be prepended to the filter_chain and
256       # will execute before the action on this controller is performed.
257       def prepend_before_filter(*filters, &block)
258         prepend_filter_to_chain(filters, :before, &block)
259       end
260
261       # Shorthand for append_before_filter since it's the most common.
262       alias :before_filter :append_before_filter
263
264       # The passed <tt>filters</tt> will be appended to the array of filters
265       # that run _after_ actions on this controller are performed.
266       def append_after_filter(*filters, &block)
267         append_filter_to_chain(filters, :after, &block)
268       end
269
270       # The passed <tt>filters</tt> will be prepended to the array of filters
271       # that run _after_ actions on this controller are performed.
272       def prepend_after_filter(*filters, &block)
273         prepend_filter_to_chain(filters, :after, &block)
274       end
275
276       # Shorthand for append_after_filter since it's the most common.
277       alias :after_filter :append_after_filter
278
279
280       # If you append_around_filter A.new, B.new, the filter chain looks like
281       #
282       #   B#before
283       #     A#before
284       #       # run the action
285       #     A#after
286       #   B#after
287       #
288       # With around filters which yield to the action block, #before and #after
289       # are the code before and after the yield.
290       def append_around_filter(*filters, &block)
291         filters, conditions = extract_conditions(filters, &block)
292         filters.map { |f| proxy_before_and_after_filter(f) }.each do |filter|
293           append_filter_to_chain([filter, conditions])
294         end
295       end
296
297       # If you prepend_around_filter A.new, B.new, the filter chain looks like:
298       #
299       #   A#before
300       #     B#before
301       #       # run the action
302       #     B#after
303       #   A#after
304       #
305       # With around filters which yield to the action block, #before and #after
306       # are the code before and after the yield.
307       def prepend_around_filter(*filters, &block)
308         filters, conditions = extract_conditions(filters, &block)
309         filters.map { |f| proxy_before_and_after_filter(f) }.each do |filter|
310           prepend_filter_to_chain([filter, conditions])
311         end
312       end
313
314       # Shorthand for append_around_filter since it's the most common.
315       alias :around_filter :append_around_filter
316
317       # Removes the specified filters from the +before+ filter chain. Note that this only works for skipping method-reference
318       # filters, not procs. This is especially useful for managing the chain in inheritance hierarchies where only one out
319       # of many sub-controllers need a different hierarchy.
320       #
321       # You can control the actions to skip the filter for with the <tt>:only</tt> and <tt>:except</tt> options,
322       # just like when you apply the filters.
323       def skip_before_filter(*filters)
324         skip_filter_in_chain(*filters, &:before?)
325       end
326
327       # Removes the specified filters from the +after+ filter chain. Note that this only works for skipping method-reference
328       # filters, not procs. This is especially useful for managing the chain in inheritance hierarchies where only one out
329       # of many sub-controllers need a different hierarchy.
330       #
331       # You can control the actions to skip the filter for with the <tt>:only</tt> and <tt>:except</tt> options,
332       # just like when you apply the filters.
333       def skip_after_filter(*filters)
334         skip_filter_in_chain(*filters, &:after?)
335       end
336
337       # Removes the specified filters from the filter chain. This only works for method reference (symbol)
338       # filters, not procs. This method is different from skip_after_filter and skip_before_filter in that
339       # it will match any before, after or yielding around filter.
340       #
341       # You can control the actions to skip the filter for with the <tt>:only</tt> and <tt>:except</tt> options,
342       # just like when you apply the filters.
343       def skip_filter(*filters)
344         skip_filter_in_chain(*filters)
345       end
346
347       # Returns an array of Filter objects for this controller.
348       def filter_chain
349         read_inheritable_attribute("filter_chain") || []
350       end
351
352       # Returns all the before filters for this class and all its ancestors.
353       # This method returns the actual filter that was assigned in the controller to maintain existing functionality.
354       def before_filters #:nodoc:
355         filter_chain.select(&:before?).map(&:filter)
356       end
357
358       # Returns all the after filters for this class and all its ancestors.
359       # This method returns the actual filter that was assigned in the controller to maintain existing functionality.
360       def after_filters #:nodoc:
361         filter_chain.select(&:after?).map(&:filter)
362       end
363
364       # Returns a mapping between filters and the actions that may run them.
365       def included_actions #:nodoc:
366         @included_actions ||= read_inheritable_attribute("included_actions") || {}
367       end
368
369       # Returns a mapping between filters and actions that may not run them.
370       def excluded_actions #:nodoc:
371         @excluded_actions ||= read_inheritable_attribute("excluded_actions") || {}
372       end
373
374       # Find a filter in the filter_chain where the filter method matches the _filter_ param
375       # and (optionally) the passed block evaluates to true (mostly used for testing before?
376       # and after? on the filter). Useful for symbol filters.
377       #
378       # The object of type Filter is passed to the block when yielded, not the filter itself.
379       def find_filter(filter, &block) #:nodoc:
380         filter_chain.select { |f| f.filter == filter && (!block_given? || yield(f)) }.first
381       end
382
383       # Returns true if the filter is excluded from the given action
384       def filter_excluded_from_action?(filter,action) #:nodoc:
385         case
386         when ia = included_actions[filter]
387           !ia.include?(action)
388         when ea = excluded_actions[filter]
389           ea.include?(action)
390         end
391       end
392
393       # Filter class is an abstract base class for all filters. Handles all of the included/excluded actions but
394       # contains no logic for calling the actual filters.
395       class Filter #:nodoc:
396         attr_reader :filter, :included_actions, :excluded_actions
397
398         def initialize(filter)
399           @filter = filter
400         end
401
402         def type
403           :around
404         end
405
406         def before?
407           type == :before
408         end
409
410         def after?
411           type == :after
412         end
413
414         def around?
415           type == :around
416         end
417
418         def run(controller)
419           raise ActionControllerError, 'No filter type: Nothing to do here.'
420         end
421
422         def call(controller, &block)
423           run(controller)
424         end
425       end
426
427       # Abstract base class for filter proxies. FilterProxy objects are meant to mimic the behaviour of the old
428       # before_filter and after_filter by moving the logic into the filter itself.
429       class FilterProxy < Filter #:nodoc:
430         def filter
431           @filter.filter
432         end
433       end
434
435       class BeforeFilterProxy < FilterProxy #:nodoc:
436         def type
437           :before
438         end
439
440         def run(controller)
441           # only filters returning false are halted.
442           if false == @filter.call(controller)
443             controller.send :halt_filter_chain, @filter, :returned_false
444           end
445         end
446
447         def call(controller)
448           yield unless run(controller)
449         end
450       end
451
452       class AfterFilterProxy < FilterProxy #:nodoc:
453         def type
454           :after
455         end
456
457         def run(controller)
458           @filter.call(controller)
459         end
460
461         def call(controller)
462           yield
463           run(controller)
464         end
465       end
466
467       class SymbolFilter < Filter #:nodoc:
468         def call(controller, &block)
469           controller.send(@filter, &block)
470         end
471       end
472
473       class ProcFilter < Filter #:nodoc:
474         def call(controller)
475           @filter.call(controller)
476         rescue LocalJumpError # a yield from a proc... no no bad dog.
477           raise(ActionControllerError, 'Cannot yield from a Proc type filter. The Proc must take two arguments and execute #call on the second argument.')
478         end
479       end
480
481       class ProcWithCallFilter < Filter #:nodoc:
482         def call(controller, &block)
483           @filter.call(controller, block)
484         rescue LocalJumpError # a yield from a proc... no no bad dog.
485           raise(ActionControllerError, 'Cannot yield from a Proc type filter. The Proc must take two arguments and execute #call on the second argument.')
486         end
487       end
488
489       class MethodFilter < Filter #:nodoc:
490         def call(controller, &block)
491           @filter.call(controller, &block)
492         end
493       end
494
495       class ClassFilter < Filter #:nodoc:
496         def call(controller, &block)
497           @filter.filter(controller, &block)
498         end
499       end
500
501       class ClassBeforeFilter < Filter #:nodoc:
502         def call(controller, &block)
503           @filter.before(controller)
504         end
505       end
506
507       class ClassAfterFilter < Filter #:nodoc:
508         def call(controller, &block)
509           @filter.after(controller)
510         end
511       end
512
513       protected
514         def append_filter_to_chain(filters, filter_type = :around, &block)
515           pos = find_filter_append_position(filters, filter_type)
516           update_filter_chain(filters, filter_type, pos, &block)
517         end
518
519         def prepend_filter_to_chain(filters, filter_type = :around, &block)
520           pos = find_filter_prepend_position(filters, filter_type)
521           update_filter_chain(filters, filter_type, pos, &block)
522         end
523
524         def update_filter_chain(filters, filter_type, pos, &block)
525           new_filters = create_filters(filters, filter_type, &block)
526           new_chain = filter_chain.insert(pos, new_filters).flatten
527           write_inheritable_attribute('filter_chain', new_chain)
528         end
529
530         def find_filter_append_position(filters, filter_type)
531           # appending an after filter puts it at the end of the call chain
532           # before and around filters go before the first after filter in the chain
533           unless filter_type == :after
534             filter_chain.each_with_index do |f,i|
535               return i if f.after?
536             end
537           end
538           return -1
539         end
540
541         def find_filter_prepend_position(filters, filter_type)
542           # prepending a before or around filter puts it at the front of the call chain
543           # after filters go before the first after filter in the chain
544           if filter_type == :after
545             filter_chain.each_with_index do |f,i|
546               return i if f.after?
547             end
548             return -1
549           end
550           return 0
551         end
552
553         def create_filters(filters, filter_type, &block) #:nodoc:
554           filters, conditions = extract_conditions(filters, &block)
555           filters.map! { |filter| find_or_create_filter(filter, filter_type) }
556           update_conditions(filters, conditions)
557           filters
558         end
559
560         def find_or_create_filter(filter, filter_type)
561           if found_filter = find_filter(filter) { |f| f.type == filter_type }
562             found_filter
563           else
564             f = class_for_filter(filter, filter_type).new(filter)
565             # apply proxy to filter if necessary
566             case filter_type
567             when :before
568               BeforeFilterProxy.new(f)
569             when :after
570               AfterFilterProxy.new(f)
571             else
572               f
573             end
574           end
575         end
576
577         # The determination of the filter type was once done at run time.
578         # This method is here to extract as much logic from the filter run time as possible
579         def class_for_filter(filter, filter_type) #:nodoc:
580           case
581           when filter.is_a?(Symbol)
582             SymbolFilter
583           when filter.respond_to?(:call)
584             if filter.is_a?(Method)
585               MethodFilter
586             elsif filter.arity == 1
587               ProcFilter
588             else
589               ProcWithCallFilter
590             end
591           when filter.respond_to?(:filter)
592             ClassFilter
593           when filter.respond_to?(:before) && filter_type == :before
594             ClassBeforeFilter
595           when filter.respond_to?(:after) && filter_type == :after
596             ClassAfterFilter
597           else
598             raise(ActionControllerError, 'A filter must be a Symbol, Proc, Method, or object responding to filter, after or before.')
599           end
600         end
601
602         def extract_conditions(*filters, &block) #:nodoc:
603           filters.flatten!
604           conditions = filters.last.is_a?(Hash) ? filters.pop : {}
605           filters << block if block_given?
606           return filters, conditions
607         end
608
609         def update_conditions(filters, conditions)
610           return if conditions.empty?
611           if conditions[:only]
612             write_inheritable_hash('included_actions', condition_hash(filters, conditions[:only]))
613           elsif conditions[:except]
614             write_inheritable_hash('excluded_actions', condition_hash(filters, conditions[:except]))
615           end
616         end
617
618         def condition_hash(filters, *actions)
619           actions = actions.flatten.map(&:to_s)
620           filters.inject({}) { |h,f| h.update( f => (actions.blank? ? nil : actions)) }
621         end
622
623         def skip_filter_in_chain(*filters, &test) #:nodoc:
624           filters, conditions = extract_conditions(filters)
625           filters.map! { |f| block_given? ? find_filter(f, &test) : find_filter(f) }
626           filters.compact!
627
628           if conditions.empty?
629     &n