ruby - 如何通过 HTTParty 传递请求中的变量?
问题描述
我需要使用 Post 生成一个值并在查询中传递这个值并删除。这个怎么做?
def retrieve
是否可以在request get或delete
的方法中直接传递变量的值?我想使用在存储伪造 gem 的 var 中生成的相同值,并同时传递 get 和 delete。
require 'HTTParty'
require 'httparty/request'
require 'httparty/response/headers'
class Crud
include HTTParty
def create
@@codigo = Faker::Number.number(digits: 5)
@nome = Faker::Name.first_name
@salario = Faker::Number.decimal(l_digits: 4, r_digits: 2)
@idade = Faker::Number.number(digits: 2)
@base_url = 'http://dummy.restapiexample.com/api/v1/create'
@body = {
"id":@@codigo,
"name":@nome,
"salary":@salario,
"age":@idade
}.to_json
@headers = {
"Accept": 'application/vnd.tasksmanager.v2',
'Content-Type': 'application/json'
}
@@request = Crud.post(@base_url, body: @body, headers: @headers)
end
def retrieve
self.class.get('http://dummy.restapiexample.com/api/v1/employee/1')
end
end
解决方案
只需解析来自 API 的响应并使用获取的 id。创建员工时不需要传递id,它是自动生成的
class Crud
include HTTParty
base_uri 'http://dummy.restapiexample.com/api/v1'
def create
nome = Faker::Name.first_name
salario = Faker::Number.decimal(l_digits: 4, r_digits: 2)
idade = Faker::Number.number(digits: 2)
#note, you should pass body as JSON string
body = { name: nome, salary: salario, age: idade }.to_json
headers = {
'Accept' => 'application/vnd.tasksmanager.v2',
'Content-Type' => 'application/json'
}
self.class.post('/create', body: body, headers: headers)
end
def retrieve(id)
self.class.get("/employee/#{ id }")
end
end
> client = Crud.new
> response = client.create
> id = JSON.parse(response)['id']
> client.retrieve(id)
请阅读 ruby 中的变量 - 局部变量、实例变量和全局变量之间的区别。全局变量应该在极少数情况下使用,更多时候你需要实例/本地变量。
推荐阅读
- javascript - 如何根据 id 查找嵌套数组元素的索引?
- haskell - Haskell在一个简单的行上输入“=”解析错误
- javascript - 用 Not Null 对 findAll 进行续集
- javascript - 如何在进一步执行代码之前等待 ajax 响应?
- php - 尝试使用 foreach 使用 php 创建动态 html 元素时出错
- node.js - reactjs config.js 如何读取配置 JSON
- python - 全局变量不适用于线程 - Python
- c++ - 在 Windows C++ 中获取所有格式的剪贴板数据
- google-chrome - Chrome extension - get tab url in context menu onClicked event when used on PDF document
- c++ - Linux 不尊重 SCHED_FIFO 优先级?(正常或 GDB 执行)