了解一段铁路代码

时间:2013-05-01 20:04:09

标签: ruby-on-rails-3.2

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

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做了什么,为什么我们需要这样做?这是最好的方式吗?

1 个答案:

答案 0 :(得分:1)

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

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

重新。参数的构造 - 它是一个哈希,查询参数映射到:查询键,选项的值:group_id映射到:group_id键,选项的值:页面映射到: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"

的网址编码
"group_ids[]=asdf&group_ids[]=dfgf&group_ids[]=ert"