Is there a way not to break 3 lines of code into 3 <% %> ?

In the view code, say it is

<% @stories.each do |s| %> <%= "<div>#{h s.inspect}</div>" %> <% end %>

it would be breaking the code into 3 <% %> and <%= %>

is there a way to just have one <% %> or <%= %> so as to keep the code more flowing together?

In the view code, say it is

<% @stories.each do |s| %> <%= "<div>#{h s.inspect}</div>" %> <% end %>

it would be breaking the code into 3 <% %> and <%= %>

is there a way to just have one <% %> or <%= %> so as to keep the code more flowing together?

The above is pretty standard (I'd indent it though). You can change the %> to -%> to kill off new lines in the output.

In the above case you could do this...

<%= @stories.map {|s| content_tag(:div, h(s.inspect)) }.join %>

Not sure that's more readable or not... I'll do that sometimes for things like 'li' entries.

-philip

Philip Hallstrom wrote:

In the above case you could do this...

<%= @stories.map {|s| content_tag(:div, h(s.inspect)) }.join %>

i was at first worried that if the print out is long, like a few hundred lines, then it can create many string objects.

using join looks like will create only n + 1 string objects...

if using inject or something, it might be creating about 2n string objects, each one longer than the previous ones.

that's why is it true that   "some text #{ } and then something more #{ }"

is better since it is one string object created while   "some text " + expression + " and then something more " + expression

will create 4 string objects and therefore running slower?

Jian Lin wrote:

using join looks like will create only n + 1 string objects...

ah, on second thought, doesn't the join() method actually will create n string objects too? (the next one longer than a previous one), so it would be creating 2n string objects too.

Philip Hallstrom wrote:

In the view code, say it is

<% @stories.each do |s| %> <%= "<div>#{h s.inspect}</div>" %> <% end %>

Another option, although probably not necessary in this case, is to move the code into a view helper.

<%= h story_list(@stories) %>

def story_list(stories)   list = ""   stories.each do |s|     list += content_tag(:div, h(s.inspect))   end   list end

Yes, in this case the helper is more verbose (maybe there's a better way that what I did), but at least your view code is clean and pretty. The ugliness get move outside the view into the helper.

Another common pattern for a case like you show is to move the code that actually lists the stories into a partial. Then rendering the partial from your view becomes one line:

<%= render :partial => @stories %>

Robert Walker wrote:

Philip Hallstrom wrote: def story_list(stories)   list = ""   stories.each do |s|     list += content_tag(:div, h(s.inspect))   end   list end

Well this was a bit lame. Use the map & join as shown from previous posts:

<%= @stories.map {|s| content_tag(:div, h(s.inspect)) }.join %>

I wasn't thinking.