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.)
Yes, compared to the direct conventional method of accessing an attribute of a given object, the performance of getattr() is slower.
The getattr approach is slower than the if approach, reducing an insignificant ~3% the performance if bar is set and a considerable~35% if is not set.
The equivalent statement in Ruby:
date_wanted = :created_on
title_date = list_titles.send(date_wanted)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With