Module: Sidewalk::ControllerMixins::ViewTemplates
- Defined in:
- lib/sidewalk/controller_mixins/view_templates.rb
Overview
Mixin for supporting view templates.
This provides #render, which looks in views/ for a suitably named file, such as +views/hello.erb’ for HelloController.
See TemplateHandlers::Base for a list of supported formats.
Class Method Summary collapse
-
.handler(type) ⇒ Class
What handler to use for a given extension.
-
.template(path) ⇒ TemplateHandlers::Base
Get a TemplateHandlers::Base instance for a given path.
-
.templates ⇒ Hash
A
Hash
of all available templates. -
.view_path ⇒ Object
The local path where templates are stored.
Instance Method Summary collapse
-
#render(view = nil) ⇒ String
Return the result of rendering a view.
Class Method Details
.handler(type) ⇒ Class
What handler to use for a given extension.
33 34 35 36 37 38 39 40 41 |
# File 'lib/sidewalk/controller_mixins/view_templates.rb', line 33 def self.handler type name = type.camelize + 'Handler' begin Sidewalk::TemplateHandlers.const_get(name) rescue NameError require ('Sidewalk::TemplateHandlers::' + name).underscore Sidewalk::TemplateHandlers.const_get(name) end end |
.template(path) ⇒ TemplateHandlers::Base
Get a TemplateHandlers::Base instance for a given path.
46 47 48 |
# File 'lib/sidewalk/controller_mixins/view_templates.rb', line 46 def self.template path self.templates[path.to_s] end |
.templates ⇒ Hash
A Hash
of all available templates.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/sidewalk/controller_mixins/view_templates.rb', line 53 def self.templates return @templates if @templates @templates = {} Dir.glob( self.view_path + '/**/*' ).each do |path| # eg '/path/views/foo/bar.erb' # eg '.erb' ext = File.extname(path) # eg 'erb' type = ext[1..-1] handler = self.handler(type) # eg 'foo/bar.erb' relative = path.sub(self.view_path + '/', '') # convert to 'foo/bar' parts = relative.split('/') parts[-1] = File.basename(path, ext) key = parts.join('/') @templates[key] = handler.new(path) end @templates end |
.view_path ⇒ Object
The local path where templates are stored
This will usually be the views/ subdirectory of the application root.
18 19 20 21 22 23 |
# File 'lib/sidewalk/controller_mixins/view_templates.rb', line 18 def self.view_path @templates_path ||= File.join( Sidewalk::Application.local_root, 'views' ) end |
Instance Method Details
#render(view = nil) ⇒ String
Return the result of rendering a view.
84 85 86 87 88 89 90 91 |
# File 'lib/sidewalk/controller_mixins/view_templates.rb', line 84 def render view = nil view ||= self.class.name.sub('Controller', '').underscore template = Sidewalk::ControllerMixins::ViewTemplates.template(view) if template.nil? raise ScriptError.new("Unable to find a template for #{view}") end template.render(self) end |