Rails 5 - rendering array defined in application_helper.rb - ruby-on-rails

I want to use nhl_scores gem to get and display recent NHL game scores on the page. This is how I defined the method in app/helpers/application_helper.rb:
def scores
games = NHLScores::Games.new
s = []
games.recent.each do |g|
s.push("#{g.away_team} # #{g.home_team} - #{g.away_team_score}:#{g.home_team_score}")
end
s
end
And this is how I display this array:
<ul>
<%= scores.each do |s| %>
<li><%= s %></li>
<% end %>
</ul>
The result is:
pic with result
Yeah, for some reason the full array gets displayed after the last closing li tag but before the closing ul tag. How do I remove it? Should I define the method that returns this array elsewhere?

Try this
<ul>
<% scores.each do |s| %>
<li><%= s %></li>
<% end %>
</ul>
The <%= %> is displaying the entire scores array again which you dont want(<%= %> causes the value to be displayed).

Don't use <%= to output the result of scores.each, which is scores.
You're outputting the <li> tags inside the .each block, and then when the .each is done, the value returned from each (scores) is being passed to <%= which echos it to the browser.
You need to be aware of when to use <% and <%=; in this case, you need <%.

Related

Instagram gem returns full hash after iterating through it

I am using the instagram gem with rails. My problem is I am iterating over all of the data in the response with code like this:
<div>
<ul>
<%= #instagram.each do |pic| %>
<li><%= pic.name %></li>
<li><%= pic.latitude%></li>
<li><%= pic.longitude%></li>
<% end %>
</ul>
</div>
I am getting the desired results except for the end, where this gets printed in the browser:
[#<Hashie::Mash id="152201866" latitude=45.89172 longitude=-64.370013 name="Marshview Middle School">, ... etc...]
Any help trying to figure out how to ignore that last bit would be greatly appreciated.
Change
<%= #instagram.each do |pic| %>
to
<% #instagram.each do |pic| %>
= expects a return and prints the collection it iterates over.

not displaying several html blocks if condition not met in ruby

Im trying to restrict the information being shown if data in not available.
In my view.rb file, I have something like this
<% if #content != nil %>
<div>
<h3>....</h3>
<% #content[0..3].each do |something| %>
<li> .... <li>
<% end %>
<% #content[4..5].each do |something| %>
<li> .... <li>
<% end %>
<% #content[5..11].each do |something| %>
<li> .... <li>
<% end %>
<div>
<% end %>
how ever even if content is nil, lines like content[4..5].each do |something| is being run and throwing errors for obvious reasons.
How do I get multiple blocks of html and ruby code to be ignored if condition isn't being met?
If the code <% content[4..5].each do |something| %> is executed, then #content IS NOT nil, there is no way ruby could be wrong about that.
BUT, if it is something like an empty array or a blank string then it will pass the test. In order to cover a wide range of possible "nil-like" values (nil, empty, blank...) use:
<% unless #content.blank? %>
And let me know if it helps.
you can use:
<% unless #content.nil? %>
#true
<%else%>
#false
<%end%>
Are you sure #content is surely nil? Please be aware that an object can be empty while it is not nil.
Eg:
#content=[]
or
#content={}
will make hold true for #content!=nil since it is not actually not nil. A reference is nil if it is never instantiated before.
If you are storing data to #content via a database query like Modelname,All , then you will get an empty array instead of a null (nil) object.
Also, if you are recieving #content from user as request parameter, then if the GET request contains name of the parameter but not any value, then again #content is empty but not nil.
ie http://yourdomain.com/somecontroller/index?name=10&age=
will have params[:age] as empty nil.
Solution:
<% if #content.to_s.empty? != true %>
<div>
<h3>....</h3>
<% content[0..3].each do |something| %>
<li> .... <li>
<% end %>
<% content[4..5].each do |something| %>
<li> .... <li>
<% end %>
<% content[5..11].each do |something| %>
<li> .... <li>
<% end %>
<div>
<% end %>

Printing elements of array using ERB [duplicate]

This question already has answers here:
What is the difference between <%, <%=, <%# and -%> in ERB in Rails?
(7 answers)
Closed 3 years ago.
I'm trying to print a simple array defined in my controller into my view with a new line for each element. But what it's doing is printing the whole array on one line.
Here's my controller:
class TodosController < ApplicationController
def index
#todo_array = [ "Buy Milk", "Buy Soap", "Pay bill", "Draw Money" ]
end
end
Here's my view:
<%= #todo_array.each do |t| %>
<%= puts t %><\br>
<% end %>
Here's the result:
<\br> <\br> <\br> <\br> ["Buy Milk", "Buy Soap", "Pay bill", "Draw Money"]
Erb, the templating engine you're using in your views, has a few different ways of embedding ruby code inside templates.
When you put code inside <%= %> blocks, erb evaluates the code inside and prints the value of the last statement in the HTML. Since .each in ruby returns the collection you iterated over, the loop using <%= %> attempts to print a string representation of the entire array.
When you put code inside <% %> blocks, erb just evaluates the code, not printing anything. This allows you to do conditional statements, loops, or modify variables in the view.
You can also remove the puts from puts t. Erb knows to try to convert the last value it saw inside <%= %> into a string for display.
Hey why are you putting '=' sign in first line. <% %> are used for telling rails that string under this is ruby code,evaluate it. Where as <%= %> this tells rails that string in these tags is in ruby, evaluate it and print the result in html file too.
Hence try to inspect your code you are writing
<%= #todo_array.each do |t| %>
while this line is only for iterating over #todo_array hence we wont be in need to print that line. So final code should be
<% #todo_array.each do |t| %>
<%= puts t %>
<% end %>
Just try:
<%= #todo_array.join('<br />').html_safe %>
instead of
<%= #todo_array.each do |t| %>
<%= puts t %><\br>
<% end %>
Two issues with your view:
you are using "<%=" where you should be using "<%".
you don't need 'puts'
This should improve your results:
<% #todo_array.each do |t| %>
<%= t %><\br>
<% end %>
I would further consider using some HTML structure to better structure your todo list (instead of using br tag at the end of lines), perhaps an un-ordered list like so:
<ul>
<% #todo_array.each do |t| %>
<li><%= t %></li>
<% end %>
</ul>
Remove the equal sign from your each statement:
<% #todo_array.each do |t| %>
<%= t %><\br>
<% end %>

get specific element from ruby block, rails app

When performing a block like:
<% #user.favoured_user.each do |user| %>
<li><%= user.name %></li>
<% end %>
With the favoured_user method returning a limit of 5 users, how would I manipulate the block so that even when there are only 3 users available, I could still return 5 li elements?
I'm guessing a helper would come in to play, and maybe the 'first, second, third, etc.' array methods, but I can't think how to write it.
Any help?
You can try this,
<% 5.times do |i| %>
<li> <%= #user.favoured_user[i].try(:name) %> </li>
<% end %>
You can use in_groups_of
Like:
<% #user.favoured_user.in_groups_of(5).each do |favored_user| %>
<% favored_user.each do |user| %>
<li><%= user.try(:name) %></li>
<% end %>
<% end %>
The first 3 users will come through, and the last two entries will be nil

Rails showing strange #<Game:0xb6783820> tag

I have a simple page that displays some 'Games'.
Heres the code:
<ul>
<%= #tvshow.games.each do |game| %>
<li><%= game.gameTitle %></li>
<% end %>
</ul>
It displays like this:
The All-Syrup Squishee
#<Game:0xb6783820>
With the #Game tag coming AFTER the list item but before the closing list tag. Any idea why it's showing up or how I could get rid of it?
<%= outputs the result as markup, in this case an instance of the Game class.
For this kind of loop you want to use <% which executes some code but does not produce markup.
Edit line 2 to read <% #tvshow.games.each do |game| %>
Remove your first = from the line with the each
Rails is printing the result of the each statement, which returns the array itself. When you output an array, you will output the .to_s of each of its contents, which in your case is the default representations of the Game objects

Resources