Sha256: b2d03c8784ec1cc975ff8439e4fa00f507c9aa9ce025d26fff6c6a25c5cfb883

Contents?: true

Size: 1.21 KB

Versions: 2

Compression:

Stored size: 1.21 KB

Contents

require 'rack' if RUBY_PLATFORM != 'opal'
require 'volt'
require 'volt/router/routes'
require 'volt/server/rack/http_request'

module Volt
  # Rack middleware for HttpController
  class HttpResource
    def initialize(app, volt_app, router)
      @app = app
      @volt_app = volt_app
      @router = router
    end

    def call(env)
      request = HttpRequest.new(env)
      params = routes_match?(request)
      if params
        dispatch_to_controller(params, request)
      else
        @app.call env
      end
    end

    private

    def routes_match?(request)
      @router.url_to_params(request.method, request.path)
    end

    # Find the correct controller and call the correct action on it.
    # The controller name and actions need to be set as params for the
    # matching route
    def dispatch_to_controller(params, request)
      namespace = params[:component] || 'main'

      controller_name = params[:controller] + '_controller'
      action = params[:action]

      namespace_module = Object.const_get(namespace.camelize.to_sym)
      klass = namespace_module.const_get(controller_name.camelize.to_sym)
      controller = klass.new(@volt_app, params, request)
      controller.perform(action)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
volt-0.9.3.pre3 lib/volt/server/rack/http_resource.rb
volt-0.9.3.pre2 lib/volt/server/rack/http_resource.rb