Parse a string as if it were a querystring in Ruby on Rails

前端 未结 5 391
终归单人心
终归单人心 2020-11-28 23:12

I have a string like this:

\"foo=bar&bar=foo&hello=hi\"

Does Ruby on Rails provide methods to parse this as if it is a querystring,

相关标签:
5条回答
  • 2020-11-28 23:29

    If you want a hash you can use

    Hash[CGI::parse(x).map{|k,v| [k, v.first]}]
    
    0 讨论(0)
  • 2020-11-28 23:35

    Edit : as said in the comments, symolizing keys can bring your server down if someone want to hurt you. I still do it a lot when I work on low profile apps because it makes things easier to work with but I wouldn't do it anymore for high stake apps

    Do not forget to symbolize the keys for obtaining the result you want

    Rack::Utils.parse_nested_query("a=2&b=tralalala").deep_symbolize_keys
    

    this operation is destructive for duplicates.

    0 讨论(0)
  • 2020-11-28 23:46

    If you talking about the Urls that is being used to get data about the parameters them

    > request.url
    => "http://localhost:3000/restaurants/lokesh-dhaba?data=some&more=thisIsMore"
    

    Then to get the query parameters. use

    > request.query_parameters
    => {"data"=>"some", "more"=>"thisIsMore"}
    
    0 讨论(0)
  • 2020-11-28 23:51

    The

    CGI::parse("foo=bar&bar=foo&hello=hi")
    

    Gives you

    {"foo"=>["bar"], "hello"=>["hi"], "bar"=>["foo"]}
    
    0 讨论(0)
  • 2020-11-28 23:52

    The answer depends on the version of Rails that you are using. If you are using 2.3 or later, use Rack's builtin parser for params

     Rack::Utils.parse_nested_query("a=2") #=> {"a" => "2"}
    

    If you are on older Rails, you can indeed use CGI::parse. Note that handling of hashes and arrays differs in subtle ways between modules so you need to verify whether the data you are getting is correct for the method you choose.

    You can also include Rack::Utils into your class for shorthand access.

    0 讨论(0)
提交回复
热议问题