是否可以在 Rails 的 eRuby 模板中定义常量

发布于 2024-10-05 04:15:45 字数 240 浏览 6 评论 0原文

因为我讨厌使用布尔文字调用方法,而这些方法没有说明其意图,所以我尝试在我的 eruby 模板中定义一个常量,如下所示: <% NO_NIL_PADDING = false %> 用于调用 <代码>in_groups_of。然而,这导致了动态常量赋值错误。有办法解决这个问题吗?我可能可以在环境中的某个地方定义常量,但 atm 我更愿意使常量定义尽可能接近其用法,直到开始有必要将其定义移至更高级别。

Since I hate calling methods with boolean literals that don't say anything about their intent I tried defining a constant in my eruby template as follows: <% NO_NIL_PADDING = false %> for a call to in_groups_of. However this resulted in a dynamic constant assignment error. Any way to get around this? I could probably define the constant in the environment somewhere, but atm I'd prefer to keep the constant definition as close to its usage as possible until it starts getting necessary to move its definition to a higher level.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的往事 2024-10-12 04:15:45

我不知道你在模板中做了什么可能会导致它,但只是设置常量对我有用:

ruby-1.8.7-p249 > template = ERB.new "<% DONT_SET_CONSTANTS_IN_VIEWS = false %>"
 => #<ERB:0x100485890 @src="_erbout = '';  DONT_SET_CONSTANTS_IN_VIEWS = false ; _erbout", @filename=nil, @safe_level=nil> 
ruby-1.8.7-p249 > template.result(binding)
 => "" 

但是,在旁注中,我强烈建议不要这样做这。作为去年继承了大量代码的人,您正在为自己以及可能的其他人带来严重的头痛。这样的选项实际上可能会根据业务逻辑而改变吗?我会尝试选择一个合理的默认值并使用它。如果它没有在其他地方使用,为什么要创建一个常量?

I don't know what else you're doing in the template that might be causing it, but just setting the constant works for me:

ruby-1.8.7-p249 > template = ERB.new "<% DONT_SET_CONSTANTS_IN_VIEWS = false %>"
 => #<ERB:0x100485890 @src="_erbout = '';  DONT_SET_CONSTANTS_IN_VIEWS = false ; _erbout", @filename=nil, @safe_level=nil> 
ruby-1.8.7-p249 > template.result(binding)
 => "" 

on a side note, however, I'd strongly recommend not doing this. As someone who's inherited a lot of code in the last year, you're making serious headaches for yourself and potentially someone else. Is an option like that actually likely to change per business logic? I would try to pick a sane default and just use it. If its not being used anywhere else, why create a constant?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文