Class: Krack::Endpoint

Inherits:
Object
  • Object
show all
Defined in:
lib/krack/endpoint.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env) ⇒ Endpoint

Returns a new instance of Endpoint.



5
6
7
8
9
10
# File 'lib/krack/endpoint.rb', line 5

def initialize(env)
  @env      = env
  @request  = Rack::Request.new(env)
  @response = Rack::Response.new([], 200, {"Content-Type" => "application/json"})
  @params   = env["krack.params"].merge(@request.params)
end

Instance Attribute Details

#envObject (readonly)

Returns the value of attribute env.



3
4
5
# File 'lib/krack/endpoint.rb', line 3

def env
  @env
end

#paramsObject (readonly)

Returns the value of attribute params.



3
4
5
# File 'lib/krack/endpoint.rb', line 3

def params
  @params
end

#requestObject (readonly)

Returns the value of attribute request.



3
4
5
# File 'lib/krack/endpoint.rb', line 3

def request
  @request
end

#responseObject (readonly)

Returns the value of attribute response.



3
4
5
# File 'lib/krack/endpoint.rb', line 3

def response
  @response
end

Class Method Details

.call(env) ⇒ Object



12
13
14
# File 'lib/krack/endpoint.rb', line 12

def self.call(env)
  new(env).call!
end

Instance Method Details

#call!Object



16
17
18
19
20
21
22
23
24
# File 'lib/krack/endpoint.rb', line 16

def call!
  data = begin
    respond_or_halt
  rescue
    on_error($!)
  end
  response.write(output(data))
  response.finish
end

#on_error(error) ⇒ Object



31
32
33
# File 'lib/krack/endpoint.rb', line 31

def on_error(error)
  on_halt(500)
end

#on_halt(halt) ⇒ Object



35
36
37
38
39
# File 'lib/krack/endpoint.rb', line 35

def on_halt(halt)
  e = Krack::Error.new(halt)
  response.status = e.status
  e.to_h
end

#output(data) ⇒ Object



41
42
43
# File 'lib/krack/endpoint.rb', line 41

def output(data)
  MultiJson.dump(data, :time_format => :ruby)
end

#respondObject



45
46
47
# File 'lib/krack/endpoint.rb', line 45

def respond
  raise "#respond method is not defined in #{self.class}"
end

#respond_or_haltObject



26
27
28
29
# File 'lib/krack/endpoint.rb', line 26

def respond_or_halt
  halt = catch(:halt) { return respond }
  on_halt(halt)
end