I’ve got two small structural issues that I’m not sure how to handle given my relative newbie-ness with RoR.
First issue: In one of my views, I have code that looks like this:
<ul style='list-style-type: circle'> <li><%= @apples.size %> apples</li> <li><%= @oranges.size %> oranges</li> <li><%= @bananas.size %> bananas</li> <li><%= @grapefruits.size %> grapefruits</li> </ul>
Is it possible to refactor this so that I only need to iterate once over some list of different kinds of fruit, and have the appropriate <li>‘s be automatically generated? Edit: I forgot to add that @apples, @oranges, etc., might be nil. Is there an idiomatic way to handle that?
Second issue: In my controller, I have code that looks like this:
@apples = Apple.find(:all) @apples.each { |apple| apple.do_stuff(:xyz) } @bananas = Banana.find(:all) @bananas.each = { |banana| banana.do_stuff(:xyz) } # ... &c
As you can see, the same operation is invoked many times in exactly the same way. Is there a way to shorten this to something like [Apple.find(:all), ...].each { |fruit| ... } and have that work instead?
Thanks very much for your help!
I’d do this in a helper
And this in the view:
In your controller:
It makes sense to store all the items in a hash,
@fruits, so that you don’t have to useinstance_variable_getand stuff.Perhaps you also want to define that array somewhere, so that you don’t have to repeat it in the controller and in the view. Let’s pretend that you have a fruit model.
Then, use Fruit::FRUITS in the view and controller.