ruby on rails - Unable to convert url params string to hash and then back to url string -


input params string (input format cannot changed)

something=1,2,3,4,5&something_else=6,7,8 

expected output:

something=1,2,3,4,5&something_else=6,7,8 

what doing:

params = 'something=1,2,3,4,5' cgi::parse(params) cgi.unescape(cgi.parse(params).to_query) 

and getting output:

something[]=1,2,3,4,5 

when did cgi::parse(params) getting : {"something"=>["1,2,3,4,5"]}

which wrong because not array, string "1,2,3,4,5" being converted array when did cgi parse.

the reason need cgi parse because need manipulate url params.

is there other possible way can convert in right way , maintain params format?

the cgi module complete dinosaur , should thrown in garbage because of how bad is, reason persists in ruby core. maybe day refactor , make workable. until then, skip , use better uri, built-in.

given irregular, non-compliant query string:

query_string = 'something=1,2,3,4,5&something_else=6,7,8' 

you can handle using decode_www_form method handles query-strings:

require 'uri' decoded = uri.decode_www_form(query_string).to_h # => {"something"=>"1,2,3,4,5", "something_else"=>"6,7,8"} 

to re-encode call encode_www_form , force unescape undo it's correctly doing handle , values:

encoded = uri.unescape(uri.encode_www_form(decoded)) # => "something=1,2,3,4,5&something_else=6,7,8" 

that should effect want.


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -