Rails: undefined local variable or method `view_context' for #<ActionView::Base:0x007f8091a1cb88>

136 Views Asked by At

I have a helper called FeaturesHelper that has data about some features:

feature_info = [
    {features:
        [
            {
                description: "This is a #{view_context.link_to "link!", "https://www.example.com", target: :_blank, class: "pink-link"}", 
            }
        ]
}, ...]

I then have a partial that uses feature_info:

<% feature_info.each do |info|%>    
    <% info[:features].each do |feature| %>
        <%= feature[:description].html_safe %>                               
    <% end %>
<% end %>    
  

I then render the partial in a view:

<%= render partial: "partial_name" %>

This leads to an error with the stack trace pointing no my FeaturesHelper:

undefined local variable or method `view_context' for #ActionView::Base:0x007f80a6cdcf20

1

There are 1 best solutions below

0
Helio Borges On

view_context is not visible there, you'll need to pass it as a parameter.

module FeaturesHelper
  def self.feature_info(view_context)
    [
      {
        features: [
          {
            description: "This is a #{view_context.link_to 'link!', 'https://www.example.com', target: :_blank, class: 'pink-link'}",
          }
        ]
      }, # ...
    ]
  end
end

on your view:

<% feature_info = FeaturesHelper.feature_info(view_context) %>

<% feature_info.each do |info| %>
  <% info[:features].each do |feature| %>
    <%= feature[:description].html_safe %>
  <% end %>
<% end %>