Search code examples
ruby-on-railsstringtruncateacts-as-taggable-on

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...


Solution

  • 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 %>