Sha256: b931a7162dd1532723d3a271116a3e31d80f7aca6eeb68850caadc41ca2f17e9

Contents?: true

Size: 1.86 KB

Versions: 6

Compression:

Stored size: 1.86 KB

Contents

# frozen-string-literal: true

#
class Roda
  module RodaPlugins
    # The status_handler plugin adds a +status_handler+ method which sets a
    # block that is called whenever a response with the relevant response code
    # with an empty body would be returned.
    #
    # This plugin does not support providing the blocks with the plugin call;
    # you must provide them to status_handler calls afterwards:
    #
    #   plugin :status_handler
    #
    #   status_handler(403) do
    #     "You are forbidden from seeing that!"
    #   end
    #   status_handler(404) do
    #     "Where did it go?"
    #   end
    #
    # Before a block is called, any existing headers on the response will be
    # cleared.  So if you want to be sure the headers are set even in your block,
    # you need to reset them in the block.
    module StatusHandler
      def self.load_dependencies(app)
        app.plugin :_after_hook
      end

      def self.configure(app)
        app.opts[:status_handler] ||= {}
      end

      module ClassMethods
        # Install the given block as a status handler for the given HTTP response code.
        def status_handler(code, &block)
          opts[:status_handler][code] = block
        end

        # Freeze the hash of status handlers so that there can be no thread safety issues at runtime.
        def freeze
          opts[:status_handler].freeze
          super
        end
      end

      module InstanceMethods
        private

        # If routing returns a response we have a handler for, call that handler.
        def _roda_after_20__status_handler(result)
          if result && (block = opts[:status_handler][result[0]]) && (v = result[2]).is_a?(Array) && v.empty?
            @_response.headers.clear
            result.replace(_call(&block))
          end
        end
      end
    end

    register_plugin(:status_handler, StatusHandler)
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
roda-3.16.0 lib/roda/plugins/status_handler.rb
roda-3.15.0 lib/roda/plugins/status_handler.rb
roda-3.14.1 lib/roda/plugins/status_handler.rb
roda-3.14.0 lib/roda/plugins/status_handler.rb
roda-3.13.0 lib/roda/plugins/status_handler.rb
roda-3.12.0 lib/roda/plugins/status_handler.rb