Rails presence

While we are on the subject of Rails helper methods (yesterday was .parameterize), I learned about the .presence method today thanks to some wonderful feedback from ZogStriP on one of my commits.

I wrote this ternary operator and was pretty happy with myself that I turned a multi-line method I was writing down to one line:

def get_parameterized_title
  SiteSetting.title.parameterize.empty? ? "discourse" : SiteSetting.title.parameterize
end

Did you notice that I had to use SiteSetting.title.parameterize twice? Pretty annoying right? Well, even though I tried to google for a better way of doing a ternary operator in ruby, and didn’t find what I was looking for. It turns out there is a better way! You just need to use the Rails .presence method:

def get_parameterized_title
  SiteSetting.title.parameterize.presence || "discourse"
end

So much cleaner!