Ruby on Rails, trim the text - ruby-on-rails

Why this code is not work?
<%= truncate(post.text, :length => post.text.rindex(".", 500)) %>
I need to trim the text on last dot before 500th symbol.

Use the :separator option. It will truncate at the dot before 500 characters
truncate(post.text, :length => 500, :separator => '.')

Related

How can I render custom HTML in Spree with Deface

I am replacing some Spree core template code with Deface and it all works well until I try to make it a bit more custom.
Deface::Override.new(
:virtual_path => "spree/shared/_products",
:replace => "span.price",
:text => "<%= link_to truncateproduct.display_price + '<span class=\"purchase-suggestion\">BUY NOW</span>', :length => 20), product, :class => 'price selling', :itemprop => \"price\", :title => product.name + ': ' + product.display_price %>",
:name => "product_price"
)
Above I am aiming to make the price text a link, and also include a 'BUY NOW' text wrapped in a span for individual styling purpose.
This renders this way:
$15.99<span class="purchase-suggestion">BUY NOW</span>
How can I make Deface evaluate the HTML instead of writing the string?
I have tried doing this in two steps by making two different Deface files, one where I swap the span for the link, and another where I add the span to :insert_bottom. It seems to me it is not possible to use Deface to change the same element twice - is this correct?
Solution
Thanks for answer and conversation in channel. This is the solution:
Deface::Override.new(
:virtual_path => "spree/shared/_products",
:replace => "span.price",
:text => "<%=
link_to ('<span>' + product.display_price + '</span> <span class=\"purchase-suggestion\">BUY NOW</span>').html_safe, product,
:class => 'price selling',
:itemprop => 'price',
:title => product.name + ': ' + product.display_price
%>",
:name => "product_price"
)
.truncate was used for no reason, .html_safe did the job.
Your issue here is with truncate. The result is not marked as HTML-safe, so will be subject to the default escaping when used in views, unless wrapped by raw(). Care should be taken if text contains HTML tags or entities, because truncation may produce invalid HTML (such as unbalanced or incomplete tags).
http://apidock.com/rails/ActionView/Helpers/TextHelper/truncate

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

How to format decimals

I need to format float like price for two decimal places and thousands spaces, like this:
"1 082 233.00"
Use number_to_currency or number_with_precision:
number_with_precision(1082233, :precision => 2,
:separator => '.',
:delimiter => ' ')
# => '1 082 233.00'
See the NumberHelper documentation for details.

rails different currency formats

I need to show user amount presented in different currencies. e.q. :
Your balance: $ 100 000.00
€ 70 000.00
3 000 000,00 руб.
So I need to use number_to_currency three times with different locales(en, eu, ru). What is the right way to do it?
I don't think you actually need different locales, because you have just balances in different currencies. You can simply pass additional arguments to number_to_currency. Something like this:
number_to_currency(70000.00, :unit => "€", :separator => ".", :delimiter => " ", :format => "%u %n")
This will display: € 70 000.00
Additionally it seems that you can set :locale option when calling number_to_currency. It's not documented, but here is the part of the number_to_currency code:
defaults = I18n.translate('number.format''number.format', :locale => options[:locale], :raise => true) rescue {}
currency = I18n.translate('number.currency.format''number.currency.format', :locale => options[:locale], :raise => true) rescue {}
So you should be able to do something like:
number_to_currency(70000.00, :locale => :ru)

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