pedstrom pedstrom - 1 year ago 67
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?


Answer Source

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

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

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download