我创建了一个GET端点来使用rails来提供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
OR
localhost:8080/company/data.json?q=AOL&size=10
如何在轨道控制器中处理空格和双引号的上述用例?
答案 0 :(得分:2)
尝试使用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