Alex Rivera | Logout

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

Asked 2011-02-14T16:07:34.407
17

I have the following code:

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

Is there a shorter way to write this?

Thanks!

Edit
Report

1 Answer

3

I use a utility method.

def until_not_blank(*args)
  args.find {|a| !a.blank? }
end

url = until_not_blank(file.s3_url, file.url)

I typically just put that in my ApplicationController and make it a helper. If you wanted it to be available globally, you could put it in Kernel, or you could monkey-patch Array

class Array
  def first_not_blank
    find {|a| !a.blank?}
  end
end

url = [file.s3_url, file.url].first_not_blank
answered 2011-02-14T17:09:01.907

Your Answer