Ruby on Rails: Passing a hash as a parameter for URL parameters... how do I remove the brackets?
I've made this method here:
def get_api_xml_from_url(url, params = {}, api_key = SharedTest.user_api_key)开发者_StackOverflow中文版
response = get(url, params, :format => "xml", :api_key => api_key)
assert_response :success
response_xml_hash = CobraVsMongoose.xml_to_hash(response.body)
return response_xml_hash, response
end
but, the issue is that the params are goofing up the GET() call. I'm guessing because the url doesn't want get(url, {param, praam param}, format, etc)
but rather, it wants, get(url, param, param, param, format, etc)
How do I remove the brackets from the params variable? such that when no params are sent, nothing breaks. =\
so :format and :api_key are the default params you want to pass to the get call in any case, right?
You can merge your defaults with whatever gets passed to your get_api_xml_from_url method in the first place.
get(url, params.merge(:format => "xml", :api_key => api_key)
UPDATE: A little more explanation on whats happening here. get takes two arguments, the url and a hash. Being able to write the hash without curly brackets is just syntactic sugar in ruby. Under the hood, it realizes that your last params are all key/value pairs and it passes them all as just one hash to the function.
What you've done was passing 3 Arguments to get. The url, your params hash (enclosed in curly brackets and therefor recognized as an argument itself) and finally the remaining key/value pairs.
精彩评论