Class: LeanWeb::Controller

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

Overview

Controller is a base controller with @route, @request and @response private attributes that will be shared with your views when you #render_response.

Even if you don't #render_response, you can use the .finish method from Rack::Response on @response to return a proper Rack response.

Instance Method Summary collapse

Constructor Details

#initialize(route, request = nil) ⇒ Controller

Returns a new instance of Controller.

Parameters:

  • route (Route)
  • request (Rack::Request) (defaults to: nil)


23
24
25
26
27
# File 'lib/leanweb/controller.rb', line 23

def initialize(route, request = nil)
  @route = route
  @request = request
  @response = Rack::Response.new(nil, 200)
end

Instance Method Details

#base_url(path = '.') ⇒ Object

Relative route to path from public directory considering current route.

Parameters:

  • path (String) (defaults to: '.')

    path from public directory, never begins with /.



64
65
66
67
68
69
70
# File 'lib/leanweb/controller.rb', line 64

def base_url(path = '.')
  @base_url ||= @route.str_path[1..]
    .sub(%r{[^/]*$}, '')
    .gsub(%r{[^/]+}, '..')

  @base_url + path
end

#create_template(path, options = nil) ⇒ String

Template rendering engine. Useful for partials / nested views.

Parameters:

  • path (String)

    Same as on #render_response.

  • options (Hash) (defaults to: nil)

    Options for Tilt, defaults to template_defaults[extension].

Returns:



54
55
56
57
58
59
# File 'lib/leanweb/controller.rb', line 54

def create_template(path, options = nil)
  path = absolute_view_path(path)
  ext = File.extname(path)[1..] || ''
  ext = 'erb' unless Tilt.registered?(ext)
  Tilt[ext].new(path, 1, options || template_defaults[ext] || {})
end

#paramsObject

Request params.



73
74
75
# File 'lib/leanweb/controller.rb', line 73

def params
  @request.params
end

#render_response(path, content_type = nil) { ... } ⇒ Rack::Request#finish

Render magic. Supports every file extension that Tilt supports. Defaults to ERB when file extension is unknown.

Parameters:

  • path (String)

    Might be an absolute path or a relative path to src/views/.

  • content_type (String) (defaults to: nil)

    Defaults to the proper Content-Type for file extension, text/plain on unknown files.

Yields:

  • Optionally pass a block for nested rendering.

Returns:

  • (Rack::Request#finish)

    A valid Rack response.



38
39
40
41
42
43
44
45
46
# File 'lib/leanweb/controller.rb', line 38

def render_response(path, content_type = nil, &block)
  template = create_template(path)
  @response.set_header(
    'Content-Type',
    content_type || template.class.[:mime_type] || 'text/plain'
  )
  @response.write(template.render(self){ block.call if block_given? })
  @response.finish
end