Kashiftufail
Kashiftufail

Reputation: 10885

How Get some specific value from Rails string?

I want to get some specific value from string of Rails like below these are two string.

 1. "http://localhost:3000/admin/shops/assign_shoes?id=50&page=1"

 2. "http://localhost:3000/admin/shops/assign_shoes?id=50"

I always need value of "id" which is "50". Don't matter how many parameters are in string

as query string.

Actually these strings are values of request.referer

Any efficient method?

Thanks

Upvotes: 0

Views: 416

Answers (3)

Paul Richter
Paul Richter

Reputation: 11072

There are several different ways to do this, the common way I know about is parsing the string using the URI class, and making use of the CGI class to extract the query params, like so:

uri = URI.parse(request.referer)
parsed_query = CGI::parse(uri.query).symbolize_keys
id_value = parsed_query[:id].first

Note the .first, as the values of the query params are resolved to arrays. Additionally, the keys are parsed in to strings, therefore I would include symbolize_keys for convenience and consistency.

Upvotes: 1

Surya
Surya

Reputation: 15992

Here is one of the ways:

require 'uri'
require 'cgi'

uri = URI.parse("http://localhost:3000/admin/shops/assign_shoes?id=50&page=1")
# => #<URI::HTTP:0x000001018dc5c8 URL:http://localhost:3000/admin/shops/assign_shoes?id=50&page=1> 

uri_params = CGI.parse(uri.query)
# => {"id"=>["50"], "page"=>["1"]} 

uri_params["id"].first #=> "50" - NOTE: this will be a String!!

However, I'd prefer the answer which uses regular expressions.

Upvotes: 4

Zero Fiber
Zero Fiber

Reputation: 4465

Use regular expressions.

id = /\/admin\/shops\/assign_shoes\?id=(\d+)/.match(request.referer)[1]

Upvotes: 2

Related Questions