I have the following code:
url = file.s3_url.blank? ? file.url : file.s3_url
Is there a shorter way to write this?
Thanks!
There is an abstraction for that in ActiveSupport, Object#presence:
url = file.s3_url.presence || file.url
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With