简体   繁体   English

在 helper 中使用实例变量是一种不好的做法吗?

[英]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谢谢

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.保留这些确实有助于长期项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM