-2

Given an array like this:

%w{ field_one, field_two, some_association.field_one }

I need to iterate over this and dynamically call these methods on a given object, exactly as described here: Ruby send method with rails associations

So far I have this, which does fetch the values correctly:

field.include?('.') ? field.split('.').inject(some_object, :send) : some_object.send(field)

Additionally though, I need to call :human_attribute_name on the correct class to generate labels. What is a clean way to accomplish this?

Community
  • 1
  • 1
scoots
  • 715
  • 4
  • 16
  • 1
    Since what you have is working can you clarify what you mean by "Additionally though, I need to call :human_attribute_name on the correct class to generate labels." I don't know what the "correct" class is or what you mean by "labels" please explain the issue you are facing not the problem you have already solved. – engineersmnky Jan 13 '16 at 14:25

1 Answers1

0

It's not clear what you're trying to accomplish but if I had to guess I'd say you're trying to make some kind of CMS or reporting system in which the definition of what data to display can be altered through a user interface. There are gems for this kind of thing but seeing as you're on this track...

By :human_attribute_name I assume you mean the friendly name to be displayed on the page as a label. First of all it would be more appropriate to use a string rather than symbol as you can then use spaces and more characters. Assuming you never intend to have duplicate label names on the same webpage you could try using a hash instead of an array.

fields = { 
           "Field One" => "field_one" ,
           "Field Two" => "field_two" ,
           "Field One Of Some Association" => "some_association.field_one"
         }

and then fetch the data in a similar way to that shown in the answer you referenced.

data = {}

fields.each_pair do | friendly_name, attribute |
  data[friendly_name] = if attribute.include?('.')
    attribute.split('.').inject(some_object, :send)
  else
    some_object.send(attribute)
  end
end

That should leave you with a hash you can loop over in your view like this

{ 
  "Field One" => "Mr" ,
  "Field Two" => "Data",
  "Field One Of Some Association" => "A Friend Of Mr Data"
}
Adamantish
  • 1,888
  • 2
  • 20
  • 23