skadoosh
skadoosh

Reputation: 481

How to compare url and filepath in Rails

Is there a way to distinguish between url and a file path.

e.g.

 user.avatar.url  
 return -> '/home/pic.png' #if no image url is present  
 return -> 'https://...' #if image url is present.

Is there a way where I could check if the url returned is a link or a file path?

Upvotes: 1

Views: 623

Answers (3)

Rajesh Kolappakam
Rajesh Kolappakam

Reputation: 2125

uri = URI.parse(user.avatar.url)
if uri.scheme == 'http' or uri.scheme == 'https'
   # It is a web URL
elsif File.file?(user.avatar.url)
   # It is a file
else
   # Unknown
end

Upvotes: 2

Oleg Haidul
Oleg Haidul

Reputation: 3732

For example, in Paperclip:

user.avatar.exists?

Upvotes: 0

kobaltz
kobaltz

Reputation: 7070

Check out http://railscasts.com/episodes/244-gravatar

You can check if the user has a avatar_url using the present? method check. If it does, then return the URL, otherwise revert to a default image.

def avatar_url(user)
  if user.avatar_url.present?
    user.avatar_url
  else
    default_url = "#{root_url}images/guest.png"
    gravatar_id = Digest::MD5.hexdigest(user.email.downcase)
    "http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}"
  end
end

Upvotes: 0

Related Questions