How do I access Sinatra params using a symbol?

这一生的挚爱 提交于 2019-12-06 22:40:18

问题


In Sinatra, I use params to get the key/value passed through the URL query string. I noticed I can use either a string or a symbol as the key to get the value. So if the URL is:

http://localhost:4567/x?a=1&b=2

Then:

params[:a] # => "1"
params["a"] # => "1"
params.to_s # => '{"name"=>"x", "a"=>"1", "b"=>"2"}'
params.class # => Hash

I can tell params is a Hash. But this doesn't seem to be a common behavior of a Hash.

h = {"a" => "1", "b" => "2"}
h["a"] # => "1"
h[:a] # => nil

Can someone please explain how this is achieved through Sinatra?


回答1:


Always a good idea to have a read of the source. Specifically, the indifferent_params method.

# Enable string or symbol key access to the nested params hash.
def indifferent_params(params)
  params = indifferent_hash.merge(params)
  params.each do |key, value|
    next unless value.is_a?(Hash)
    params[key] = indifferent_params(value)
  end
end

As the comment states, it's this method (invoked on line 704 of the same file) that allows string and symbol access to the params hash.



来源:https://stackoverflow.com/questions/8619707/how-do-i-access-sinatra-params-using-a-symbol

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!