user2974739
user2974739

Reputation: 639

Ruby URI - How to get entire path after URL

How do you get the full path of the URL given the following

uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413")

I just want posts?id=30&limit=5#time=1305298413

I tried uri.path and that returns /posts and ui.query returns 'id=30&limit=5'

Upvotes: 9

Views: 8699

Answers (4)

Henrik N
Henrik N

Reputation: 16294

A bit of an artsy solution, for completeness – others may be more reasonable :)

uri.dup.tap { _1.scheme = _1.user = _1.password = _1.host = _1.port = nil }.to_s

Though a benefit of this solution is that it also handles URI::Generic like you'd get from parsing a standalone path:

uri = URI.parse("/foo?bar#baz")  # => #<URI::Generic /foo?bar#baz>

Solutions that rely on URI::HTTP#request_uri won't work with URI::Generic. So if you're writing code that accepts both full URLs and paths, that may be a factor.

Upvotes: 1

sawa
sawa

Reputation: 168269

File.basename("http://foo.com/posts?id=30&limit=5#time=1305298413")
# => "posts?id=30&limit=5#time=1305298413"

Upvotes: -1

fdisk
fdisk

Reputation: 438

The method you are looking for is request_uri

uri.request_uri
=> "/posts?id=30&limit=5"

You can use any method you'd like to remove the leading / if needed.

Edit: To get the part after the # sign, use fragment:

[uri.request_uri, uri.fragment].join("#")
=> "/posts?id=30&limit=5#time=1305298413"

Upvotes: 17

tessi
tessi

Reputation: 13574

You can ask the URI object for its path, query, and fragment like this:

"#{uri.path}?#{uri.query}##{uri.fragment}"
# => "/posts?id=30&limit=5#time=1305298413"

or (a little more consice, but less explicit):

"#{uri.request_uri}##{uri.fragment}"
# => "/posts?id=30&limit=5#time=1305298413"

Upvotes: 5

Related Questions