gazay / gon

Your Rails variables in your JS
MIT License
3.05k stars 184 forks source link

jbuilder parsing ignores conditionals when finding partials #230

Open corporealfunk opened 7 years ago

corporealfunk commented 7 years ago

When we have a jbuilder template like this:

json.name = @my_object.name

if @my_object.child
  json.child do
    json.partial! 'children/show', :child => @my_object.child
  end
else
  json.child = nil
end

This is how we might nest or include parent/child relationships in jbuilder, by utilizing a jbuilder partial for the child.

It is clear here that if @my_object.child is falsey, we don't want the partial to be parsed. Normal jbuilder template parsing would not attempt to parse the 'children/show' partial.

However, the gon jbuilder module does a simple text scan of each line of the the jbuilder template looking for lines that contain the word =~ 'partial', and then it actually attempts to create output from that partial, regardless of where that partial may sit in a conditional. In cases where the partial should not be parsed, there are probably good reasons for this, and attempting to parse it might cause errors (especially "xyz" for nil:NilClass errors), since the partial is trying to access methods on the @my_object.child variable, which is nil, or at least not an object or hash.