What is the ruby equivalent of python's getattr
Asked Answered
U

4

11

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.)

Unintelligible answered 24/4, 2009 at 15:44 Comment(1)
See also: #771536Leith
S
14

The equivalent statement in Ruby:

date_wanted = :created_on
title_date = list_titles.send(date_wanted)
Senseless answered 24/4, 2009 at 15:51 Comment(1)
Rubocop suggestion: prefer using list_titles.__send__ or list_titles.public_send rather than sendValadez
P
4

I think the answer to the original question is send:

irb(main):009:0> t = Time.new
=> Thu Jul 02 11:03:04 -0500 2009
irb(main):010:0> t.send('year')
=> 2009

send allows you to dynamically call an arbitrarily-named method on the object.

Peale answered 2/7, 2009 at 16:4 Comment(0)
F
0

You could add a function to the model like this

def get_date(date)
  return created_on if date == 'created'
  return updated_on
end
Fecit answered 24/4, 2009 at 15:51 Comment(0)
S
0

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.

render( 
  :partial => "shared/titles", 
  :object => @titles, 
  :locals => { :user => @user } 
)

Then within the partial call a helper method to return the correct date for each title, something like:

<p><%= title_date_for_user(title, user) %></p>

Pass the user and each title object to the helper method.

def title_date_for_user(title, user)
  case user.date_i_like_to_see
  when "created_on"
    title_date = title.created_on
  when "updated_on"
    title_date = title.updated_on
  end
  return title_date.to_s(:short)
end

The date_i_like_to_see method resides in the User model and returns a string (created_on or updated_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.

Sapling answered 25/4, 2009 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.