有没有比这个 Ruby 习惯更好的替代方案?
我发现自己经常在控制器中编写这段代码:
params[:task][:completed_at] = Time.parse(params[:task][:completed_at]) if params[:task][:completed_at]
不要沉迷于我在这里具体做的事情,因为原因每次都会改变;但在很多情况下,我需要检查 params 中的值并在将其交给 create
或 update_attributes
之前进行更改。
重复 params[:task][:completed_at] 三次感觉非常糟糕。有更好的方法吗?
I'm finding myself writing this bit of code in my controllers a lot:
params[:task][:completed_at] = Time.parse(params[:task][:completed_at]) if params[:task][:completed_at]
Don't get hung up on what I'm doing here specifically, because the reasons change every time; but there are many circumstances where I need to check for a value in params and change it before handing it off to create
or update_attributes
.
Repeating params[:task][:completed_at]
three times feels very bad. Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
稍微缩短这一过程的一种方法是:
或者,您可能更喜欢这样:
在第二种情况下,仅当左侧为“真实”时才会发生分配。
One way to shorten this slightly is:
Or, you might prefer this:
In the second case, the assignment will only happen if the left side is "truthy".
我想你可以考虑做这样的事情。
在 String 和 NilClass 上实现
#to_time
,可能在extensions.rb
中(如 Ruby 最佳实践,例如,然后您只需调用
params[:task][:created_at].to_time
即可,重复项就消失了。我完全不确定这是否有效必然构成“最佳实践”,但恕我直言,它满足了问题的目标......
I suppose you could consider doing something like this.
Implement
#to_time
on String and NilClass, perhaps in aextensions.rb
(as recommended in Ruby Best Practices, e.g.Then you can just call
params[:task][:created_at].to_time
and the duplication is gone.I'm not at all sure that this necessarily constitutes "best practice", but IMHO it meets the objective of the question...
我对 Ruby 并不是非常熟悉,但由于它具有 Perl 根源,因此可能有一个构造允许您像这样编写它:
基本上利用 for 循环来创建变量的别名(如果存在),
可能类似于:
编辑:
我发现 Ruby 有一个
alias
关键字。我对它不太熟悉,无法给出 Ruby 示例,但在 Perl 中,上面的内容也可以写成:其中指定
$_
将是$params[$task] 的别名[$completed_at]
我尝试在 Ruby 中简单地使用它,但没有找到为标识符别名的方法,只有全局变量。
I am not incredibly familiar with Ruby, but since it has Perl roots, there may be a construct that allows you to write it like this:
basically exploiting the for loop to create an alias to the variable, if it exists
maybe something like:
edit:
I see that Ruby has an
alias
keyword. I am not familiar enough with it to give a Ruby example, but in Perl, the above could also be written:which specifies that
$_
will be an alias for$params[$task][$completed_at]
I tried playing around with it breifly in Ruby, but didn't see a way to alias an identifier, just global variables.