Class: Corrupt::Template

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

Overview

This class is responsible for setting view variables and rendering a template file.

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Template

TODO: Maybe add a layout option?



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/corrupt/template.rb', line 6

def initialize(file)
  # FIXME: This is rather ugly; maybe raise a 'view not found' exception?
  if file
    view_path = File.join(Corrupt.app_root, 'views')
    @file = File.join(view_path, file)
  else
    @file = File.join(Corrupt.root, 'public', 'index.haml')
  end
  @layout = File.join(Corrupt.app_root, 'views', 'layouts', 'application.haml')
  @variables = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object

This captures any key/value pair called on the Template object and saves them for later use in the rendered template file.



20
21
22
23
24
# File 'lib/corrupt/template.rb', line 20

def method_missing(name, *args)
  # Trip the trailing '='
  name = name.to_s.gsub!(/[=]$/, '')
  @variables[name] = args
end

Instance Method Details

#renderObject

Renders the file with any variables and returns an HTML string. Wraps the file inside of the layout.

Currently only supports Haml templates.



30
31
32
33
34
35
36
# File 'lib/corrupt/template.rb', line 30

def render
  wrap = Haml::Engine.new(File.read(@layout))
  wrap.render do
    engine = Haml::Engine.new(File.read(@file))
    engine.render(Object.new, @variables)
  end
end