Albert Català
Albert Català

Reputation: 2044

is it a bad practice to use instance variable in helper?

I've been refactoring an old project, and I'm seeing some helper methods difficult to test, because of existence of instance variables inside helpers.

What is the best practice to achieve this? pass these instance variables to the helpers as parameters...

in the test I can do things like this, but it seems quite weird

  it 'returns family and categoy names' do
    @category = instance_double(Category, name: 'category_name')
    expect(helper.meta_description_home_products).to eq(
      'blabla - categoria'
    )
  end

As an example of controller view and helper:

class HomeController < BaseController
  @family = ...
  @category = ...
  @products = ...
end

and in views

<% @products.each ...
  ...
  my_helper
...

and in helpers:

  module ApplicationHelper
   def my_helper
     ...
     desctiption = 'blabla' if @category.name == 'blabla'

Thanks

Upvotes: 3

Views: 2672

Answers (1)

ekampp
ekampp

Reputation: 1959

I wouldn't do it. It tightly couples your controller and view layer making future features, rewrite, and refactoring hard.

It also makes reading, testing and bug fixing both your controller and your view hard.

Separation of concern and responsibility are something to consider. Keeping those do help on long lived projects.

Upvotes: 2

Related Questions