tags:

views:

210

answers:

3

In a ruby on rails app, I build an array of Project Names and project id values, but want to truncate the length of the names. Current code is:

names = active_projects.collect {|proj| [proj.name, proj.id]}

I have tried to add a truncate function to the block, but am getting undefined method for class error.

Thanks in advance - I just cannot wrap my head around this yet.

A: 

Try Following

name=[]
active_projects.collect {|proj| name << [proj.name, proj.id]}

EDITED this should be

names= active_projects.collect {|proj|  [proj.name.to_s[0..10], proj.id]}
Salil
This looks like it will concatenate the strings, not truncate them.
pkaeding
in fact, it does exactly the same thing as the OP, only worse and semantically wrong.
dominikh
it will produce o/p like name= [ ['salil', 1], ['ander', '2'] ].no check though.
Salil
This worked, thanks.
ander163
+1  A: 

Assuming I understood the question properly:

max_length = 10 # this is the length after which we will truncate
names = active_projects.map { |project|
  name = project.name.to_s[0..max_length] # I am calling #to_s because the question didn't specify if project.name is a String or not
  name << "…" if project.name.to_s.length > max_length # add an ellipsis if we truncated the name
  id = project.id
  [name, id]
}
dominikh
Great - I used this.
ander163
A: 

In a Rails application you can use the truncate method for this.

If your code isn't in a view then you will need to include the TextHelper module in order to make the method available:

include ActionView::Helpers::TextHelper

you can then do:

names = active_projects.collect { |proj| [truncate(proj.name), proj.id] }

The default behaviour is to truncate to 30 characters and replace the removed characters with '...' but this can be overridden as follows:

names = active_projects.collect {
  # truncate to 10 characters and don't use '...' suffix
  |proj| [truncate(proj.name, :length => 10, :omission => ''), proj.id]
}
mikej
The function was in the model, not in a view. I added the line you suggested to the project.rb file, but still get the same error as originally reported. The simpler method of treating the project name (which is a string) as an array and pulling just the first n characters works for now. Thanks.
ander163