Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/ruby-handlebars.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ def initialize()
set_escaper
end

def compile(template)
Template.new(self, template_to_ast(template))
def compile(template, **options)
Template.new(self, template_to_ast(template), **options)
end

def register_helper(name, &fn)
Expand Down
8 changes: 7 additions & 1 deletion lib/ruby-handlebars/context.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
module Handlebars
class Context
def initialize(hbs, data)
class AttributeNotFoundError < StandardError
end

def initialize(hbs, data, **options)
@hbs = hbs
@data = data
@options = options || {}
end

def get(path)
Expand Down Expand Up @@ -75,6 +79,8 @@ def get_attribute(item, attribute)
if item.respond_to?(sym_attr)
return item.send(sym_attr)
end

raise AttributeNotFoundError.new("\"#{attribute}\" not found in #{item}") if @options[:strict]
end
end
end
5 changes: 3 additions & 2 deletions lib/ruby-handlebars/template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

module Handlebars
class Template
def initialize(hbs, ast)
def initialize(hbs, ast, **options)
@hbs = hbs
@ast = ast
@options = options || {}
end

def call(args = nil)
ctx = Context.new(@hbs, args)
ctx = Context.new(@hbs, args, **@options)

@ast.eval(ctx)
end
Expand Down
12 changes: 9 additions & 3 deletions spec/handlebars_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
describe Handlebars::Handlebars do
let(:hbs) {Handlebars::Handlebars.new}

def evaluate(template, args = {})
hbs.compile(template).call(args)
def evaluate(template, args = {}, **compiling_options)
hbs.compile(template, **compiling_options).call(args)
end

context 'evaluating' do
Expand Down Expand Up @@ -51,6 +51,12 @@ def evaluate(template, args = {})
expect(evaluate('Hello {{first-name}}', double("first-name": 'world'))).to eq('Hello world')
end

context 'strict mode' do
it 'raises an error' do
expect{evaluate('Hello {{you}}', {}, strict: true)}.to raise_error(Handlebars::Context::AttributeNotFoundError)
end
end

context 'partials' do
it 'simple' do
hbs.register_partial('plic', "Plic")
Expand All @@ -71,7 +77,7 @@ def evaluate(template, args = {})
hbs.register_partial('brackets', "[{{name}}]")
expect(evaluate("Hello {{> brackets}}", {name: 'world'})).to eq("Hello [world]")
end

it 'with a string argument' do
hbs.register_partial('with_args', "[{{name}}]")
expect(evaluate("Hello {{> with_args name='jon'}}")).to eq("Hello [jon]")
Expand Down