Topic: Invoking a nested getted using reflection

I'm using some helper method to render an active record's property name and it's current value.

def label_value(object, property, opts={})
  res = "<p><label>#{white_list(opts[:label] || property.id2name.capitalize)}"
  res = res + ":</label>"
  res = res + white_list(object.send(property).to_s)
  res = res + "</p>"
end

The argument 'property' names the property to be evaluated. This is done using reflection (object.send(property)).

Unfortunately this just works for top-level properties (like object.name) and not for nested (associated) properties (like object.associated_object.name).

What's the best way to recurse down to the associated object and call send on the property ?

Re: Invoking a nested getted using reflection

You could call send again like this:

object.send(:foo).send(:bar)

If you need to parse "foo.bar" you could use split and inject:

properties = property.split('.')
result = properties.inject(object) { |o, property| o.send(property) }

Untested.

Railscasts - Free Ruby on Rails Screencasts