class Raamen::ControllerBase

Attributes

already_built_response[RW]
authenticity_token[RW]
flash[R]
params[R]
req[R]
res[R]
session[R]

Public Class Methods

new(req, res, route_params = {}) click to toggle source
# File lib/raamen/controller_base.rb, line 13
def initialize(req, res, route_params = {})
  @req = req
  @res = res
  @params = route_params.merge(req.params)
  @session = Session.new(req)
  @flash = Flash.new(req)
  @already_built_response = false
  @authenticity_token = generate_authenticity_token
  @@protect_from_forgery ||= false
end
protect_from_forgery() click to toggle source
# File lib/raamen/controller_base.rb, line 74
def self.protect_from_forgery
  @@protect_from_forgery = true
end

Public Instance Methods

already_built_response?() click to toggle source
# File lib/raamen/controller_base.rb, line 24
def already_built_response?
  self.already_built_response
end
form_authenticity_token() click to toggle source
# File lib/raamen/controller_base.rb, line 66
def form_authenticity_token
  self.res.set_cookie(
    "authenticity_token",
    {path: "/", value: self.authenticity_token}
  )
  self.authenticity_token
end
invoke_action(name) click to toggle source
# File lib/raamen/controller_base.rb, line 58
def invoke_action(name)
  if @@protect_from_forgery && self.req.request_method != "GET"
    check_authenticity_token
  end
  self.send(name)
  render(name) unless already_built_response?
end
redirect_to(url) click to toggle source
# File lib/raamen/controller_base.rb, line 28
def redirect_to(url)
  raise "double render" if already_built_response?
  self.res["location"] = url
  self.res.status = 302
  self.session.store_session(res)
  self.flash.store_flash(res)
  self.already_built_response = true
end
render(template_name) click to toggle source
# File lib/raamen/controller_base.rb, line 46
def render(template_name)
  template_path = File.join(
    Dir.pwd,
    "app",
    "views",
    "#{self.class.name.underscore}",
    "#{template_name}.html.erb"
    )
  template_content = File.read(template_path)
  render_content(ERB.new(template_content).result(binding), "text/html")
end
render_content(content, content_type) click to toggle source
# File lib/raamen/controller_base.rb, line 37
def render_content(content, content_type)
  raise "double render" if already_built_response?
  self.res["Content-Type"] = content_type
  self.res.write(content)
  self.session.store_session(res)
  self.flash.store_flash(res)
  self.already_built_response = true
end

Private Instance Methods

check_authenticity_token() click to toggle source
# File lib/raamen/controller_base.rb, line 84
def check_authenticity_token
  cookie = self.req.cookies["authenticity_token"]
  unless cookie && cookie == params["authenticity_token"]
    raise "Invalid authenticity token"
  end
end
generate_authenticity_token() click to toggle source
# File lib/raamen/controller_base.rb, line 80
def generate_authenticity_token
  SecureRandom.urlsafe_base64(16)
end