user984621
user984621

Reputation: 48443

Show only a few characters from a string

I have this simple helper (in Rails app):

def shortener(text, text_length = nil)
  if text_length.nil?
    text_size = 60
  else
    text_size = text_length
  end

  #text_size = 60 if text_length.nil? => return the same error as above

  if text.length.to_i > text_size.to_i # HERE IS THE ISSUE
    return "#{text[0..(text_size-5)]}..."
  else
    return text
  end
end

However, I am getting this error:

undefined method `length' for nil:NilClass

Why am I getting this error? Both parameters exist and are integers.

Upvotes: 0

Views: 918

Answers (4)

Agis
Agis

Reputation: 33626

If for some reason you want to roll your own method instead of using the built-in truncate:

def shortener(text = "", text_length = 60)
  "#{text[0...text_length]}..."
end

Upvotes: 4

vidang
vidang

Reputation: 1771

Because you are using Rails, I recommend you to use Rails built-in helper truncate

truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)')

For more information, refer http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate

Upvotes: 8

Alex Siri
Alex Siri

Reputation: 2864

You are getting that error because text is passed as nil.

In order for it to behave like a normal text renderer in rails, you might want to do this:

  def shortener(text, text_length = 60)
    text ||= ''

    if text.length.to_i > text_length.to_i
      return "#{text[0..(max_text_length-5)]}..."
    else
      return text
    end
  end

Upvotes: 0

Denis de Bernardy
Denis de Bernardy

Reputation: 78433

It means text is nil. Use caller to find out why.

Upvotes: 0

Related Questions