Skip to content

🐛 Locals with nil value removed before rendering partial #750

@pabvald

Description

@pabvald

nil is a completely valid value of every variable in both Ruby and Ruby on Rails (see RubyGuides) .

nil is a special Ruby object used to represent an “empty” or “default” value

However, turbo-rails removes now all locals that have a nil value. Why does turbo-rails have this inconsistent behaviour?

My code

  • Rails version: 8.0.2
  • turbo-rails version: 2.16.0

My broadcast_render_to with definition of locals:

# IntakeCase model
 broadcast_render_to(
        "intake_case:#{id}",
        partial: "intake_case/assessment",
        locals: {
          state: state,
          intake_case: self,
          question: last_question, # might be nil 
          replies: las_question&.replies
        }
      )

My partial, rendering an AssessmentComponent with all required arguments:

# _assessment.turbo_stream.erb
<%= turbo_stream.replace "target-tile-center" do %>
  <div id="target-tile-center">
    <%= render AssessmentComponent.new(
      intake_case: intake_case,
      question: question,
      replies: replies,
    ) %>
  </div>
<% end %>

My AssessmentComponent, where I handle the possibility of question being nil or "":

# assessment_component.html.erb
<%if question.blank?%>
      <div> 
            No question 
      </div>
<%else%>
       <div> 
            Other stuff showing replies
       </div> 
<%end>

Expected behaviour

The local variable last_question is available with value nil and _assessment.turbo_stream.html renders the AssessmentComponent passing question: nil:

# _assessment.turbo_stream.erb
<%= turbo_stream.replace "target-tile-center" do %>
  <div id="target-tile-center">
    <%= render AssessmentComponent.new(
      intake_case: intake_case,
      question: nil, # last_question == nil
      replies: replies,
    ) %>
  </div>
<% end %>

Then component then handles the question being nil or an empty string.

Actual behaviour

undefined local variable or method 'last_question' for an instance of #Class:0x000000032a50f320

The partial _assessment.turbo_stream.html cannot be rendered properly because the local variable last_question is no longer available.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions