Reputation: 54949
I have this function
application_helper.rb
def nl2br(s)
s.gsub(/\n/, '<br/>')
end
View
<%= nl2br(@event.rules).html_safe %>
Error:
undefined method `gsub' for nil:NilClass
At times the content can be nil
so which is the best way to handle it?
When I add unless s.nil?
in the function I get html_safe undefined method error
.
Upvotes: 1
Views: 2170
Reputation: 46479
(Updated 2019)
With modern Ruby (2.3+), you can use the safe navigation operator:
def nl2br(s)
s&.gsub(/\n/, '<br/>')
end
If s
is nil, s&.gsub
will fall back to nil, which will then output as empty string.
(Original answer from 2015)
Simple trick, just use an OR to setup a default:
def nl2br(s)
(s||'').gsub(/\n/, '<br/>')
end
Alternatively, since nil.to_s
evaluates to an empty string, you can do:
def nl2br(s)
s.to_s.gsub(/\n/, '<br/>')
end
Upvotes: 6