Browse files

Added optional blocks to :before and :after hooks

  • Loading branch information...
1 parent 57f51ad commit f877c0f8609d55dbd5c6f839880a4c2a0a379aa7 @michaeldv michaeldv committed Jan 20, 2012
Showing with 37 additions and 11 deletions.
  1. +5 −4 TODO
  2. +26 −6 lib/dio/controller.rb
  3. +6 −1 samples/test.rb
View
9 TODO
@@ -1,4 +1,5 @@
-+ Basic error handling (404, etc)
-+ Serving static files
-- Before and after filters
-- supports :json, :xml, :html in controllers
++ Basic error handling (404, etc).
++ Serving static files.
++ Before and after filters with blocks.
+- supports :json, :xml, :html in controllers.
+
View
32 lib/dio/controller.rb
@@ -70,7 +70,11 @@ def invoke(before_or_after, action)
next if hook[:only] && !Array(hook[:only]).include?(action)
next if hook[:except] && Array(hook[:except]).include?(action)
puts "invoking #{hook[:method].inspect}"
- __send__(hook[:method])
+ case hook[:method]
+ when Symbol, String then __send__(hook[:method])
+ when Proc then hook[:method].call(self)
+ else raise "Invalid #{before_or_after} hook"
+ end
end
end
@@ -145,13 +149,29 @@ def routes(group = nil, scope = {}, &block)
yield # routes do ... end
end
end
-
+ #
+ # Define +before+ and +after+ hook methods. The hooks get executed in the
+ # order received before or after the current action. Examples:
+ #
+ # before :hello, :only => :index
+ # after :cheers, :goodbye, :except => [ :new, :destroy ]
+ #
+ # With a block - accepts current controller instance as a parameter.
+ #
+ # after :only => :index do |controller|
+ # puts controller.response.inspect
+ # end
+ #
#--------------------------------------------------------------------------
- [ :before, :after ].each do |hook|
- define_method hook do |method, scope = {}|
- puts "#{hook}: #{method.inspect}"
+ [ :before, :after ].each do |hook, &block|
+ define_method hook do |*names, &block|
+ puts "#{hook}: #{names.inspect}"
@hooks ||= { :before => [], :after => [] }
- @hooks[hook] << { :method => method }.merge(scope)
+ scope = names.last.is_a?(Hash) ? names.pop : {}
+ names << block if block # When invoking the hook it might be Symbol or Proc.
+ names.each do |name|
+ @hooks[hook] << { :method => name }.merge(scope)
+ end
end
end
View
7 samples/test.rb
@@ -2,7 +2,12 @@ class Test < Dio::Controller
# routes :restful, :except => :destroy
# routes :restful, :only => [:index, :new]
- before :say_hi, :only => :cancel
+ after [], :only => :index do |controller|
+ puts "--- BYE (INDEX ONLY) ---"
+ puts controller.response.inspect
+ end
+
+ before "say_hi", :only => :cancel
routes do
get "/:action/*/:id/*" => :index

0 comments on commit f877c0f

Please sign in to comment.