Rails erb formatting troubles, phantom spaces - ruby-on-rails

Halp! My template is formatting strangely and I can't fathom how/why.
<% #poll.questions_all.each do |q| %>
<td>
<span class="optionvalue">
<% if can? :read_full, #poll %>
<%= resp[:texts][q.id] %>
<% else %>
<%= resp[:texts][q.id].nil? ? '' : resp[:texts][q.id].gsub(Question::POISON_WORDS_REGEX, '---') %>
<% end %>
</span>
<% unless q.options.empty? %>
<%= q.get_matching_option(resp[:texts][q.id])? ": #{q.get_matching_option(resp[:texts][q.id])}" : '' %>
<% end %>
</td>
<% end %>
Results in this:
A : Playgrounds
No idea where that first space is coming form, and every effort to get rid of it has failed! The generated markup:
<td>
<span class="optionvalue">
A
</span>
: Playgrounds
</td>

Try using the <%- -%> version of erb tags, these should suppress the extra whitespaces:
<%- if can? :read_full, #poll -%>
<%= resp[:texts][q.id] %>
<%- else -%>
<%= resp[:texts][q.id].nil? ? '' : resp[:texts][q.id].gsub(Question::POISON_WORDS_REGEX, '---') %>
<%- end -%>
I don't recall if you need them in both the opening and ending tags, but I'd suggest playing around with it and see if you can get what you want.

Horrible solution, but it works:
<% #poll.questions_all.each do |q| %>
<td>
<span class="optionvalue">
<% if can? :read_full, #poll %>
<%= resp[:texts][q.id] %></span><%= q.get_matching_option(resp[:texts][q.id])? ": #{q.get_matching_option(resp[:texts][q.id])}" : '' unless q.options.empty? %>
<% else %>
<%= resp[:texts][q.id].nil? ? '' : resp[:texts][q.id].gsub(Question::POISON_WORDS_REGEX, '---') %></span><%= q.get_matching_option(resp[:texts][q.id])? ": #{q.get_matching_option(resp[:texts][q.id])}" : '' unless q.options.empty? %>
<% end %>
</td>
<% end %>

I am pretty sure erb will do the right thing (not add unwanted lines) if you keep everything on one line of HTML.
For this case, and in general, I recommend that you put any logic for generating the content in methods in the view helper file (or if you're feeling lazy, in a code block in the erb, as in this example):
<% #poll.questions_all.each do |q| %>
<%
if can? :read_full, #poll
texts = resp[:texts][q.id]
else
texts = (resp[:texts][q.id].nil? ? '' : resp[:texts][q.id].gsub(Question::POISON_WORDS_REGEX, '---'))
end
if q.options.empty?
matching_options = ''
else
matching_options = (q.get_matching_option(resp[:texts][q.id])? ": #{q.get_matching_option(resp[:texts][q.id])}" : '')
end
%>
<td>
<span class="optionvalue"><%= texts %></span><%= matching_options %>
</td>
<% end %>

Related

The result repeats the message several times with ruby on rails

I have this code:
<% #lookup_coins.each do |x| %>
<% if #symbol == '' %>
<%= 'Sorry, but you forgot to write something, LOL'%>
<% elsif #symbol == x %>
<%= x["symbol"]%> <br/> <%= x["name"]%>: <%= number_to_currency(x['quote']['USD']['price'].round(2) , :unit => "$ ") %> <br/> <%= x["cmc_rank"]%> <br/>
<% else 'Sorry, there was a mistake, try again'%>
<% end %>
The info looks like this:
[{"id"=>1, "name"=>"Bitcoin", "symbol"=>"BTC", "slug"=>"bitcoin", "num_market_pairs"=>9713, "date_added"=>"2013-04-28T00:00:00.000Z", "tags"=>["mineable", "pow", "sha-256", "store-of-value", "state-channels", "coinbase-ventures-portfolio", "three-arrows-capital-portfolio", "polychain-capital-portfolio"], "max_supply"=>21000000, "circulating_supply"=>18633612, "total_supply"=>18633612, "platform"=>nil, "cmc_rank"=>1, "last_updated"=>"2021-02-20T07:45:02.000Z", "quote"=>{"USD"=>{"price"=>55541.51774356704, ...
I am not sure how to do it in the correct way
It looks like you're failing to match to the actual symbol value, but instead are expecting #symbol to perfectly match a Hash, which it won't.
Secondly, you're also printing that "forgot to write something" message each time through the loop which is wrong. You can get rid of the loop, just use find to locate the entry right away, and then as a bonus you can more easily detect a "missed" condition.
Just see if you can find a matching entry, otherwise display the message.
The fix looks like:
<%- if #symbol.blank? -%>
Sorry, but you forgot to write something.
<%- else -%>
<%- found = #lookup_coins.find { |c| c['symbol'] == #symbol } -%>
<%- if (found) -%>
<%= found["symbol"]%> <br/> <%= found["name"]%>:
<%= number_to_currency(found['quote']['USD']['price'].round(2), :unit => "$ ") %>
<br/>
<%= found["cmc_rank"]%> <br/>
<%- else -%>
Sorry, there was a mistake, try again
<%- end -%>
<%- end -%>
Using #symbol.blank? here which is more forgiving than == '' as it will also reject a bunch of spaces and/or tabs.
Tip: Don't use <%= '...' %> Instead just put the text there as-is. The default is to echo it.
<% if #symbol %>
<%#resultant_symbol = #lookup_coins['data'].select {|lookup_coin| lookup_coin["symbol"] == #symbol }%>
<%if #resultant_symbol.present?%>
<% x = #resultant_symbol.first %>
<%= x["symbol"]%> <br/> <%= x["name"]%>: <%= number_to_currency(x['quote']['USD']['price'].round(2) , :unit => "$ ") %> <br/> <%= x["cmc_rank"]%> <br/>
<%else%>
<%= #symbol = 'Sorry, there was a mistake, try again'%>
<%end%>

How to specify syntax error in Ruby on Rails

My controller is like this
def show
#receipt = Receipt.find(params[:id])
#hospitalizations=#receipt.hospitalizations
#outpatients=#receipt.outpatients
#surgeries=#receipt.surgeries
end
my show.html.erb is like this.
<h1>details of receiptid: <%= #receipt.id %></h1>
<% #hospitalizations.each do |hospitalization| %>
<p>hospitalization_id:<%= hospitalization.id %>hospitalization_start :<%= hospitalization.hospitalization_start %> hospitalization_end:<%= hospitalization.hospitalization_end %> </p>
<% #surgeries.each do |surgery| %>
<p>surgeryid:<%= surgery.id %> surgery_day :<%= surgery.surgery_day %> </p>
<% #outpatients.each do |outpatient| %>
<p>outpatientid:<%= outpatient.id %>outpatient_day :<%= outpatient.outpatient_day %> </p>
<% end %>
When I access it's page,some error like below was incurred. I tried to specify error location,but didn't work well.
It seems syntax error,where should end insert?
If someone has experienced same issues,please let me know.
Each of your each loop requires an <% end %> clause, you can't find the specific line since the error says it reached the end when it expected "end". Close all your loops like this:
<% #hospitalizations.each do |hospitalization| %>
<p>hospitalization_id:<%= hospitalization.id %>hospitalization_start :<%= hospitalization.hospitalization_start %> hospitalization_end:<%= hospitalization.hospitalization_end %> </p>
<% end %>

Dont have a comma on the last iteration of an each loop in Rails

I want to print out a list of links separated by commas in Rails.
Heres what I've got:
<%= topics.each do |topic| %>
<a href="<%= topic.link %>" ><%= topic.name %></a>
,
<% end %>
Heres what I want:
Thing A,
Thing B,
Thing C
But right now I get an extra comma on the last iteration of the loop! What should I do?
One way of doing this is with map then Array#join:
<%= topics.map { |topic| link_to(topic.name, topic.link) }.join(',').html_safe %>
if you want to do minimum possible change to your code, you can use the following
<%= topics.each do |topic| %>
<a href="<%= topic.link %>" ><%= topic.name %></a>
<% if(topic != topics.last) %>
,
<% end %>
<% end %>
How about using each_with_index, and only put comma before the content unless it's not the first item.
<% topics.each_with_index do |topic, i| %>
<% if i > 0 %>
,
<% end %>
<%= topic.name %>
<% end %>
I made it in one line call (for active records collections) using the concat helper:
<% concat (',') if e.bills.last != b %>
concat is an ERB helper (TextHelper) to add some HTML without the <%= %> syntax, helpful to add few characters.
Here is the full code to make it clear:
<% event.bills.each do |b| %>
<%= link_to(b.number.to_s, bill_display_path(b)) %>
<% concat (',') if e.bills.last != b %>
<% end %>
Simply try this. It works for me
<%= topics.map{|p| p.topic.name}.join(",") %>
You can do the following to print out the comma for all items except for the last:
<% topics.each do |topic| %>
<%= topic %>
<%= "," if topic != topics.last %>
<% end %>
This will check if the current item in the loop is the last item, and will use the <%= %> syntax to output the comma.

Order by time_field

I have a database table called "bookings" which users can select the 'time_from' and 'time_to' in which they want the booking done.
When adding these fields to the database I added them as a time_field.
<%= f.label :time_from, "From (24hr Clock)" %>
<%= f.time_field :time_from %>
<%= f.label :time_to, "To (24hr Clock)" %>
<%= f.time_field :time_to %>
The form works and saves correctly but my problem is the order. Below is my controller code and subsequently my view to display the time and its output. Any idea on how to order these by time correctly?
Controller:
def show
#location = Location.find(params[:id])
#booking = Booking.order("time_to")
#company = Company.all
end
View:
<% 0.upto(11.to_i).each do |day_count| %>
<span class="col-md-3 booking-times">
<h4><%= time_tag(Date.today + day_count.days) %></h4>
<span class="label label-danger no-bookings">No Bookings</span>
<% #booking.each do |b| %>
<% if b.date == Date.today + day_count.days && b.type == "Meeting" %>
<% if b.location == params[:id] %>
<span class="label label-info booking-time">
<%= time_tag(b.time_from, :format=>"%H:%M") %> -
<%= time_tag(b.time_to, :format=>"%H:%M") %>
</span>
<% #company.each do |c| %>
<% if c.id == b.company %>
<%=link_to c.name, c %></br>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
</span>
<% end %>
Output: (For first day time)
09:30 - 10:30
22:00 - 23:00
07:30 - 08:30
I appreciate this is not the nicest looking code. I would like the above output to order by time. Any ideas? I have tried to order in the controller, this effects the layout but not in the correct order still. I think the dat attatched to the time_to input may be having ian affect? Thanks!
Have you tried this:
#booking = Booking.order(time_to: :desc)
Can you please try this:
#booking = Booking.order('time_to desc')

Whats wrong with my simple If Else?

Im new to RoR/Ruby and i cant seem to get the simplest thing to work. (trust me, ive search google and reread docs, i dont know what wrong)
So in my main view, I added the following:
<%= if 1>2 %>
<%= print "helllloooo" %>
<%= else %>
<%= print "nada" %>
<%= end %>
And nothing is outputted..
**UPDATE**
Ok heres my new CORRECTED code and its STILL NOT WORKING
<th>
<% if 1 > 2 %>
<%= print "helllloooo" %>
<% else %>
<%= print "nada" %>
<% end %>
</th>
Your statements are not intended to be displayed so instead of
<%= if 1>2 %>
write
<% if 1 > 2 %>
Same thing for else and end
EDIT
<% if 1 > 2 %>
<%= "helllloooo" %> #option 1 to display dynamic data
<% else %>
nada #option 2 to display static data
<% end %>
You don't need to use print, or even ERB for the text. Also, your if, else, and end statements should be <%, not <%=:
<% if 1 > 2 %>
helllloooo
<% else %>
nada
<% end %>
<%= already means "print to the HTML response" in ERB (Ruby's own templating language).
So <%= print '...' means "print the return type of print '...'" which is nothing.
The right code would look like:
<% if 1>2 %>
<%= "helllloooo" %>
<% else %>
<%= "nada" %>
<% end %>
In fact you can even omit the <%= because you're just printing strings (not arbitrary objects):
<% if 1>2 %>
helllloooo
<% else %>
nada
<% end %>
The = is the problem. Use <% instead. <%= is for printing something, while <% is for instructions.
for dynamic content use: <%= %>

Resources