RoR. Styling a helper method in rails - ruby-on-rails

I am trying to style a helper method. The method works fine but html_safe (or how I have done it here) does not work to style it. I tried other variations as well like putting html_safe after .to_s, didn't work either.
Here is my latest approach.
def tweeted_text(counted)
if current_user.tweets.count == 1
first = "<b>current_user.tweets.count.to_s</b>" + " Tweet"
first.html_safe
else
second = "<b>current_user.tweets.count.to_s</b>" + " Tweets"
second.html_safe
end
end
In my view
<%= tweeted_text(#counted) %>
What would be an appropriate way to go about styling my helper?
ty

Please try this.
def tweeted_text
result = "<b>#{current_user.tweets.count}</b> Tweet"
result = result + "s" if current_user.tweets.count > 1
result.html_safe
end

Related

Getting a double line break with a concat content_tag [duplicate]

My helper works like this:
def some_help(in_string)
in_string + " and more"
end
But I want it do to a before the output and I keep getting the < br > characters themselves literally, i.e. not a break but what I want is a < br > that is the problem.
so
def some_help(in_string)
"<br/>" + in_string + " and more"
end
doesn't work right.
Use tag(:br) instead of "<br/>".
content_tag(:br) creates opening and closing br tags and using raw or html_safe is just ugly (not to mention dangerous).
you can also use the "content_tag" view helper.
http://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag
def some_help
content_tag(:br) + "some help"
end
I'm not sure I understand you. You add <br /> in your string, and it stays in plain while you want it to have the effect of a newline ? If it is that, you have to mark your string as html-safe. you do this with "somestring".html_safe.
Rails automatically escapes HTML characters. Use .html_safe on the string.

View helper method that lists images in a directory with `Dir.glob` and `each ... do` not working

My goal is to be able to include a helper method in my Rails 4 project that will list all images in a particular directory in a view so that I don't have to manually add image_tags each time I add a new image.
I've come across several examples of this, but for my purposes I'd like to allocate this job to a helper method, and I can't for the life of me understand why this isn't working.
myapp_helper.rb
module MyAppHelper
def list_logos(clss)
logos = Dir.glob("engines/myapp/app/assets/images/myapp/logos/*.{gif,png,jpg}")
logos.each do |logo|
content_tag("li", class: clss) do
image_tag logo.gsub("engines/myapp/app/assets/images/", "")
end
end
end
end
show.html.erb
<%= list_logos("companies__company") %>
This just prints out the Dir.glob array. Before, I had tried image_tag("myapp/logos/#{image.split('/').last}" to no avail, and so I thought I might have better luck with the gsub method. Nope.
Funny thing is, if, in my helper method, I just write:
logos = Dir.glob("engines/myapp/app/assets/images/myapp/logos/*.{gif,png,jpg}")
image_tag logos.sample.gsub("engines/petitions/app/assets/images/", "")
the image renders fine, which leads me to believe that it's the logos.each iteration which is failing.
I'm stumped. I'll add that this is an engines-based project that I've inherited, and I'm a relative newbie when it comes to Ruby and Rails, so I very well could be missing something simple. Yay! Thanks in advance.
You need to concatenate and return the tags. Try something like this:
module MyAppHelper
def list_logos(clss)
logos = Dir.glob("engines/myapp/app/assets/images/myapp/logos/*.{gif,png,jpg}")
logos.map do |logo|
content_tag("li", class: clss) do
image_tag logo.gsub("engines/myapp/app/assets/images/", "")
end
end.join
end
end
Also, since you're constructing HTML in the helper, you'll need to use html_safe in the template:
<%= list_logos("companies__company").html_safe %>
Oh, and the reason you saw the result of Dir.glob is that each returns the object it's called on.
module MyAppHelper
def list_logos(clss)
logos = Dir.glob("engines/myapp/app/assets/images/myapp/logos/*.{gif,png,jpg}")
list_items = logos.map do |logo|
content_tag("li", class: clss) do
image_tag logo.gsub("engines/myapp/app/assets/images/", "")
end
end
list_items.join
end
end

Rails 3 + html_safe, raw

html_safe and raw works good inside Viwe, but it dosent work inside action inside controller
a = "<p> sample text </p>"
Inside view <%=a.html_safe%>
give output "Sample text"
Inside controller
def test
a = "<p> sample text </p>"
a.html_safe
end
this returns the as it is "<p> sample text </p>"
please guide me how to make this html_safe work inside controller action....
I guess you should simply do:
def test
#a = "<p> sample text </p>".html_safe
end
Just tried myself, and it works properly. In my view I have
<%= #a %>

Don't escape html in ruby on rails

rails 3 seems to escape everything, including html. I have tried using raw() but it still escapes html. Is there a workaround? This is my helper that I am using (/helpers/application_helper.rb):
module ApplicationHelper
def good_time(status = true)
res = ""
if status == true
res << "Status is true, with a long message attached..."
else
res << "Status is false, with another long message"
end
end
end
I am calling the helper in my view using this code:
<%= raw(good_time(true)) %>
You can use .html_safe like this:
def good_time(status = true)
if status
"Status is true, with a long message attached...".html_safe
else
"Status is false, with another long message".html_safe
end
end
<%= good_time(true) %>
I ran into this same thing and discovered a safer solution than using html_safe, especially once you introduce strings which are dynamic.
First, the updated code:
def good_time(long_message1, long_message2, status = true)
html = "".html_safe
html << "Status is #{status}, "
if status
html << long_message1
else
html << long_message2
end
html
end
<%= good_time(true) %>
This escapes long_message content if it is unsafe, but leaves it unescaped if it is safe.
This allows "long message for success & such." to display properly, but also escapes "malicious message <script>alert('foo')</script>".
The explanation boils down to this -- 'foo'.html_safe returns an ActiveSupport::SafeBuffer which acts like a String in every way except one: When you append a String to a SafeBuffer (by calling + or <<), that other String is HTML-escaped before it is appended to the SafeBuffer. When you append another SafeBuffer to a SafeBuffer, no escaping will occur. Rails is rendering all of your views under the hood using SafeBuffers, so the updated method above ends up providing Rails with a SafeBuffer that we've controlled to perform escaping on the long_message "as-needed" rather than "always".
Now, the credit for this answer goes entirely to Henning Koch, and is explained in far more detail at Everything you know about html_safe is wrong -- my recap above attempts only to provide the essence of the explanation in the event that this link ever dies.

rails: get a teaser/excerpt for an article

I have a page that will list news articles. To cut down on the page's length, I only want to display a teaser (the first 200 words / 600 letters of the article) and then display a "more..." link, that, when clicked, will expand the rest of the article in a jQuery/Javascript way. Now, I've all that figured out and even found the following helper method on some paste page, which will make sure, that the news article (string) is not chopped up right in the middle of a word:
def shorten (string, count = 30)
if string.length >= count
shortened = string[0, count]
splitted = shortened.split(/\s/)
words = splitted.length
splitted[0, words-1].join(" ") + ' ...'
else
string
end
end
The problem that I have is that the news article bodies that I get from the DB are formatted HTML. So if I'm unlucky, the above helper will chop up my article string right in the middle of an html tag and insert the "more..." string there (e.g. between ""), which will corrupt my html on the page.
Is there any way around this or is there a plugin out there that I can use to generate excerpts/teasers from an HTML string?
You can use a combination of Sanitize and Truncate.
truncate("And they found that many people were sleeping better.",
:omission => "... (continued)", :length => 15)
# => And they found... (continued)
I'm doing a similar task where I have blog posts and I just want to show a quick excerpt. So in my view I simply do:
sanitize(truncate(blog_post.body, length: 150))
That strips out the HTML tags, gives me the first 150 characters and is handled in the view so it's MVC friendly.
Good luck!
My answer here should do work. The original question (err, asked by me) was about truncating markdown, but I ended up converting the markdown to HTML then truncating that, so it should work.
Of course if your site gets much traffic, you should cache the excerpt (perhaps when the post is created/updated, you could store the excerpt in the database?), this would also mean you could allow the user to modify or enter their own excerpt
Usage:
>> puts "<p><b>Something</p>".truncate_html(5, at_end = "...")
=> <p><b>Someth...</b></p>
..and the code (copied from the other answer):
require 'rexml/parsers/pullparser'
class String
def truncate_html(len = 30, at_end = nil)
p = REXML::Parsers::PullParser.new(self)
tags = []
new_len = len
results = ''
while p.has_next? && new_len > 0
p_e = p.pull
case p_e.event_type
when :start_element
tags.push p_e[0]
results << "<#{tags.last}#{attrs_to_s(p_e[1])}>"
when :end_element
results << "</#{tags.pop}>"
when :text
results << p_e[0][0..new_len]
new_len -= p_e[0].length
else
results << "<!-- #{p_e.inspect} -->"
end
end
if at_end
results << "..."
end
tags.reverse.each do |tag|
results << "</#{tag}>"
end
results
end
private
def attrs_to_s(attrs)
if attrs.empty?
''
else
' ' + attrs.to_a.map { |attr| %{#{attr[0]}="#{attr[1]}"} }.join(' ')
end
end
end
Thanks a lot for your answers!
However, in the meantime I stumbled upon the jQuery HTML Truncator plugin, which perfectly fits my purposes and shifts the truncation to the client-side. It doesn't get any easier :-)
you would have to write a more complex parsers if you dont want to split in the middle of html elements. it would have to remember if it is in the middle of a <> block and if its between two tags.
even if you did that, you would still have problems. if some put the whole article into an html element, since the parser couldnt split it anywhere, because of the missing closing tag.
if it is possible at all i would try not to put any tags into the articles or keep it to tags that dont contain anything (no <div> and so on). that way you would only have to check if you are in the middle of a tag which is pretty simple:
def shorten (string, count = 30)
if string.length >= count
shortened = string[0, count]
splitted = shortened.split(/\s/)
words = splitted.length
if(splitted[words-1].include? "<")
splitted[0,words-2].join(" ") + ' ...'
else
splitted[0, words-1].join(" ") + ' ...'
else
string
end
end
I would have sanitized the HTML and extracted the first sentence. Assuming you have an article model, with a 'body' attribute that contains the HTML:
# lib/core_ext/string.rb
class String
def first_sentence
self[/(\A[^.|!|?]+)/, 1]
end
end
# app/models/article.rb
def teaser
HTML::FullSanitizer.new.sanitize(body).first_sentence
end
This would convert "<b>This</b> is an <em>important</em> article! And here is the rest of the article." into "This is an important article".
I solved this using following solution
Install gem 'sanitize'
gem install sanitize
and used following code, here body is text containing html tags.
<%= content_tag :div, Sanitize.clean(truncate(body, length: 200, separator: ' ', omission: "... #{ link_to '(continue)', '#' }"), Sanitize::Config::BASIC).html_safe %>
Gives excerpt with valid html.
I hope it helps somebody.
There is now a gem named HTMLTruncator that takes care of this for you. I've used it to display post excerpts and the like, and it's very robust.
If you are using Active Text, I would suggest first converting the text using to_plain_text.
truncate(sanitize(career.content.body.to_plain_text), length: 150).squish

Resources