简体   繁体   English

如何从url查询参数检查rails params hash包含双引号字符串?

[英]How to check rails params hash from url query parameter contains double quoted string?

I created a GET endpoint to serve an API using rails. 我创建了一个GET端点来使用rails来提供API。 I want to be able to check for when the user passes double quotes for the query parameter in the url. 我希望能够检查用户何时为url中的查询参数传递双引号。

So for example the user could call the below endpoint by passing the query parameter with double quotes or no quotes. 因此,例如,用户可以通过使用双引号或无引号传递查询参数来调用以下端点。 My application is expected to behave differently if the double quotes are found in the query params.. 如果在查询参数中找到双引号,我的应用程序预计会有不同的行为。

localhost:8080/company/data.json?q="America Online in UK"&size=10

Now the user can also call the endpoint with no double quotes like this: 现在用户也可以调用没有双引号的端点,如下所示:

localhost:8080/company/data.json?q=America+Online+in+UK&size=10

OR 要么

localhost:8080/company/data.json?q=AOL&size=10

How do I handle the above use-cases in a rails controller with respect to spaces and double quotes? 如何在rails控制器中处理空格和双引号中的上述用例?

Try with request.fullpath . 尝试使用request.fullpath Also, the content of params[:q] should change to show the escaped characters: 此外, 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\""

Further answer as requested in comment: 评论中要求的进一步答复:

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"

A more practical method: 一种更实用的方法:

def query
  if (q = params[:q]).present? && with_quotes?(q)
    q.gsub("\"", "")
  end
end


def with_quotes?(string)
  string =~ /\A\"/
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM