Regex extract substring ruby - ruby-on-rails

"{\"status\":1,\"redirect\":\"/some/uri/uri2/index.html?post_login=80607979823520\",\"security_token\":\"/cpsess8233434446\"}"
I am getting this response as string and I need to extract security_token value.
I tried to convert the string to Hash by eval method.seems not worked and I need to do a regex match.

You can do this:
require 'json'
a = JSON.load "{\"status\":1,\"redirect\":\"/some/uri/uri2/index.html?post_login=80607979823520\",\"security_token\":\"/cpsess8233434446\"}"
p a["security_token"] #=> "/cpsess8233434446"

You need to parse the JSON data..
result = "{\"status\":1,\"redirect\":\"/some/uri/uri2/index.html?post_login=80607979823520\",\"security_token\":\"/cpsess8233434446\"}"
h = JSON.parse(result)
h['security_token'] # => "/cpsess8233434446"

You can either JSON.load the data and filter for ['security_token'] or use a .match(/security_token/) style regex expression.
I'd suggest the prior for future readability and code maintenance.

Related

Rails params to array

I am sending a list of checkbox selected from PHP file to our Rails API server. All checked items' ID's will be sent in json format (campaign_ids in json_encode from PHP):
I got a URL being passed to our API like this
Started PUT "/campaigns/function.json?campaign_ids=["6","7"]&user_id=0090000007"
I need to get the campaign_ids ["6","7"] and process it like any other array using array.each do || end
How can I convert this to an array so I can use array.each?
The following sample code can achieve it but I think there could be a better way?
campaign_ids = params[:campaign_ids].to_s # [\"6\",\"7\"]
campaign_ids = campaign_ids.gsub(/[^0-9,]/,'') # 6,7
if campaign_ids.size.to_i > 0 # 3 ??
campaign_ids.split(",").each do |campaign_id|
...
end
end
The correct format of the URL should've been campaign_ids[]=6&campaign_ids[]=7. That would automatically yield an array of [6, 7] when you do params[:campaign_ids].
But assuming you can't change the format of the incorrect parameters, you can still get it via JSON.parse(params[:campaign_ids])
Try this
campaign_ids = JSON.parse(params[:campaign_ids])
You get params[:campaign_ids] as a string.
So, you will have to parse that json string to get array elements.
params[:campaign_ids] is already in your desired array format, you need not convert that to string using to_s.
You can do something like this
campaign_ids = params[:campaign_ids]
campaign_ids.each do |campaign_id|
# do the computation here
end

Tidy long string in Ruby

I have a method in Ruby, which needs an API URL:
request_url = "http://api.abc.com/v3/avail?rev=#{ENV['REV']}&key=#{ENV['KEY']}&locale=en_US&currencyCode=#{currency}&arrivalDate=#{check_in}&departureDate=#{check_out}&includeDetails=true&includeRoomImages=true&room1=#{total_guests}"
I want to format it to be more readable. It should take arguments.
request_url = "http://api.abc.com/v3/avail?
&rev=#{ENV['REV']}
&key=#{ENV['KEY']}
&locale=en_US
&currencyCode=#{currency}
&arrivalDate=#{check_in}
&departureDate=#{check_out}
&includeDetails=true
&includeRoomImages=true
&room1=#{total_guests}"
But of course there's line break. I tried heredoc, but I want it to be in one line.
I would prefer to not build URI queries by joining strings, because that might lead to URLs that are not correctly encoded (see a list of characters that need to be encoded in URIs).
There is the Hash#to_query method in Ruby on Rails that does exactly what you need and it ensure that the parameters are correctly URI encoded:
base_url = 'http://api.abc.com/v3/avail'
arguments = {
rev: ENV['REV'],
key: ENV['KEY'],
locale: 'en_US',
currencyCode: currency,
arrivalDate: check_in,
departureDate: check_out,
includeDetails: true,
includeRoomImages: true,
room1: total_guests
}
request_url = "#{base_url}?#{arguments.to_query}"
You could use an array and join the strings:
request_url = [
"http://api.abc.com/v3/avail?",
"&rev=#{ENV['REV']}",
"&key=#{ENV['KEY']}",
"&locale=en_US",
"&currencyCode=#{currency}",
"&arrivalDate=#{check_in}",
"&departureDate=#{check_out}",
"&includeDetails=true",
"&includeRoomImages=true",
"&room1=#{total_guests}",
].join('')
Even easier, you can use the %W array shorthand notation so you don't have to write out all the quotes and commas:
request_url = %W(
http://api.abc.com/v3/avail?
&rev=#{ENV['REV']}
&key=#{ENV['KEY']}
&locale=en_US
&currencyCode=#{currency}
&arrivalDate=#{check_in}
&departureDate=#{check_out}
&includeDetails=true
&includeRoomImages=true
&room1=#{total_guests}
).join('')
Edit: Of course, spickermann makes a very good point above on better ways to accomplish this specifically for URLs. However, if you're not constructing a URL and just working with strings, the above methods should work fine.
You can extend strings in Ruby using the line continuation operator. Example:
request_url = "http://api.abc.com/v3/avail?" \
"&rev=#{ENV['REV']}" \
"&key=#{ENV['KEY']}"

Hashie::Rash being converted to string instead on Json or hash in Ruby on Rails

I am using an API whose reply is in form of Hashie::Rash. an example:
country = #<Hashie::Rash confidence="99" geoname_id=3175395 iso_code="IT" names=#<Hashie::Rash de="Italien" en="Italy" es="Italia" fr="Italie" ja="イタリア共和国" pt_br="Itália" ru="Италия" zh_cn="意大利">>
country.class = Hashie::Rash
I want to convert this to Json, to look like
{"iso_code":"IT","names": {"pt_br":"Itália","es":"Italia","ru":"Италия","en":"Italy","zh_cn":"意大 利","fr":"Italie","de":"Italien","ja":"イタリア共和 国"},"confidence":"99","geoname_id":3175395}
when I try using to_json(), it produces this:
"{\"iso_code\":\"IT\",\"names\":{\"pt_br\":\"Itália\",\"es\":\"Italia\",\"ru\":\"Италия\",\"en\":\"Italy\",\"zh_cn\":\"意大利\",\"fr\":\"Italie\",\"de\":\"Italien\",\"ja\":\"イタリア共和国\"},\"confidence\":\"99\",\"geoname_id\":3175395}"
whose class is a string.
How can I convert it to a JSON or Hash form??. Thanks
I assume that you have to_json format data look like:
str = "{\"iso_code\":\"IT\",\"names\":{\"pt_br\":\"Itália\",\"es\":\"Italia\",\"ru\":\"Италия\",\"en\":\"Italy\",\"zh_cn\":\"意大利\",\"fr\":\"Italie\",\"de\":\"Italien\",\"ja\":\"イタリア共和国\"},\"confidence\":\"99\",\"geoname_id\":3175395}"
then go to terminal and require json and parse it like bellow:
require 'json'
ob = JSON.parse(str)
Then you get json formatted output there and this will be look like:
{"iso_code"=>"IT", "names"=>{"pt_br"=>"Itália", "es"=>"Italia", "ru"=>"Италия", "en"=>"Italy", "zh_cn"=>"意大利", "fr"=>"Italie", "de"=>"Italien", "ja"=>"イタリア共和国"}, "confidence"=>"99", "geoname_id"=>3175395}

Regex in Ruby: expression not found

I'm having trouble with a regex in Ruby (on Rails). I'm relatively new to this.
The test string is:
http://www.xyz.com/017010830343?$ProdLarge$
I am trying to remove "$ProdLarge$". In other words, the $ signs and anything between.
My regular expression is:
\$\w+\$
Rubular says my expression is ok. http://rubular.com/r/NDDQxKVraK
But when I run my code, the app says it isn't finding a match. Code below:
some_array.each do |x|
logger.debug "scan #{x.scan('\$\w+\$')}"
logger.debug "String? #{x.instance_of?(String)}"
x.gsub!('\$\w+\$','scl=1')
...
My logger debug line shows a result of "[]". String is confirmed as being true. And the gsub line has no effect.
What do I need to correct?
Use /regex/ instead of 'regex':
> "http://www.xyz.com/017010830343?$ProdLarge$".gsub(/\$\w+\$/, 'scl=1')
=> "http://www.xyz.com/017010830343?scl=1"
Don't use a regex for this task, use a tool designed for it, URI. To remove the query:
require 'uri'
url = URI.parse('http://www.xyz.com/017010830343?$ProdLarge$')
url.query = nil
puts url.to_s
=> http://www.xyz.com/017010830343
To change to a different query use this instead of url.query = nil:
url.query = 'scl=1'
puts url.to_s
=> http://www.xyz.com/017010830343?scl=1
URI will automatically encode values if necessary, saving you the trouble. If you need even more URL management power, look at Addressable::URI.

JSON string to rails hash

I'm on Rails 2.3 and I'm trying to convert a string that is JSON-formatted to a Rails hash. However, when I use JSON.parse I get a JSON string without the delimiters:
{"source_id":40007,"object":"86088947610496.1","coursewalk_id":"86088947610477.1","description":"","image_uri":"db\/db-files\/
Image_2011-09-24_14.37.37__0000.jpg","latitude":"38.0113439821061","letter":"","letter_A":"","letter_B":"","letter_C":"","lett
er_D":"","letter_E":"","letter_F":"","longitude":"-78.7576854509104","number":"1","mcw_id":71}
Results of JSON.parse:
number1letter_Bcoursewalk_id86088947610477.1letter_Clatitude38.0113439821061letter_Dletter_Eletter_Fmcw_id71longitude-78.75768
54509104letterdescriptionobject86088947610496.1source_id40007letter_Aimage_uridb/db-files/Image_2011-09-24_14.37.37__0000.jpg
Code:
puts string_to_parse
fence_parsed = JSON.parse(string_to_parse)
puts fence_parsed
Any ideas?
Thanks,
Nick
That's just because you're using "puts". If you just type fence_parsed, or p fence_parsed you'll get what you're looking for. puts calls to_s. I hope this clears it up for you, if not let me know and I'll elaborate.

Resources