2015-10-21 11 views
5

Come costruire l'oggetto URI con argomenti di query passando hash?Come costruire l'URI con argomenti di query dall'hash in Ruby

posso generare query con:

URI::HTTPS.build(host: 'example.com', query: "a=#{hash[:a]}, b=#{[hash:b]}")

che genera

https://example.com?a=argument1&b=argument2

Tuttavia penso costruendo stringa di query per molti argomenti sarebbero illeggibili e difficili da mantenere. Mi piacerebbe costruire una stringa di query passando hash. Come nell'esempio qui sotto:

hash = { 
    a: 'argument1', 
    b: 'argument2' 
    #... dozen more arguments 
} 
URI::HTTPS.build(host: 'example.com', query: hash) 

che solleva

NoMethodError: undefined method `to_str' for {:a=>"argument1", :b=>"argument2"}:Hash 

E 'possibile costruire query string sulla base di hash utilizzando URI api? Non voglio scomporre patch hash object ...

risposta

8

Basta chiamare '#to_query' per cancellarlo.

hash = { 
    a: 'argument1', 
    b: 'argument2' 
    #... dozen more arguments 
} 
URI::HTTPS.build(host: 'example.com', query: hash.to_query) 

=> https://example.com?a=argument1&b=argument2

Se non si utilizza rotaie ricordarsi di require 'uri'

+7

'to_query 'è un metodo Rails only. Non esiste in Ruby. –

+1

Le domande di @marc_ferna hanno ruby ​​sul tag rails. È possibile includere: ActiveSupport in progetti non-rail –

1

Per quelle che non utilizzano Rails o Supporto Active, la soluzione utilizzando la libreria standard di Ruby è

hash = { 
    a: 'argument1', 
    b: 'argument2' 
} 
URI::HTTPS.build(host: 'example.com', query: URI.encode_www_form(hash)) 
=> #<URI::HTTPS https://example.com?a=argument1&b=argument2> 
Problemi correlati