开发者

Comma separation in a ruby loop?

I am working on creating a adserver using rails 3.1 and ruby 1.9.2. In the app I have page at localhost:3000/ads/script that generates the javascript to show the ads. Im looking for some help with the loops.

Here is the code for script.html.erb:

<% @ad.each do |ad| %>   

  <% if ad.end_date <= Date.today || ad.start_date >= Date.today %> 

  <% else %>

  var advert<%= ad.id %> = ''
  advert<%= ad.id %>+='<img class="ad" alt="<%= ad.title %>" src="http://<%= request.env["HTTP_HOST"] %><%= ad.image.url %>" border="0" height="<%= ad.best_height %>" width="<%= ad.best_width %>" />';
  advert<%= ad.id %>+='</a>';
  advert<%= ad.id %>+=''; 

  <% end %>  
<% end %>    


document.write( <% @ad.each do |ad|%>
                <% if ad.end_date <= Date.today || ad.start_date >= Date.today %>

                <% else %>
                  avert<%= ad.id %>, 
                <% end %>  
             <% end %>);     

On the second loop I am trying to add dynamic javascript variables to the document.write that are separated with a comma. like “document.write(advert1, advert2, advert3) but with the current code it puts a comma开发者_StackOverflow after every variable and I need there to not be a trailing comma. Any idea how to accomplish this?

Aside from the comma separation issue, everything works but it doesn't seem very dry and it seems like there could be a better way to do the if else statement... this is my first ruby app and any insight to refactoring would be much appreciated.

Thanks!


Use join:

@ad.select{|ad| !(ad.end_date <= Date.today || ad.start_date >= Date.today)}.collect{|ad| "avert#{ad.id}" }.join(",")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜