Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a controller hooking feature #62

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/controllers/api_taster/routes_controller.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module ApiTaster
class RoutesController < ApiTaster::ApplicationController
ApiTaster.controller_hook(self)
before_filter :map_routes
layout false, except: :index

Expand Down
18 changes: 18 additions & 0 deletions lib/api_taster.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
14 changes: 14 additions & 0 deletions spec/controllers/api_taster/routes_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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