Class: Acrylic::Cascade

Inherits:
Object show all
Defined in:
lib/cascade.rb,
lib/cascade/errors.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.handle(req) ⇒ Object

returns a response based on the defined routes.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/cascade.rb', line 44

def self.handle req
    headers = {}

    # loop through all the routes to find a final one
    Acrylic::ROUTES.each do |route|
        next unless route.match? req
        
        res = route.call req
        res = case true
            when (res.is_a? Rack::Response) then res
            when (res.respond_to? :to_h)    then res.to_h
            when (res.is_a? Integer)        then Rack::Response.new nil, res
            when (res.is_a? String)         then Rack::Response.new      res
            when (res.nil?)                 then next
            else                                 raise TypeError
        end

        # if the returned route has a body, return it. else, add its headers to the existing response.
        if res.is_a? Rack::Response
            res.headers.merge! headers
            return res
        elsif res.is_a? Hash
            headers.merge! res
        end
    end

    # if no route returned a response, return a 404
    return Rack::Response.new nil, 404, headers
end

.serve(env) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/cascade.rb', line 75

def self.serve env
    req = Rack::Request.new env

    res = handle req
    # apply a series of transformations to the response
    # unfortunately since Response is immutable we have to make a copy
        # 1. if res is an error code, transform it into a full response with cascade/errors
        body = res.body.fallback "" # (error_page res.status, req)
          
        # 2. transform every header key of res into a string
        headers = res.headers.map do |k, v| [k.to_s, v] end.to_h
    
    p body
    Rack::Response.new body, res.status, headers
end

Instance Method Details

#default_error_body(code, req) ⇒ Object



25
26
27
# File 'lib/cascade/errors.rb', line 25

def default_error_body code, req
    
end

#error_body(code, req) ⇒ Object

returns body of response.



30
31
32
33
34
35
36
# File 'lib/cascade/errors.rb', line 30

def error_body code, req
    route = ERROR_ROUTES.find do |route| route.match? code, req end
    body = if route.nil? then default_error_page code, req else route.call req end
    
    raise TypeError("return value of error_handler body must be a string") unless body.is_a? String
    body
end