我正在使用 RestClient gem 为 REST API 编写一个 ruby 客户端。在查看示例时,我看到使用不同的代码来实现基本相同的结果,但没有对差异进行任何解释。
client = RestClient::Resource.new('https://example.com/')
response = client.get
VS
response = RestClient.get('https://example.com/')
如果我可以使用 get
方法实现相同的效果,那么使用 Resource
类有什么好处?
最佳答案
代码重用。当您处理 API,并且需要使用不同的参数和/或路径一遍又一遍地访问相同的基本 url 时,它特别有用。正如文档所示,一旦构建了基础资源:
client = RestClient::Resource.new('https://example.com/')
您可以轻松访问此资源下的其他路径:
response = client["/users/1"].get
这相当于
response = RestClient.get("https://example.com/users/1")
但打字/重复次数较少。
关于ruby - RestClient 使用 Resource 进行 GET 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24519621/