diff --git a/app/controllers/api_taster/routes_controller.rb b/app/controllers/api_taster/routes_controller.rb index bd6b40a..a5f2d13 100644 --- a/app/controllers/api_taster/routes_controller.rb +++ b/app/controllers/api_taster/routes_controller.rb @@ -1,5 +1,6 @@ module ApiTaster class RoutesController < ApiTaster::ApplicationController + ApiTaster.controller_hook(self) before_filter :map_routes layout false, except: :index diff --git a/lib/api_taster.rb b/lib/api_taster.rb index e74e8e8..f88023d 100644 --- a/lib/api_taster.rb +++ b/lib/api_taster.rb @@ -25,5 +25,23 @@ def self.routes(&block) ApiTaster::RouteCollector.routes << block end + @@controller_hook = nil + + # Controller hooking may used for custom filters, authorizations, etc. + # + # Example with adding basic authentication: + # + # ApiTaster.controller_hook do + # http_basic_authenticate_with name: "admin", password: "123456" + # end + # + def self.controller_hook(klass=nil, &block) + if block_given? + @@controller_hook = Proc.new {|klass| klass.instance_eval(&block) } + elsif @@controller_hook && klass + @@controller_hook.call(klass) + end + end + class Exception < ::Exception; end end diff --git a/spec/controllers/api_taster/routes_controller_spec.rb b/spec/controllers/api_taster/routes_controller_spec.rb index 7c09df9..7f074fd 100644 --- a/spec/controllers/api_taster/routes_controller_spec.rb +++ b/spec/controllers/api_taster/routes_controller_spec.rb @@ -61,5 +61,19 @@ module ApiTaster end end end + + context "when defined ApiTaster.controller_hook" do + before do + ApiTaster.controller_hook { before_action {|c| c.response.headers['X-Controller-Hook'] = '1'} } + ApiTaster.controller_hook(described_class) + end + + it 'applies the hook' do + ApiTaster.controller_hook.should.kind_of? Proc + + get :index, :use_route => :api_taster + response.headers.keys.should include('X-Controller-Hook') + end + end end end