How to Extract Url Parameters from a Url With Ruby or Rails

How to extract URL parameters from a URL with Ruby or Rails?

I think you want to turn any given URL string into a HASH?

You can try http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000075

require 'cgi'

CGI::parse('param1=value1¶m2=value2¶m3=value3')

returns

{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}

Extract url params in ruby

As I said above, you only need to escape slashes in a Regexp literal, e.g. /foo\/bar/. When defining a Regexp from a string it's not necessary: Regexp.new("foo/bar") produces the same Regexp as /foo\/bar/.

As to your larger problem, here's how I'd solve it, which I'm guessing is pretty much how you'd been planning to solve it:

PATTERN_PART_MATCH = /:(\w+)/
PATTERN_PART_REPLACE = '(?<\1>.+?)'

def pattern_to_regexp(pattern)
expr = Regexp.escape(pattern) # just in case
.gsub(PATTERN_PART_MATCH, PATTERN_PART_REPLACE)
Regexp.new(expr)
end

pattern = "/foo/:foo_id/bar/:bar_id"
expr = pattern_to_regexp(pattern)
# => /\/foo\/(?<foo_id>.+?)\/bar\/(?<bar_id>.+?)/

str = "/foo/1/bar/2"
expr.match(str)
# => #<MatchData "/foo/1/bar/2" foo_id:"1" bar_id:"2">

Rails Routes: Programmatically extract params from a URL

You can parse the URL, read the query string and convert them to hash.

u = URI.parse("http://localhost:3000/blogs/213?published=true")
cgi_params = u.query.split('&').map { |e| e.split('=') }.to_h

Merge them with params that you got using Rails.application.routes.recognize_path

How to get a specific value from url in ruby on rails

Do can get it like this:

require 'uri'

url = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-xxx"

uri = URI.parse(url)
params = CGI::parse(uri.query)

params['token'] # => 'EC-xxx'

How to extract a parameter from a URL using a regex pattern

Don't use regular expressions, use a well-tested wheel.

Ruby's URI class is your friend, in particular decode_www_form:

require 'uri'

uri = URI.parse('http://foo.com?code=768140119')
uri.query # => "code=768140119"
URI.decode_www_form(uri.query) # => [["code", "768140119"]]
URI.decode_www_form(uri.query).to_h # => {"code"=>"768140119"}

As for extracting the value of a parameter of a tag, Nokogiri makes it easy, just treat the Node like a hash:

require 'nokogiri'

doc = Nokogiri::HTML("
<html>
<body>
<a href='path/to/foo'>bar</a>
</body>
</html>
")

doc.at('a')['href'] # => "path/to/foo"

You don't need to waste time typing attr(...).



Related Topics



Leave a reply



Submit