views:

351

answers:

4

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

A: 

You could add a function to the model like this

def get_date(date)
  return created_on if date == 'created'
  return updated_on
end
Jason Miesionczek
+6  A: 

The equivalent statement in Ruby:

date_wanted = :created_on
title_date = list_titles.send(date_wanted)
Matt Haley
A: 

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.

nutcracker
+1  A: 

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.