Module: Roda::RodaPlugins::Hooks

Defined in:
lib/roda/plugins/hooks.rb

Overview

The hooks plugin adds before and after hooks to the request cycle.

plugin :hooks

before do
  request.redirect('/login') unless logged_in?
  @time = Time.now
end

after do |res|
  logger.notice("Took #{Time.now - @time} seconds")
end

Note that in general, before hooks are not needed, since you can just run code at the top of the route block:

route do |r|
  r.redirect('/login') unless logged_in?
  # ...
end

However, this code makes it easier to write after hooks, as well as handle cases where before hooks are added after the route block.

Note that the after hook is called with the rack response array of status, headers, and body. If it wants to change the response, it must mutate this argument, calling response.status= inside an after block will not affect the returned status. Note that after hooks can be called with nil if an exception is raised during routing.

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Class Method Summary collapse

Class Method Details

.configure(app) ⇒ Object



41
42
43
44
# File 'lib/roda/plugins/hooks.rb', line 41

def self.configure(app)
  app.opts[:before_hook] ||= nil
  app.opts[:after_hook] ||= nil
end

.load_dependencies(app) ⇒ Object



36
37
38
39
# File 'lib/roda/plugins/hooks.rb', line 36

def self.load_dependencies(app)
  app.plugin :_before_hook
  app.plugin :_after_hook
end