Rails 助手应该假设实例变量存在还是应该将它们作为参数接收? [英] Should Rails helpers assume an instance variable exists or should they receive them as parameters?

查看:22
本文介绍了Rails 助手应该假设实例变量存在还是应该将它们作为参数接收?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个特定的编程原则(Demeter?)支持 Rails 助手不应该使用控制器实例变量,而是应该接收这样的变量作为函数参数的想法.例如,假设我的 ChickensController#squawk 操作创建了一个名为 @egg 的实例变量.此外,假设 squawk 视图包含对名为 cockadoodledoo 的助手的调用,实现如下:

I'm wondering if there's a specific programming principle (Demeter?) that supports the idea that Rails helpers should never use controller instance variables, rather, they should receive such variables as function parameters. For example, assume my ChickensController#squawk action creates an instance variable called @egg. Furthermore, assume the squawk view contains a call to a helper called cockadoodledoo, implemented like so:

def cockadoodledoo
  @egg.to_s
end

@egg 作为参数传递是更好还是不必要的冗长,以便视图调用 cockadoodledoo(@egg) 并且帮助器类似于:

Would it be better or unnecessarily verbose to pass @egg as a parameter, such that the view calls cockadoodledoo(@egg) and for the helper to resemble:

def cockadoodledoo(egg)
  egg.to_s
end

我希望你们中的一个快乐的黑客在周五下午无聊到断言答案.鹦鹉!

I hope one of you happy hackers is bored enough on a Friday afternoon to assert an answer. Cockadoodledoo!

这里的问题很相似,但从未得到准确回答.

推荐答案

将它们作为参数接收.否则,随着应用的增长,在重构、故障排除等时很难追踪实例变量的设置位置.

Receive them as a param. Otherwise, as the app grows, it gets very difficult to trace where the instance vars are being set when refactoring, troubleshooting, etc.

另外,我相信有一个通用的最佳实践,即在初始模板中的视图中只使用实例变量......从那里你应该将变量传递给助手和其他部分.

Also, I believe there's a general best practice to only use instance vars in views within the initial template...and from there you should pass the var into helpers and other partials.

这篇关于Rails 助手应该假设实例变量存在还是应该将它们作为参数接收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆