Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make render_in_view_context forward its args to the block #1616

Merged
merged 4 commits into from
Jan 3, 2023

Conversation

camertron
Copy link
Contributor

@camertron camertron commented Dec 21, 2022

What are you trying to accomplish?

Our render_in_view_context test helper uses instance_exec to evaluate the given block in the view context. Since instance_exec changes the value of self, instance variables, methods, etc defined in the caller's context are not available inside the block, which can be pretty confusing. For example, consider this test:

class MyTest < Minitest::Test
  def setup
    @user = create(:user)
  end

  def test_my_component
    render_in_view_context do
      render(MyComponent.new(@user))
    end
  end
end

As a direct result of using instance_exec, @user will be nil inside the block.

What approach did you choose and why?

Presumably to provide an escape hatch for this problem, instance_exec forwards its arguments when calling the block. This PR modifies render_in_view_context to forward its arguments to instance_exec, so this is now possible:

class MyTest < Minitest::Test
  def setup
    @user = create(:user)
  end

  def test_my_component
    render_in_view_context(@user) do |user|
      render(MyComponent.new(user))
    end
  end
end

@camertron camertron marked this pull request as ready for review December 22, 2022 00:29
.standard.yml Show resolved Hide resolved
Copy link
Member

@joelhawksley joelhawksley left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense to me. Mind adding a regression test?

Copy link
Contributor

@BlakeWilliams BlakeWilliams left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, I really like this solution. 👍

@camertron camertron merged commit 66b443a into main Jan 3, 2023
@camertron camertron deleted the render_in_view_context_arg_forwarding branch January 3, 2023 21:23
claudiob pushed a commit to claudiob/view_component that referenced this pull request Dec 22, 2023
claudiob pushed a commit to claudiob/view_component that referenced this pull request Jan 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants