pedstrom pedstrom - 5 months ago 9
Ruby Question

Ruby shorthand for "use this if it isn't blank, otherwise use that"

I have the following code:

url = file.s3_url.blank? ? file.url : file.s3_url


Is there a shorter way to write this?

Thanks!

Answer

Well, you could write a method on whatever file is an instance of (say S3File):

class S3File 
   def real_url
     self.s3_url.blank? ? self.url : self.s3_url
   end
   #...
end

Then it gets real simple:

url = file.real_url 

As @tokland said, you could monkey patch Object to use an or_if method, which would be implemented like this:

class Object
   def or_if(method, val = nil)
      self.send(method) ? (block_given? ? yield : val) : self
   end         
end

This way, you'd be able to do this:

url = file.s3_url.or_if(:blank?) { file.url }

Or this:

url = file.s3_url.or_if(:blank?, file.url)