python 的 getattr 的 ruby 等价物是什么
我是 Rails 新手,并尝试进行一些重构(在 app/views/shared 中放置一个列出标题的部分渲染器)渲染器显示日期和标题。 然而,渲染器的不同用户使用不同的日期。 通过重构,我有
title_date = list_titles.created_on
对于渲染器的其他用户,我想要
title_date = list_titles.updated_on
那么我可以使用我传递的字符串(使用 :locals 参数)吗? 我知道在 Python 中我可以做到,
date_wanted = 'created_on'
title_date = getattr(list_titles, date_wanted)
但我不知道如何在 ruby 中做到这一点。 (显然,在 Rails 中,我会从调用部分渲染器的视图中传递 date_wanted 字符串。)
I am new to rails and trying to do a little refactoring (putting a partial renderer that lists titles in app/views/shared ) The renderer shows the dates along with the titles. However different users of the renderer use different dates. Part way through refactoring I have
title_date = list_titles.created_on
For the other user of the renderer I would want
title_date = list_titles.updated_on
So can I use a string I pass through (using the :locals parameter)? I know in Python I could do
date_wanted = 'created_on'
title_date = getattr(list_titles, date_wanted)
but I can't work out how to do that in ruby. (Obviously in rails I would pass the date_wanted string through from the view calling the partial renderer.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Ruby 中的等效语句:
The equivalent statement in Ruby:
我认为原始问题的答案是 send:
send 允许您动态调用对象上的任意命名的方法。
I think the answer to the original question is send:
send allows you to dynamically call an arbitrarily-named method on the object.
您可以像这样向模型添加一个函数
You could add a function to the model like this
马特的答案对于您的确切问题是正确的,我可能无法理解您的情况,但是......
我会通过本地哈希将整个用户对象传递到部分对象中。
然后在部分调用辅助方法中返回每个标题的正确日期,类似于:
将用户和每个标题对象传递给辅助方法。
date_i_like_to_see
方法驻留在 User 模型中,并根据给定用户特有的某些逻辑返回一个字符串(created_on
或updated_on
)。这种方法隐藏了大部分逻辑,让您的视图保持美观和干净。 另外,它使得以后添加特定于给定用户的更多功能变得简单。
Matt's answer is correct for your exact question and I might be way off-mark with understanding your situation but...
I'd pass the entire user object into the partial via the locals hash.
Then within the partial call a helper method to return the correct date for each title, something like:
Pass the user and each title object to the helper method.
The
date_i_like_to_see
method resides in the User model and returns a string (created_on
orupdated_on
) based on some logic particular to the given user.This approach tucks away most of the logic and keeps your view nice and clean. Plus it makes it simple to add further features specific to a given user later.