Class: HandlebarsExec::Context

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeContext

Returns a new instance of Context.



8
9
10
11
12
# File 'lib/handlebars_exec/context.rb', line 8

def initialize
  @sources= []
  @_handlebars_source = File.read Handlebars::Source.bundled_path
  @context = generate_context
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



7
8
9
# File 'lib/handlebars_exec/context.rb', line 7

def context
  @context
end

Instance Method Details

#add_file_to_context(file) ⇒ Object Also known as: register_helper_file, register_partial_file



23
24
25
# File 'lib/handlebars_exec/context.rb', line 23

def add_file_to_context file
  add_to_context File.read(file)
end

#add_to_context(str) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/handlebars_exec/context.rb', line 40

def add_to_context str
  @sources.push (str)
  if context_preserved_between_calls?
    context.eval("(function(){ #{str}})()")
  else
    # ExecJS::ExternalRuntime::Context does not have a writable context
    # the only way to attach new variables and functions is to destroy the old context
    @context = generate_context
  end
end

#compile(template) ⇒ Object



19
20
21
# File 'lib/handlebars_exec/context.rb', line 19

def compile template
  HandlebarsExec::Template.new self.context,template 
end

#generate_contextObject



14
15
16
17
# File 'lib/handlebars_exec/context.rb', line 14

def generate_context
  sources = ([@_handlebars_source] + @sources).join("\n")
  ExecJS.compile(sources)
end

#register_helper(name, function) ⇒ Object



33
34
35
# File 'lib/handlebars_exec/context.rb', line 33

def register_helper name, function
  add_to_context "Handlebars.registerHelper('#{name}', #{function});"
end

#register_partial(name, partial) ⇒ Object



36
37
38
# File 'lib/handlebars_exec/context.rb', line 36

def register_partial name, partial 
  add_to_context "Handlebars.registerPartial('#{name}', #{partial.inspect});"
end