0

I commonly need to use this kind of methods where I have to check if an object exists and if this object returns a specific value or a behavior. Is that a better way to write this code?

def set_current_theme
   if current_tenant && current_tenant.has_custom_domain?
     @theme = Theme.last || Theme.create
   end
end

At a first glance, I would just add one conditional: if current_tenant.has_custom_domain? and that should be enough. But the result is generally that there is no such method (in this case has_custom_domain?) for nil class.

2 Answers2

2

Shorter (and i think better) way is to use &. (it's shorthand for try!) like this.

if current_tenant&.has_custom_domain?
  @theme = Theme.last || Theme.create
end

What does &. (ampersand dot) mean in Ruby?

blackbiron
  • 809
  • 10
  • 17
1

I would suggest early return (so called guard clause) instead of :if statement, because you don't have :else clause:

def set_current_theme
  return unless current_tenant&.has_custom_domain?

  @theme = Theme.last || Theme.create
end
Ruslan Valeev
  • 1,529
  • 13
  • 24