diff --git a/lib/ruby-handlebars.rb b/lib/ruby-handlebars.rb index ba24187..93fffba 100644 --- a/lib/ruby-handlebars.rb +++ b/lib/ruby-handlebars.rb @@ -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) diff --git a/lib/ruby-handlebars/context.rb b/lib/ruby-handlebars/context.rb index 73b99e7..aa61cdc 100644 --- a/lib/ruby-handlebars/context.rb +++ b/lib/ruby-handlebars/context.rb @@ -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) @@ -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 diff --git a/lib/ruby-handlebars/template.rb b/lib/ruby-handlebars/template.rb index 25020b7..b5d485a 100644 --- a/lib/ruby-handlebars/template.rb +++ b/lib/ruby-handlebars/template.rb @@ -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 diff --git a/spec/handlebars_spec.rb b/spec/handlebars_spec.rb index 91c3c8a..82636a3 100644 --- a/spec/handlebars_spec.rb +++ b/spec/handlebars_spec.rb @@ -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 @@ -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") @@ -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]")