Class: HtmlMockup::Template

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, options = {}) ⇒ Template

Returns a new instance of Template.

Parameters:

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :source_path (String, Pathname)

    The path to the source of the template being processed

  • :layouts_path (String, Pathname)

    The path to where all layouts reside

  • :partials_path (String, Pathname)

    The path to where all partials reside



34
35
36
37
38
39
40
41
42
43
# File 'lib/html_mockup/template.rb', line 34

def initialize(source, options = {})
  @options = options
  self.source_path = options[:source_path]
  self.data, self.source = extract_front_matter(source)
  self.template = Tilt.new(self.source_path.to_s){ self.source }
  
  if self.data[:layout] && layout_template_path = self.find_template(self.data[:layout], :layouts_path)
    @layout_template = Tilt.new(layout_template_path.to_s)
  end
end

Instance Attribute Details

#dataObject

Store the frontmatter



15
16
17
# File 'lib/html_mockup/template.rb', line 15

def data
  @data
end

#sourceObject

The source



12
13
14
# File 'lib/html_mockup/template.rb', line 12

def source
  @source
end

#source_pathObject

The path to the source file for this template



21
22
23
# File 'lib/html_mockup/template.rb', line 21

def source_path
  @source_path
end

#templateObject

The actual Tilt template



18
19
20
# File 'lib/html_mockup/template.rb', line 18

def template
  @template
end

Class Method Details

.open(path, options = {}) ⇒ Object



24
25
26
27
# File 'lib/html_mockup/template.rb', line 24

def open(path, options = {})
  raise "Unknown file #{path}" unless File.exist?(path)
  self.new(File.read(path), options.update(:source_path => path))
end

Instance Method Details

#find_template(name, path_type) ⇒ Object

Raises:

  • (ArgumentError)


58
59
60
61
62
63
64
65
# File 'lib/html_mockup/template.rb', line 58

def find_template(name, path_type)
  raise(ArgumentError, "path_type must be one of :partials_path or :layouts_path") unless [:partials_path, :layouts_path].include?(path_type)

  @resolvers ||= {}        
  @resolvers[path_type] ||= Resolver.new(@options[path_type])
  
  @resolvers[path_type].url_to_path(name)
end

#render(env = {}) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/html_mockup/template.rb', line 45

def render(env = {})
  context = TemplateContext.new(self, env)
  locals = {:document => OpenStruct.new(self.data)}
  
  if @layout_template
    @layout_template.render(context, locals) do
      self.template.render(context, locals)
    end
  else
    self.template.render(context, locals)
  end
end