rails 部分模板中的可选局部变量:我如何摆脱(定义?foo)的混乱? [英] optional local variables in rails partial templates: how do I get out of the (defined? foo) mess?

查看:29
本文介绍了rails 部分模板中的可选局部变量:我如何摆脱(定义?foo)的混乱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直是个坏孩子,如果在渲染部分时未在 :locals 哈希中明确定义值,我会在部分模板中使用以下语法为局部变量设置默认值 --

I've been a bad kid and used the following syntax in my partial templates to set default values for local variables if a value wasn't explicitly defined in the :locals hash when rendering the partial --

<% foo = default_value unless (defined? foo) %>

直到最近,这似乎都运行良好,当时(无缘无故地辨别)未传递的变量开始表现得好像它们已被定义为 nil(而不是未定义).

This seemed to work fine until recently, when (for no reason I could discern) non-passed variables started behaving as if they had been defined to nil (rather than undefined).

正如各种乐于助人的人所指出的那样,http://api.rubyonrails.org/classes/ActionView/Base.html不要使用

As has been pointed by various helpful people on SO, http://api.rubyonrails.org/classes/ActionView/Base.html says not to use

defined? foo

改为使用

local_assigns.has_key? :foo

我正在尝试修改我的方法,但这意味着要更改很多模板.

I'm trying to amend my ways, but that means changing a lot of templates.

我可以/应该提前收费并在所有模板中进行此更改吗?有什么需要注意的地方吗?我需要多认真地测试每一个?

Can/should I just charge ahead and make this change in all the templates? Is there any trickiness I need to watch for? How diligently do I need to test each one?

推荐答案

我这样做:

<% some_local = default_value if local_assigns[:some_local].nil? %>

这篇关于rails 部分模板中的可选局部变量:我如何摆脱(定义?foo)的混乱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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