Sha256: 49a26c0cb7436d7d17af1aa047b69946c25caafb48eeecc0a5e85921d1841555

Contents?: true

Size: 1.38 KB

Versions: 3

Compression:

Stored size: 1.38 KB

Contents

# frozen_string_literal: true

module Wayfarer
  module Middleware
    class Router
      extend Base

      module API
        def self.included(base)
          base.extend(ClassMethods)
          base.include(InstanceMethods)
        end

        module ClassMethods
          def router
            # TODO: Use cattr_accessor
            @router ||= Wayfarer::Routing::Router.new
          end

          def route(&block)
            router.draw(&block) if block_given?
          end

          def steer(&block)
            define_method(:steer) { block.call(task) }
          end
        end

        module InstanceMethods
          def steer
            []
          end

          def params
            task.metadata.params
          end
        end
      end

      def call(task)
        controller = task.metadata.controller
        # TODO: The router has to be cloned because it's not thread-safe
        router = controller.class.router.clone
        url = Addressable::URI.parse(task.url)

        case result = router.invoke(url, controller.steer)
        when Routing::Result::Mismatch
          return
        when Routing::Result::Match
          task.metadata.action = result.action
          task.metadata.params ||= ActiveSupport::HashWithIndifferentAccess.new
          task.metadata.params.merge!(result.params)
        end

        yield if block_given?
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
wayfarer-0.4.6 lib/wayfarer/middleware/router.rb
wayfarer-0.4.5 lib/wayfarer/middleware/router.rb
wayfarer-0.4.4 lib/wayfarer/middleware/router.rb