10

I want to find File extensions like .gif,.jpg,.txt from the uri like http://testasp.vulnweb.com/avatars/noavatar.gif.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
Nidhi Barot
  • 155
  • 1
  • 10

4 Answers4

25

You can use an extname method of File

url = "http://testasp.vulnweb.com/avatars/noavatar.gif"
File.extname(url) #=> .gif
alony
  • 10,725
  • 3
  • 39
  • 46
  • You're assuming that the URL looks like a file path but that's not necessarily a valid assumption. What happens if there's a fragment or CGI parameters? – mu is too short Nov 18 '16 at 19:56
5

There may be an easier way to do this but I'd recommend using a combination of the Pathname and URI libraries

require 'uri'

uri = URI("http://testasp.vulnweb.com/avatars/noavatar.gif")

path = uri.path # /avatars/noavatar.gif

pathname = Pathname.new(path)

extension = pathname.extname # gif

See the Pathname and URI library docs for more info.

Chris Bailey
  • 4,126
  • 24
  • 28
  • Thanx for your replay...my another question is how can i traverse through the source folder of a uri and get extensions?... – Nidhi Barot Jan 06 '12 at 11:56
2

If you are in Rails and you are talking about the request URL path's extension you can do this from a controller or helper:

File.extname(request.path)

Noting that request.path is a method of the request object in the rails controller.

And noting that request.path will never return nil.

Mike P.
  • 198
  • 1
  • 12
0

I know that you asked about extracting file extension, though take a look at this question/answers Determine file type in Ruby it's better and more secure to rely on mime type rather than extension.

Community
  • 1
  • 1
shurikk
  • 534
  • 7
  • 8