Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 637
pedstrom Avatar asked Feb 14 '11 16:02

pedstrom


3 Answers

There is an abstraction for that in ActiveSupport, Object#presence:

url = file.s3_url.presence || file.url
like image 138
tokland Avatar answered Oct 29 '22 21:10

tokland


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)
like image 24
Jacob Relkin Avatar answered Oct 29 '22 21:10

Jacob Relkin


Maybe, you can do the following:

url = file.s3_url || file.url

This code will only use file.url if file.s3_url is nil. That means that an empty string won't work though. If you want to ensure that an empty string is not used, like you do in your example, then there isn't a shorter way to do this.

like image 42
Pan Thomakos Avatar answered Oct 29 '22 23:10

Pan Thomakos