问题描述
我是 Rails 的新手,正在尝试进行一些重构(在 app/views/shared 中放置一个列出标题的部分渲染器)渲染器显示日期和标题.然而,渲染器的不同用户使用不同的日期.重构的一部分
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
那么我可以使用我传递的字符串吗(使用 :locals 参数)?我知道在 Python 中我可以做到
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)
但我不知道如何在 ruby 中做到这一点.(显然在 Rails 中,我会从调用部分渲染器的视图中传递 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.)
推荐答案
Ruby 中的等效语句:
The equivalent statement in Ruby:
date_wanted = :created_on
title_date = list_titles.send(date_wanted)
这篇关于python的getattr的ruby等价物是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!