ruby rails delete space after link_to without HAML - ruby-on-rails

I am programming an app with Ruby on Rails and, in some views, I would like to get rid of the automatic whitespace triggered by the 'link_to' helper.
<%= link_to liker.first_name.capitalize, user_path(liker) %>
<!-- Example of link with a user's firstname (who liked a given content), redirecting to it's user profile -->
I have read this post, which talks about using HAML (that I do not use). Isn't it possible to delete this tiny whitespace only using Ruby on Rails?

You always get a whitespace between inline html elements if you put them in different lines in your html document. For example
<span>foo</span>
<span>bar</span>
would render as "foo bar" on the page. But if you write that html elements next to each other in one line, without a whitespace in between
<span>foo</span><span>bar</span>
it would render as "foobar".
That said: Just write the link_to into the same line with the text that should not be separated with a whitespace:
foo<%= link_to 'bar', '#' %>baz
Would look like "foobarbaz" without any whitespace

As Akshay said you can use .strip or .strip! to remove leading and trailing whitespace.But if you want to remove all whitespace use some tricky hack like .gsub(/\s+/, "") or .gsub(" ","").
<%= link_to liker.first_name.capitalize.to_s.gsub(/\s+/, ""), user_path(liker) %>

Related

How do you use a link_to helper in a YML file that is being sanitized?

I have this key in my locales.yml file that uses a link_to helper.
payment_types:
credit_card: "Requires bank authorization. <%= link_to 'Tutorial', 'www.linktotutorial.com', target: '_blank' %>"
Previously we used an a tag with the href inside along with sanitize, like so:
sanitize(t("payment_types.#{payment_type}"),
tags: %w(a), attributes: %w(target href)), payment_type
But I have to refactor it to use the link_to helper.
The problem is that sanitize is filtering the erb tag alltogether (nothing appears past "Requires bank authorization"), and I can't find a way to allow the erb tag and render the link_to properly.
Getting rid of sanitize in the other hand, renders the string with the erb tags included.
Are erb tags even allowed in yml files?
To parse that ERB tag you can create something like locales.yml.erb
But again there will be too much of hassle to check if Rails is internally parsing ERB yml or not.
And even if it is parsing then will link_to helper will be available or not.
Instead I would suggest a simple way:
# locales.yml
payment_types:
credit_card_html: "Requires bank authorization. %{titorial_link}"
# Usage in views
= t("payment_types.#{payment_type}_html", tutorial_link: link_to('Tutorial', 'www.linktotutorial.com', target: '_blank'))
Please note _html suffix. It is for HTML safe translations.
Read more about HTML safe translations here

Can a `<button type="submit">` be used in place of a `f.submit` in a Rails `form_for` form?

I'm looking to standardize all the buttons and button-styled elements in our Rails app with a button component. This means rendering a styled <button> element with type "button" or type "submit". I'm making use of the view_component gem provided by github!
I am hoping to be able to replace all Rails form helper-y elements such as button_tag, submit_tag and f.submit with a button element. I'm pretty new to Rails, and I am not sure if there are things happening under the hood I'm not taking into account. Looking at the Rails documentation, it doesn't seem like there anything special with the f.submit form helper element.
Am I missing something? Are there consequences to replacing rails form helper submits with a button[type='submit']?
It would be long way to change stuff, so Better to use css and adjust css to get your requirements.
Just add following in you code to create your own my_submit_button
### app/helpers/application_helper.rb ###
module ApplicationHelper
def my_submit
# decide what the submit text should be
text = if #record.new_record?
"Create #{#record.class}"
else
"Update #{#record.class}"
end
# build and return the tag string
my_submit_tag(text)
end
end
further you can read here
The form_for helper

Do not understand what "#" key means with Haml in Rails

I am new to Ruby on Rails, and I setup a starter package on my local machine.
As I looked through it I found this in one of the html.haml files:
%p
Welcome #{#email}!
%p You can confirm your account email through the link below:
%p= link_to 'Confirm my account', confirmation_url(#resource, :confirmation_token => #token)
I think that the ! is part of the message to the user and I believe the #email is a variable with string text and is the person's email address.
However, I don't quite understand what the # does with the email. From the Haml documentation I believe that the # symbol makes a div as show from the example on the Haml site, but this doesn't really make sense so if anyone could explain what it means I would greatly appreciate it.
Haml site example:
#content
.left.column
%h2 Welcome to our site!
%p= print_information
.right.column
= render :partial => "sidebar"
# is for setting the id of an element if it is part of an element, possibly an implicit div.
In plain text (i.e. not in an element definition) the #{...} syntax does interpolation. The contents are evaluated as Ruby, and the result is inserted into the output at this point. In this case, if #email had the value matt#example.com the result would be:
Welcome matt#example.com!
If you want to start a line with some interpolation you can escape the # with \, otherwise it would be interpreted as the start of an element and you would likely get an error.

link_to acting strangely in Rails

All my link_to's in my views seem to return the link text, but also the ink address in brackets. Why is this?
E.g
<%= link_to "Home", root_url %>
and renders in the view
Home (http://localhost:3000/)
Check your stylesheets. For example, I know plenty of print media css does that for the benefit of those who can't "click" their paper.

Rails 3: How to display properly text from "textarea"?

In my Rails 3 application I use textarea to let users to write a new message in a forum.
However, when the message is displayed, all newlines look like spaces (there is no <br />). Maybe there are other mismatch examples, I don't know yet.
I wonder what is the most appropriate way to deal with this.
I guess that the text that is stored in the database is OK (I see for example that < is converted to <), so the main problem is the presentation.
Are there build-in helper methods in Rails for this ?
(simple_format does something that looks similar to what I need, but it adds <p> tags which I don't want to appear.)
Rails got a helper method out of the box, so you dont have to write your own method.
From the documentation:
simple_format(text, html_options={}, options={})
my_text = "Here is some basic text...\n...with a line break."
simple_format(my_text)
# => "<p>Here is some basic text...\n<br />...with a line break.</p>"
more_text = "We want to put a paragraph...\n\n...right there."
simple_format(more_text)
# => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"
simple_format("Look ma! A class!", :class => 'description')
# => "<p class='description'>Look ma! A class!</p>"
You can use style="white-space: pre-wrap;" in the html tag surrounding the text. This respects any line breaks in the text.
Since simple_format does not do what you want, I'd make a simple helper method to convert newlines to <br>s:
def nl2br(s)
s.gsub(/\n/, '<br>')
end
Then in your view you can use it like this:
<%= nl2br(h(#forum_post.message)) %>
If someone still gets redirected here and uses Rails 4:
http://apidock.com/rails/v4.0.2/ActionView/Helpers/TextHelper/simple_format
You can now specify the tag it gets wrapped in (defaults to p) like so:
simple_format(my_text, {}, wrapper_tag: "div")
# => "<div>Here is some basic text...\n<br />...with a line break.</div>"
CSS-only option
I believe one of the easiest options is to use css white-space: pre-line;
Other answers also mentioned using white-space, but I think it needs a little more information:
In most cases you should probably choose pre-line over pre-wrap. View the difference here.
It's very important to keep in mind about white-space that you should not do something like this:
<p style="white-space: pre-line;">
<%= your.text %>
</p>
It will produce extra spaces and line-breaks in the output. Instead, go with this:
<p style="white-space: pre-line;"><%= your.text %></p>
HTML alternative
Another way is to wrap your text in <pre> tags. And last note on my CSS option is true here as well:
<p>
<pre><%= your.text %></pre>
</p>
Don't separate your text from <pre> tags with spaces or line-breaks.
Final thoughts
After googling this matter a little I have a feeling that html-approach is considered less clean than the css one and we should go css-way. However, html-way seems to be more browser-compatible (supports archaic browsers, but who cares):
pre tag
white-space
The following helper preserves new lines as line breaks, and renders any HTML or Script (e.g Javscript) as plain text.
def with_new_lines(string)
(h(string).gsub(/\n/, '<br/>')).html_safe
end
Use as so in views
<%= with_new_lines #object.some_text %>
I just used white-space: pre-line. So next line (\n) will render it.
You'll need to convert the plain text of the textarea to HTML.
At the most basic level you could run a string replacement:
message_content.gsub! /\n/, '<br />'
You could also use a special format like Markdown (Ruby library: BlueCloth) or Textile (Ruby library: RedCloth).
I was using Ace code-editor in my rails app and i had problem, that whenever i update or create the code, it adds always extra TAB on every line (except first). I couldn't solve it with gsub or javascript replace.. But it accidently solved itself when i disabled layout for that template.
So, i solved it with
render :layout => false

Resources