Output text size in ruby on rails - ruby-on-rails

How do I get only first (say) 200 characters from my object Article (which is in a table articles with aattributes content and title)?
Thank you

The rails' TextHelper has a truncate method.
So, in your views, you just have to do :
<%= truncate #article.content, :length => 50 %>
Where 50 is the number of characters you want to display.

irb(main):004:0> '0123456789'[3,7]
=> "3456789"
irb(main):005:0> '0123456789'[3..7]
=> "34567"
irb(main):006:0> '0123456789'[3...7]
=> "3456"
Above code and outputs are self explanatory.

now there is a gem; Auto_excerpt, at github.
https://github.com/RipTheJacker/auto_excerpt.

Related

HTML_SAFE allow everything except <span style="font-size: TAG

How do I disallow font size change in html_safe rails 3
I have here a truncated description of an article, and I want to disallow big font sizes in display mode when the user inputs a big font size using tinymce editor
= truncate(event.description.html_safe, :length => 110, :omission => "...")
How can i do that?
You will want to use the sanitize helper before marking it as html_safe. Unfortunately for you, in this case, the blacklist functionality has been removed, so you will need to list literally all of the attributes you do want, in addition to the defaults. It may be easier to use a regex to remove the attribute in question.
Also, for what it's worth, raw(event.description) does the same as event.description.html_safe, but will not blow up on a nil value (not sure what your validation rules are), so it is generally preferred.
Edit:
Sanitize example usage (from http://apidock.com/rails/v3.2.8/ActionView/Helpers/SanitizeHelper/sanitize ):
truncate( raw( sanitize(event.description, :tags => %w(table tr td), :attributes => %w(id class style) ) ), :length => 110, :omission => "...")
Note: Truncating HTML like that can lead to some weird and hard-to-track-down errors, by creating invalid HTML because of cut-off end tags.

Rails truncate helper with link as omit text

I'm quite long description that I want to truncate using truncate helper.
So i'm using the:
truncate article.description, :length => 200, :omission => ' ...'
The problem is that I want to use more as a clickable link so in theory I could use this:
truncate article.description, :length => 200, :omission => "... #{link_to('[more]', articles_path(article)}"
Omission text is handled as unsafe so it's escaped. I tried to make it html_safe but it didn't work, instead of link [more] my browser is still showing the html for that link.
Is there any way to force truncate to print omission link instead of omission text?
I would suggest doing this on your own in a helper method, that way you'll have a little more control over the output as well:
def article_description article
output = h truncate(article.description, length: 200, omission: '...')
output += link_to('[more]', article_path(article)) if article.description.size > 200
output.html_safe
end
With Rails 4, you can/should pass in a block for the link:
truncate("Once upon a time in a world far far away",
length: 10,
separator: ' ',
omission: '... ') {
link_to "Read more", "#"
}
Dirty solution... use the method "raw" to unescape it.
you have to be sure of "sanity" of your content.
raw(truncate article.description, :length => 200, :omission => "... #{link_to('[more]', articles_path(article)}")
raw is a helper acting like html_safe .
bye
edit: is not the omission of being escaped , but the result of truncate method.
I encountered a similar situation and this did the trick. Try (line breaks for readability):
(truncate h(article.description),
:length => 200,
:omission => "... #{link_to('[more]',articles_path(article)}")
.html_safe
You can use h to ensure sanity of article description, and since you are setting the link_to to a path you know to not be something potentially nefarious, you can mark the resulting string as html_safe without concern.
TextHelper#truncate has a block form of truncate, which lets you use a link_to that isn't escaped, while still escaping the truncated text:
truncate("<script>alert('hello world')</script>") { link_to "Read More", "#" }
#=> <script>alert('hello world'...Read More
The only one that worked for me :
<%= truncate(#article.content, length: 200, omission: " ... %s") % link_to('read more', article_path(#article)) %>
I had the same problem, in my case i just used :escape => false.
That worked:
truncate article.description, :length => 200, :omission => "... #{link_to('[more]', articles_path(article)}", :escape => false
From documentation :
The result is marked as HTML-safe, but it is escaped by default, unless :escape is false....
link: http://apidock.com/rails/ActionView/Helpers/TextHelper/truncate

Formatting Tables in Prawn (this seems to be a common problem)

I"m having no luck formatting a table in a PDF served from a Rails action using Prawn.
Here's the code, but it doesn't apply any of the formatting:
p = Prawn::Document.new(:page_size => "A4")
data = []
data << ["alpha", "brava", "charlie"]
data << ["delta", "echo", "foxtrot"]
p.table(data) do
row(0).style(:background_color => 'dddddd', :size => 9, :align => :center, :font_style => :bold)
cells[0,0].background_color = '999999'
end
p.render
Any clues?
Which version of prawn are you using? I had all sorts of issues with things not working as expected, then I upgraded to prawn 0.11.1.pre and it sorted it all.
See Prawn Tables: Block is not executing which is pretty much the same question.

How can I limit the amount of words displayed from a Ruby string?

the Ruby code is below:
<%= product.advert_text -%>
What script can limit the amount of words?
Since you are working with Rails, you can use the truncate method.
So, something like:
<%= truncate(product.advert_text, :length => 20) -%>
The :length option sets the # of characters to truncate at & will add ellipses at the end (you can override the default ellipses with the :omission option - see the documentation on my link).
If you want to limit to a certain number of words, the easiest way is going to be to split on space and then join the desired number of words back into a string.
<%=product.advert_text.split.slice(0, limit).join(" ") -%>

Maximum length on a textarea in Ruby on Rails

I tried applying the :maxlenght => 40 on a textarea on my form.
But it didn't work out.
Can we have a length limit on a textarea?
The code for text area is
<%= f.text_area :data,
:rows => 2,
:cols => 60 ,
:maxlength => 140,
:autocomplete => :off,
:class => "textareabytes" %>
Just like Rahul said, there's no maxlength attribute for textarea in HTML. Only text input's have that.
The thing you need to remember, is that RoR's text_area function (and all of RoR's HTML-generator functions) accept any argument you'll give them. If they don't recognized the parameter, then the'll just convert it to HTML.
<%=f.text_area :data, :hellothere => "hello to you too"%>
Will output this HTML:
<textarea name="data" hellothere="hello to you too"></textarea>
I know it's hard to remember, but Ruby on Rails isn't magic, it just does a lot of things for you. The trick is to know how it does them, so you can understand why they work, and how to fix them when they don't!
Could it be due to a typo?
":maxlenght => 40 " in your post is misspelt.
EDIT:
I didn't read your post carefully. I think there is no maxlength attribute for textarea in HTML. You will have to handle it in JavaScript. There is more information in "MaxLength on a Textarea".
Not strictly what you're after of course, but, you can always put a:
validates_length_of :data, max: 40
on your model. Won't stop the textarea size of course :)
You can use the maxlength attribute. It is new for the tag in HTML5. It should work nowadays.

Resources