Jerome
Jerome

Reputation: 6217

access truncate method in model method

truncate is intended as a view helper. However, if a model method needs to be invoked to create a string for use by a controller (with end intent of carting off the string to a dynamically generated javascript)

 "#{title}" + " " + "#{main_text.truncate(length: 120)}" 

fails with undefined method 'truncate' for nil:NilClass The error is misleading as "#{title}" + " " + "#{main_text}" renders properly.

How can one effect truncate then?

Upvotes: 0

Views: 224

Answers (2)

Mark Merritt
Mark Merritt

Reputation: 2695

Even if you are passing in nil to the truncate helper the view should still render...i.e. this should not throw an error..

<%= truncate(nil, length: 120) %>

So, try <%= truncate(main_text, length: 120) %>

It looks like you are trying to use Ruby truncate instead of the Rails view helper...which is why it's throwing undefined method 'truncate' for nil:NilClass. But...main_text is still nil, which you will need to figure out if this is a problem.

As far as "#{title}" + " " + "#{main_text}" rendering properly...it's most likely not. Similar to the above, you can say

"#{nil}" + " " + "#{nil}"

And it will still render the blank space without error.

Upvotes: 1

Deepak Mahakale
Deepak Mahakale

Reputation: 23711

main_text is nil that's why you are getting the error

undefined method 'truncate' for nil:NilClass

To make sure you handle the nil you can use safe navigation operator

"#{title} #{main_text&.truncate(120)}"

This will work on ruby 2.3+

If you are using ruby < 2.3 you can make use of

"#{title} #{main_text.try(:truncate, 120)}"

Upvotes: 2

Related Questions