从 params hash 访问值的简写
我经常觉得需要从“params”哈希访问各个键值对,就好像它们是局部变量一样。
我发现使用局部变量而不是每次都编写“params”,使我的代码更容易理解。
因此,我不会使用像 params[:first_variable]
这样的值,而是会做类似的事情:
first_var = params[:first_variable]
second_var = params[:second_variable]
...
在我的程序中,我会使用这个简短的符号,而不是编写 params[:first_var]
每次。
这样做的问题是,当我的参数中有很多值时,我的函数的大小会显着增加。
有没有更好的方法将“params”中的对象引用为函数中的局部变量?
I often feel the need to access the individual key-value pairs from the 'params' hash, as if they were local variables.
I find that using local variables instead of writing 'params' every time, makes my code easier to understand.
So instead of using the values like params[:first_variable]
I would do something like :
first_var = params[:first_variable]
second_var = params[:second_variable]
...
and in my program i would use this short notation instead of writing params[:first_var]
every time.
The problem with this is that the size of my functions can grow significantly, when I have many values in params.
Is there a better way to reference the objects from 'params' as local variables in my function ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在您想要此功能的类中重新定义
method_missing
。如果你这样做,请记住method_missing
的基本规则 - 如果你无法处理它,请调用 pass it on (tosuper
);并并行更新respond_to?
。也许是这样的。
请记住,Rails 已经大量使用了
method_missing
,因此要么只在您自己的类上重新定义它,要么为现有版本添加别名,并在您不使用时调用它而不是super
处理。You could redefine
method_missing
in which class you want this functionality. If you do, remember the cardinal rules ofmethod_missing
- if you can't handle it, call pass it on (tosuper
); and updaterespond_to?
in parallel.Something like this, perhaps.
Remember that Rails makes heavy use of
method_missing
already, so either only redefine it on your own classes, or alias the existing version and call that instead ofsuper
when you aren't handling.