简体   繁体   English

在Rails中调用辅助方法时是否有理由不包含模块名称?

[英]Is there ever a reason NOT to include the module name when calling a helper method in Rails?

When working with helper methods in Rails, it's possible to create a method in a helper file and then call the method in the view without referring to the helper module: 在Rails中使用帮助器方法时,可以在辅助文件中创建一个方法,然后在视图中调用该方法而不引用辅助模块:

// application_helper.rb
module ApplicationHelper

   def foobar
      return "foo"
   end

end

// index.html.erb
<%= foobar %>

But if you want to avoid naming conflicts, you can also tie in the name of the helper module to the method you're calling, like this: 但是如果你想避免命名冲突,你也可以将助手模块的名称绑定到你正在调用的方法,如下所示:

// application_helper.rb
module ApplicationHelper

   def self.foobar
      return "foo"
   end

end

// index.html.erb
<%= ApplicationHelper.foobar %>

Am I right in thinking that always doing the second approach is best practice for using a helper method in Rails, or is there sometimes a reason to not do so? 我是否正确地认为总是采用第二种方法是在Rails中使用辅助方法的最佳实践,或者有时候有理由不这样做?

Rails convention dictates the former , rather than the latter. Rails惯例决定了前者 ,而不是后者。 Naming conflicts should be avoided by invoking descriptive method names – that is, truncate_name is better than truncate (so long as it's a name that's being truncated) – rather than namespacing via the module name. 应该通过调用描述性方法名称来避免命名冲突 - 也就是说, truncate_name优于truncate (只要它是被截断的名称) - 而不是通过模块名称命名空间。

If you're still at a loss, consider what the Rails core does: the FormHelper class's form_for function is invoked using form_for , not FormHelper.form_for . 如果你仍然处于亏损状态,请考虑Rails核心的作用:使用form_for 而不是 FormHelper.form_for调用FormHelper类的 form_for函数。 This convention holds true for the vast majority of Rails helper functions. 这种约定适用于绝大多数Rails辅助函数。

Another consideration: when utilizing Rails' default generator, a helper is created for each generated resource by default. 另一个考虑因素:当使用Rails的默认生成器时,默认情况下会为每个生成的资源创建一个帮助程序。 It's common practice to define any helper functions that are specific to the resource within that resource's designated helper file. 通常的做法在该资源的指定帮助程序文件中定义特定于该资源的任何帮助程序函数。 In contrast, helper functions that are applicable across the application should be defined in application_helper.rb , rather than in a resource specific helper. 相反,应用程序中应用的辅助函数应在application_helper.rb定义,而不是在资源特定的帮助程序中定义。

Basically, if you're a strict adherent to Rails DRY principles, you'd want to distill your helper method names to their most elegant forms. 基本上,如果您严格遵守Rails DRY原则,那么您需要将辅助方法名称提炼为最优雅的形式。 If that's the case, it seems preferable to simply invoke concatenate_names(['Alvin', 'Simon', 'Theodore']) , rather than creating a new NamesHelper module and invoking NamesHelper.concatenate(['A', 'S', 'T']) . 如果是这种情况,最好只调用concatenate_names(['Alvin', 'Simon', 'Theodore']) ,而不是创建一个新的NamesHelper模块并调用NamesHelper.concatenate(['A', 'S', 'T'])

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

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