Enable :if condition for node properties
This commit is contained in:
parent
fbcbbd2328
commit
0c0ec9f23f
@ -47,7 +47,17 @@ module RablFastJson
|
||||
end
|
||||
|
||||
def node(name, options = {}, &block)
|
||||
@template[name] = block
|
||||
condition = options[:if]
|
||||
|
||||
if condition.present?
|
||||
if condition.is_a?(Proc)
|
||||
@template[name] = [condition, block]
|
||||
else
|
||||
@template[name] = block if condition
|
||||
end
|
||||
else
|
||||
@template[name] = block
|
||||
end
|
||||
end
|
||||
alias_method :code, :node
|
||||
|
||||
|
@ -30,6 +30,9 @@ module RablFastJson
|
||||
data.send(value) # attributes
|
||||
when Proc
|
||||
value.call(data) # node
|
||||
when Array # node with condition
|
||||
next output if !value.first.call(data)
|
||||
value.last.call(data)
|
||||
when Hash
|
||||
current_value = value.dup
|
||||
data_symbol = current_value.delete(:_data)
|
||||
|
@ -36,4 +36,24 @@ class TestCompiledTemplate < ActiveSupport::TestCase
|
||||
{ :uid => 2, :name => 'bar', :gender => 'female'}
|
||||
], @template.render)
|
||||
end
|
||||
|
||||
test "render object with node property" do
|
||||
proc = lambda { |object| object.sex }
|
||||
@template.source = { :sex => proc }
|
||||
assert_equal({ :sex => 'male' }, @template.render)
|
||||
end
|
||||
|
||||
test "render obejct with conditionnal node property" do
|
||||
condition = lambda { |u| u.name.present? }
|
||||
proc = lambda { |object| object.name }
|
||||
@template.source = { :name => [condition, proc] }
|
||||
assert_equal({ :name => 'foobar' }, @template.render)
|
||||
end
|
||||
|
||||
test "render node property with false condition" do
|
||||
condition = lambda { |u| false }
|
||||
proc = lambda { |object| object.name }
|
||||
@template.source = { :name => [condition, proc] }
|
||||
assert_equal({}, @template.render)
|
||||
end
|
||||
end
|
@ -122,4 +122,11 @@ class CompilerTest < ActiveSupport::TestCase
|
||||
assert_not_nil t.source[:foo]
|
||||
assert_instance_of Proc, t.source[:foo]
|
||||
end
|
||||
|
||||
test "node with condition are compiled as an array of procs" do
|
||||
t = @compiler.compile_source(%{ node(:foo, :if => lambda { |m| m.foo.present? }) do |m| m.foo end })
|
||||
assert_not_nil t.source[:foo]
|
||||
assert_instance_of Array, t.source[:foo]
|
||||
assert_equal 2, t.source[:foo].size
|
||||
end
|
||||
end
|
Loading…
Reference in New Issue
Block a user