Class: VizBuilder::TemplateContext

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

Overview

Templates are rendered using this class. Templates are effectively treated as methods of this class when rendered. So any methods or attributes exposed in this class are available inside of templates.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ TemplateContext

Returns a new instance of TemplateContext.



289
290
291
292
293
294
295
296
297
298
# File 'lib/vizbuilder.rb', line 289

def initialize(config)
  # Config is our Builder config object
  @config_obj = config
  # Page is a hash representing the page. Is the same as whats in sitemap
  # for a given page path
  @page = {}
  # Locals is a hash thats used to resolve missing methods, making them
  # seem like local variables
  @locals = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym) ⇒ Object

Looks for an invoked method name in locals then in config, so locals and config vars can be used as if they’re local vars in the template



326
327
328
329
330
# File 'lib/vizbuilder.rb', line 326

def method_missing(sym)
  return @locals[sym] if @locals.key?(sym)
  return config[sym] if config.key?(sym)
  super
end

Instance Attribute Details

#pageObject

Returns the value of attribute page.



286
287
288
# File 'lib/vizbuilder.rb', line 286

def page
  @page
end

Instance Method Details

#include_file(filepath) ⇒ Object

Load the content of a pre-rendered file and return it



312
313
314
315
316
317
318
319
320
321
322
# File 'lib/vizbuilder.rb', line 312

def include_file(filepath)
  content = File.read(filepath)
  mime = MimeMagic.by_path(filepath)
  if mime.text?
    return content
  elsif mime.image?
    return Base64.strict_encode64(content)
  else
    raise "File '${filepath}' of type '${mime}' can't be included as text"
  end
end

#render(template_path, locals = {}) ⇒ Object

Render any given template and return as a string. Can be used to render partials.



302
303
304
305
306
307
308
309
# File 'lib/vizbuilder.rb', line 302

def render(template_path, locals = {})
  old_locals = @locals
  @locals = locals.with_indifferent_access
  erb = VizBuilder.erb_new(template_path)
  ret = erb.result(binding)
  @locals = old_locals
  ret
end

#respond_to_missing?(sym) ⇒ Boolean

Returns:

  • (Boolean)


332
333
334
# File 'lib/vizbuilder.rb', line 332

def respond_to_missing?(sym, *)
  @locals.key?(sym) || config.key?(sym) || super
end