0

我的客户应该调用的服务的示例 URL 如下所示:

http://www.example.com/providers/?query=eric&group_ids[]=1F23&group_ids[]=423&start=3&limit=20

已经写好的帮助模块/方法是这样的,我应该为我自己的客户使用:

def create_http_request(method, path, options = {})
  # create/configure http
  http = Net::HTTP.new(@base_uri.host, @base_uri.port)
  http.open_timeout = options[:open_timeout] || @open_timeout
  http.read_timeout = options[:read_timeout] || @read_timeout

  # create/configure request
  if method == :get
    request = Net::HTTP::Get.new(path)
  else
    raise ArgumentError, "Error: invalid http method: #{method}"
  end

  return http, request
end

在其他人编写的类似代码的其他部分中,我看到如下内容: 为了调用该 create_http_request 方法:

 def person_search(query, options = {})
  params = {
    query: query,
      group_ids: options[:group_ids],
    start: options[:page] || @default_page,
    limit: options[:page_size] || @default_page_size
  }

  pathSemantic = "/patients/?#{ params.to_param }"
  httpSemantic, requestSemantic = create_http_request(:get, pathSemantic, options)

所以主要是我不明白她在用 params 做什么,为什么我们需要这样做?这是最好的方法吗?

4

1 回答 1

1

您是在询问 to_param 方法吗?它创建一个可在 URL 中使用的参数字符串。你可以在这里阅读:http: //apidock.com/rails/ActiveRecord/Base/to_param

因此,在人员搜索方法中,参数是根据查询、选项哈希中给出的值和对象中存储的默认选项来构造的。它们附加到路径以创建 pathSemantic 字符串,然后将其传递给 create_http_request 方法。

关于。参数的构造——它是一个哈希,查询参数映射到:query键,选项:group_id的值映射到:group_id键,选项:page的值映射到:start等.

  params = {                                         # params is a hash
    query: query,                                    # the key query is mapped to the query method parameter (we got it from the call to the method)
    group_ids: options[:group_ids],                  # the key :group_ids is mapped to the value that we got in the options hash under the :group_id key (we also got the options as a parameter in teh call to the method)
    start: options[:page] || @default_page,          # the key :start is mapped to the value that we got in the options hash under the :page key. In case it is not set, we'll use the value in the instance variable @default_page
    limit: options[:page_size] || @default_page_size # the key :page_size is mapped to the value that we got in the options hash under the :page_size key. In case it is not set, we'll use the value in the instance variable @default_page_size
  }

如果您想知道 x || y 表示法——这意味着如果未设置 x,则将使用 y 的值(这是惯用形式中使用的快捷运算符“或”)

to_param 的方式适用于映射到数组的键:

{group_ids: ["asdf","dfgf","ert"]}.to_param
=> "group_ids%5B%5D=asdf&group_ids%5B%5D=dfgf&group_ids%5B%5D=ert"

这是 URL 编码

"group_ids[]=asdf&group_ids[]=dfgf&group_ids[]=ert"
于 2013-05-01T20:16:06.720 回答