Rails助手应该假设一个实例变量是否存在或是否应该将它们作为参数接收? [英] Should Rails helpers assume an instance variable exists or should they receive them as parameters?
问题描述
我想知道是否有一个特定的编程原则(Demeter?)支持Rails助手不应该使用控制器实例变量的想法,相反,他们应该接受像函数参数那样的变量。例如,假设我的 ChickensController#squawk
action创建了一个名为 @egg
的实例变量。此外,假设 squawk
视图包含对称为 cockadoodledoo
的助手的调用,实现如下所示:
def cockadoodledoo
@ egg.to_s
end
传递 @egg
作为参数会更好还是不必要地冗长,这样视图会调用<$ c $
def cockadoodledoo(egg) - > cockadoodledoo(@egg)
egg.to_s
end
我希望你们中的一个快乐的黑客很无聊足以在星期五下午提出答案。 Cockadoodledoo!
接受他们作为参数。否则,随着应用程序的增长,很难追踪重构,排除故障等时设置实例变量的位置。
另外,我相信这里有一个最好的练习只在初始模板中的视图中使用实例变量...并从那里你应该将var传递给助手和其他部分。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
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!
This question here is similar, but was never accurately answered.
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屋!