Class: LeanWeb::Controller
- Inherits:
-
Object
- Object
- LeanWeb::Controller
- 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
-
#base_url(path = '.') ⇒ Object
Relative route to path from public directory considering current route.
-
#create_template(path, options = nil) ⇒ String
Template rendering engine.
-
#initialize(route, request = nil) ⇒ Controller
constructor
A new instance of Controller.
-
#params ⇒ Object
Request params.
-
#render_response(path, content_type = nil) { ... } ⇒ Rack::Request#finish
Render magic.
Constructor Details
#initialize(route, request = nil) ⇒ Controller
Returns a new instance of Controller.
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.
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.
54 55 56 57 58 59 |
# File 'lib/leanweb/controller.rb', line 54 def create_template(path, = nil) path = absolute_view_path(path) ext = File.extname(path)[1..] || '' ext = 'erb' unless Tilt.registered?(ext) Tilt[ext].new(path, 1, || template_defaults[ext] || {}) end |
#params ⇒ Object
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.
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 |