diff --git a/lib/rabl-fast-json/template.rb b/lib/rabl-fast-json/template.rb index b5e78e2..0a755ca 100644 --- a/lib/rabl-fast-json/template.rb +++ b/lib/rabl-fast-json/template.rb @@ -21,7 +21,7 @@ module RablFastJson def render_resource(data = nil, source = nil) data ||= @object source ||= @source - + source.inject({}) { |output, current| key, value = current @@ -61,9 +61,12 @@ module RablFastJson @context.respond_to?(name) ? @context.send(name, *args, &block) : super end - def partial(template_path, options = {}) - raise "No object was given to partial" if options[:object].blank? + def partial(template_path, options = {}) + raise "No object was given to partial" if options[:object].nil? object = options[:object] + + return [] if object.respond_to?(:empty?) && object.empty? + template = Library.instance.get(template_path) object.respond_to?(:each) ? template.render_collection(object) : template.render_resource(object) end diff --git a/test/compiled_template_test.rb b/test/compiled_template_test.rb index 983c363..96ea262 100644 --- a/test/compiled_template_test.rb +++ b/test/compiled_template_test.rb @@ -57,4 +57,35 @@ class TestCompiledTemplate < ActiveSupport::TestCase @template.source = { :name => [condition, proc] } assert_equal({}, @template.render) end + + test "partial should be evaluated at rendering time" do + # Set assigns + @context.stub(:instance_variable_get).with(:@_assigns).and_return({'user' => @data}) + @data.stub(:respond_to?).with(:empty?).and_return(false) + + # Stub Library#get + t = RablFastJson::CompiledTemplate.new + t.source, t.context = { :name => :name }, @context + RablFastJson::Library.reset_instance + RablFastJson::Library.instance.should_receive(:get).with('users/base').and_return(t) + + @template.data = false + @template.source = { :user => ->(s) { partial('users/base', :object => @user) } } + + assert_equal({ :user => { :name => 'foobar' } }, @template.render) + end + + test "partial with nil values should raise an error" do + @template.data = false + @template.source = { :user => ->(s) { partial('users/base') } } + + assert_raises(RuntimeError) { @template.render } + end + + test "partial with empty values should not raise an error" do + @template.data = false + @template.source = { :users => ->(s) { partial('users/base', :object => []) } } + + assert_equal({ :users => [] }, @template.render) + end end \ No newline at end of file