简体   繁体   中英

Rails truncate strings in an array

In my app I'm trying to truncate a string of tags that get displayed. I've tried doing it this way:

<%= @medium.marker_list.map { |m| 
      link_to truncate('+ ' + m.titleize, length: 5), 
              :controller => "media", :action => "index", :media => m 
    }.join(' ').html_safe %>

The problem is that if any string is greater than 5 it replaces the whole string with ellipsis instead of replacing just the characters that are longer than the set length.

How do I get this to output correctly?

I'm creating the tags through the acts-as-taggable gem.

** EDIT **

So if I have list of tags like this: example, test, product, listing

it returns this: ..., test, ..., ...

when it should be returning this: examp...,test,produ..., listi...

Try this:

%w(example test product listing).map { |w| w.size > 5 ? w[0,5] + "..." : w }

Output:

[examp..., test, produ..., listi...]

So in your code you could implement that like this (untested):

# Helper method
def truncate_tag(tag)
  tag.size > 5 ? tag[0,5] + "..." : tag
end

# View
<%= @medium.marker_list.map { |m|
    link_to truncate_tag(m.titleize),
    :controller => "media",
    :action => "index",
    :media => m
}.join(' ').html_safe %>

How about going for a simple ruby solution

<%= @medium.marker_list.map { |m| 
      link_to "+ {m.titalize}".gsub("+ {m.titalize}"[5..-1],"..."), 
              :controller => "media", :action => "index", :media => m 
    }.join(' ').html_safe %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM