Sha256: 89dd919885e92109172fd423eae07662e9050bb22c37d7e7d52e8abbe9db0a6d

Contents?: true

Size: 1.54 KB

Versions: 13

Compression:

Stored size: 1.54 KB

Contents

require 'volt/server/rack/http_response_header'
require 'volt/server/rack/http_response_renderer'

module Volt
  # Allow you to create controllers that act as http endpoints
  class HttpController
    attr_accessor :response_body
    attr_reader :params, :response_headers, :request

    # Initialzed with the params parsed from the route and the HttpRequest
    def initialize(params, request)
      @response_headers = HttpResponseHeader.new
      @response_body = []
      @request = request
      @params = Volt::Model.new(params.symbolize_keys.merge(request.params))
    end

    def perform(action)
      # TODO: before actions
      send(action.to_sym)
      # TODO: after actions / around actions
      respond
    end

    private

    def store
      $page.store
    end

    def head(status, additional_headers = {})
      @response_status = status
      response_headers.merge!(additional_headers)
    end

    def redirect_to(target, status = :found)
      head(status, location: target)
    end

    def render(content)
      status = content.delete(:status) || :ok
      body, additional_headers = HttpResponseRenderer.new.render(content)
      head(status, additional_headers)
      response_body << body
    end

    def respond
      Rack::Response.new(response_body, response_status, response_headers)
    end

    # Get the http status code as integer
    def response_status
      if @response_status.is_a?(Symbol)
        Rack::Utils::SYMBOL_TO_STATUS_CODE[@response_status]
      else
        @response_status.try(:to_i) || 200
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
volt-0.9.3.pre1 lib/volt/controllers/http_controller.rb
volt-0.9.2 lib/volt/controllers/http_controller.rb
volt-0.9.1 lib/volt/controllers/http_controller.rb
volt-0.9.1.pre5 lib/volt/controllers/http_controller.rb
volt-0.9.1.pre4 lib/volt/controllers/http_controller.rb
volt-0.9.1.pre3 lib/volt/controllers/http_controller.rb
volt-0.9.1.pre2 lib/volt/controllers/http_controller.rb
volt-0.9.1.pre1 lib/volt/controllers/http_controller.rb
volt-0.9.0 lib/volt/controllers/http_controller.rb
volt-0.9.0.pre7 lib/volt/controllers/http_controller.rb
volt-0.9.0.pre6 lib/volt/controllers/http_controller.rb
volt-0.9.0.pre5 lib/volt/controllers/http_controller.rb
volt-0.9.0.pre4 lib/volt/controllers/http_controller.rb