2

i have a field which is not required i.e. can be nil. i want to use the ffg: myfield.html_safe in my view. this doesn't work for the items that have no myfield. i get an exception, how do i get html_safe to apply only if the field is defined? thanks

newbie_86
  • 4,520
  • 17
  • 58
  • 89

3 Answers3

12

In Rails, you can use

myfield.try(:html_safe)

Docs: http://api.rubyonrails.org/classes/Object.html#method-i-try

Nikola
  • 694
  • 8
  • 15
11

myfield.html_safe if myfield or myfield.to_s.html_safe

Kelly
  • 40,173
  • 4
  • 42
  • 51
  • you'd get an exception here if you try to do nil.to_s – Yule Mar 29 '11 at 15:29
  • @Yule not according to the [rubydocs on NilClass](http://www.ruby-doc.org/core/classes/NilClass.html) – Kelly Mar 29 '11 at 15:35
  • to_s.html_safe seems to work, no exception is thrown. out of curiousity why does converting to_s make a difference? is nil.html_safe not valid? – newbie_86 Mar 29 '11 at 18:23
  • 2
    the Nil class only has a few basic methods, some of them being the ability to convert to an integer or a string. by using `.to_s`, you are essentially converting `nil` to a String class, and at that point you can use any of the String methods that Rails has added, like `html_safe`. – Kelly Mar 29 '11 at 18:32
0

This should do it...

myfield.html_safe unless myfield.blank?
Yule
  • 9,668
  • 3
  • 51
  • 72