Convert POST parameters to hash in Ruby without rails
What's the best library to use to convert the HTTP POST string received from a browser into a Ruby hash? I don't want to use the large rails-based libraries. I am using eventmachine
and evma_ht开发者_JAVA技巧tpserver
, and want to include the lightest library possible that will decode and convert the params string.
Note: I don't need a webserver. I have the encoded post string in hand, and just need to convert it to a hash.
URI.decode_www_form
from the Ruby standard library can do this: http://rubydoc.info/docs/ruby-stdlib/1.9.2/URI#decode_www_form-class_method
You could use the rack
gem for its Rack::Utils.parse_query
method.
If you want lighter than that, you could just copy the source code to the parse_query
and unescape
methods from it.
If you want event lighter (but perhaps not as performant or robust) than that, just implement your own split and lean on CGI.unescape
.
Try this:
require "uri"
result = URI.decode_www_form("your=post¶ms=values").inject({}) {|r, (key,value)| r[key.to_sym] = value;r}
puts result[:your]
puts result[:params]
精彩评论