Class: Puffs::ControllerBase

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(req, res, route_params = {}) ⇒ ControllerBase

Setup the controller



13
14
15
16
# File 'lib/controller_base.rb', line 13

def initialize(req, res, route_params = {})
  @req, @res = req, res
  @params = req.params.merge(route_params)
end

Instance Attribute Details

#paramsObject (readonly)

Returns the value of attribute params.



10
11
12
# File 'lib/controller_base.rb', line 10

def params
  @params
end

#reqObject (readonly)

Returns the value of attribute req.



10
11
12
# File 'lib/controller_base.rb', line 10

def req
  @req
end

#resObject (readonly)

Returns the value of attribute res.



10
11
12
# File 'lib/controller_base.rb', line 10

def res
  @res
end

Instance Method Details

#already_built_response?Boolean

Helper method to alias @already_built_response

Returns:

  • (Boolean)


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

def already_built_response?
  @already_built_response ||= false
end

#controller_nameObject



68
69
70
# File 'lib/controller_base.rb', line 68

def controller_name
  self.class.name.underscore
end

#invoke_action(name) ⇒ Object

use this with the router to call action_name (:index, :show, :create…)



63
64
65
66
# File 'lib/controller_base.rb', line 63

def invoke_action(name)
  send(name)
  render(name) unless already_built_response?
end

#redirect_to(url) ⇒ Object

Set the response status code and header

Raises:



24
25
26
27
28
29
30
# File 'lib/controller_base.rb', line 24

def redirect_to(url)
  raise DoubleRenderError if already_built_response?
  res.header['location'] = url
  res.status = 302
  @already_built_response = true
  session.store_session(res)
end

#render(template_name) ⇒ Object

use ERB and binding to evaluate templates pass the rendered html to render_content



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/controller_base.rb', line 45

def render(template_name)
  body_string = ''
  File.open("./app/views/#{controller_name}/#{template_name}.html.erb", 'r') do |f|
    f.each_line do |line|
      body_string += line
    end
  end

  content = ERB.new(body_string).result(binding)
  render_content(content, 'text/html')
end

#render_content(content, content_type) ⇒ Object

Populate the response with content. Set the response’s content type to the given type. Raise an error if the developer tries to double render.

Raises:



35
36
37
38
39
40
41
# File 'lib/controller_base.rb', line 35

def render_content(content, content_type)
  raise DoubleRenderError if already_built_response?
  res['Content-Type'] = content_type
  res.body = [content]
  @already_built_response = true
  session.store_session(res)
end

#sessionObject

method exposing a ‘Session` object



58
59
60
# File 'lib/controller_base.rb', line 58

def session
  @session ||= Puffs::Session.new(req)
end