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

root/trunk/actionpack/lib/action_controller/filters.rb

Revision 9225, 23.4 kB (checked in by josh, 3 months ago)

Replaced callback method evaluation in AssociationCollection class to use ActiveSupport::Callbacks. Modified ActiveSupport::Callbacks::Callback#call to accept multiple arguments.

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