如何从 url 查询参数中检查 rails 参数散列包含双引号字符串?
How to check rails params hash from url query parameter contains double quoted string?
我使用 rails 创建了一个 GET 端点来为 API 提供服务。我希望能够检查用户何时为 url.
中的查询参数传递双引号
例如,用户可以通过传递带有双引号或不带引号的查询参数来调用以下端点。如果在查询参数中找到双引号,我的应用程序预计会有不同的行为..
localhost:8080/company/data.json?q="America Online in UK"&size=10
现在用户也可以像这样调用不带双引号的端点:
localhost:8080/company/data.json?q=America+Online+in+UK&size=10
或
localhost:8080/company/data.json?q=AOL&size=10
如何在 rails 控制器中处理有关空格和双引号的上述用例?
试试 request.fullpath
。此外,params[:q]
的内容应更改为显示转义字符:
http://localhost:3000/?q=hello
request.fullpath
# => "/?q=hello"
params[:q]
# => "hello"
http://localhost:3000/?q=hello+world
request.fullpath
# => "/?q=hello+world"
params[:q]
# => "hello world"
http://localhost:3000/?q="hello world"
request.fullpath
# => "/?q=%22hello%20world%22"
params[:q]
# => "\"hello world\""
评论中要求的进一步回答:
require "uri" # not required inside Rails
raw = "/?q=%22hello%20world%22"
clean = URI.unescape(raw)
# => "/?q=\"hello world\""
pattern = /\A\/\?q\=\"(.*)\"\z/
clean.match(pattern)[1]
# => "hello world"
更实用的方法:
def query
if (q = params[:q]).present? && with_quotes?(q)
q.gsub("\"", "")
end
end
def with_quotes?(string)
string =~ /\A\"/
end
我使用 rails 创建了一个 GET 端点来为 API 提供服务。我希望能够检查用户何时为 url.
中的查询参数传递双引号例如,用户可以通过传递带有双引号或不带引号的查询参数来调用以下端点。如果在查询参数中找到双引号,我的应用程序预计会有不同的行为..
localhost:8080/company/data.json?q="America Online in UK"&size=10
现在用户也可以像这样调用不带双引号的端点:
localhost:8080/company/data.json?q=America+Online+in+UK&size=10
或
localhost:8080/company/data.json?q=AOL&size=10
如何在 rails 控制器中处理有关空格和双引号的上述用例?
试试 request.fullpath
。此外,params[:q]
的内容应更改为显示转义字符:
http://localhost:3000/?q=hello
request.fullpath
# => "/?q=hello"
params[:q]
# => "hello"
http://localhost:3000/?q=hello+world
request.fullpath
# => "/?q=hello+world"
params[:q]
# => "hello world"
http://localhost:3000/?q="hello world"
request.fullpath
# => "/?q=%22hello%20world%22"
params[:q]
# => "\"hello world\""
评论中要求的进一步回答:
require "uri" # not required inside Rails
raw = "/?q=%22hello%20world%22"
clean = URI.unescape(raw)
# => "/?q=\"hello world\""
pattern = /\A\/\?q\=\"(.*)\"\z/
clean.match(pattern)[1]
# => "hello world"
更实用的方法:
def query
if (q = params[:q]).present? && with_quotes?(q)
q.gsub("\"", "")
end
end
def with_quotes?(string)
string =~ /\A\"/
end