Class: NuHttp::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/nuhttp/context.rb

Instance Method Summary collapse

Constructor Details

#initialize(req:, route:) ⇒ Context

Returns a new instance of Context.



7
8
9
10
11
12
13
# File 'lib/nuhttp/context.rb', line 7

def initialize(req:, route:)
  @req = req
  @res = Response.new

  @herb_renderer_loaded = false
  @json_loaded = false
end

Instance Method Details

#body(str) ⇒ Object

TODO: take IO and allow streaming



32
33
34
# File 'lib/nuhttp/context.rb', line 32

def body(str)
  res.body = str
end

#erb(template_path, locals = {}) ⇒ Object

Render a template using the provided renderer and set as HTML response. : (String, ?Hash[Symbol, untyped]) -> void



46
47
48
49
50
51
# File 'lib/nuhttp/context.rb', line 46

def erb(template_path, locals = {})
  require_relative './herb_renderer' if !@herb_renderer_loaded

  rendered = HerbRenderer.new.render(template_path, locals)
  html(rendered)
end

#header(name, value) ⇒ Object



27
28
29
# File 'lib/nuhttp/context.rb', line 27

def header(name, value)
  res.headers[name] = value
end

#html(str) ⇒ Object

Set response to HTML str. Content-Type header will be set to text/html; charset=utf-8. : (String) -> void



39
40
41
42
# File 'lib/nuhttp/context.rb', line 39

def html(str)
  res.headers['Content-Type'] = 'text/html; charset=utf-8'
  res.body = str
end

#json(obj) ⇒ Object

Set response to the JSON representation of obj. Content-Type header will be set to application/json. : (Object) -> void



64
65
66
67
68
69
# File 'lib/nuhttp/context.rb', line 64

def json(obj)
  require 'json' if !@json_loaded

  res.headers['Content-Type'] = 'application/json'
  res.body = JSON.generate(obj)
end

#reqObject



15
16
17
# File 'lib/nuhttp/context.rb', line 15

def req #: Request[ParamsT]
  @req
end

#resObject

: Response



19
20
21
# File 'lib/nuhttp/context.rb', line 19

def res #: Response
  @res
end

#status(code) ⇒ Object



23
24
25
# File 'lib/nuhttp/context.rb', line 23

def status(code)
  res.status = code
end

#text(str) ⇒ Object

Set response to plain text str. Content-Type header will be set to text/plain; charset=utf-8. : (String) -> void



56
57
58
59
# File 'lib/nuhttp/context.rb', line 56

def text(str)
  res.headers['Content-Type'] = 'text/plain; charset=utf-8'
  res.body = str
end