Topic: Make this view code shorter
DISCLAIMER: I've only been working in ruby and rails for a few days. I know almost nothing.
At any rate, just noticed this pattern in the view code for a particular model (show):
<p> <b>Size:</b> <%= @order.size %> </p> <p> <b>Price:</b> <%= @order.price %> </p> etc...
It seems to me that the pattern is thus:
<p> <b>NAME_OF_INSTANCE_VAR:</b> <%= @order.INSTANCE_VAR %> </p>
What I'd like to do is have some generic function, method, helper, whatever, which would cycle through the instance vars of the object and output the above code snippet. Something like this (pseudocode):
<%= foreach INSTANCE_VAR order do: %> <p> <b>name(INSTANCE_VAR):</b> <%= @order.INSTANCE_VAR %> </p><%= end %>
I could not only make this one particular view a lot shorter, but I could use the same method, function, whatever, in other views too. Thing is, not only do I not know how to get this list of instance vars, I also don't know the way to metaprogram this in Ruby. I could easily do it in TCL right now without even thinking. I could easily do it in a few other languages. But I don't know how to do it in Ruby.
I guess the first question is, is there already some Rails function that will already do this for me? I'd be surprised if there wasn't, but then again it doesn't use said theorized function in the views it auto-generates, so I guess the answer is no.
Second question would then be, how does the rails community tend to handle this?
I guess something like this?
<% @order.attributes.each do |key, value| %> <%= content_tag :b, key+":" %> <%= value %> <% end %>
Last edited by rex.goxman (2012-05-28 16:07:37)