我如何在请求中粘贴变量?

问题描述 投票:0回答:1

我需要使用Post生成一个值,并将该值传递给查询并删除。这该怎么做?是否可以在请求get或delete的def检索方法中直接传递变量的值?[我想使用在存储伪造的gem的var中生成的相同值,并同时传递get和delete。] [1]

  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 

  [1]: https://i.stack.imgur.com/Zidpn.jpg
http-post httparty
1个回答
0
投票

如果我理解正确,您想生成一些值并将它们传递给两个请求。您可以在初始化程序中进行操作,并在所有请求中使用:

class Crud
  include HTTParty
  base_uri 'http://dummy.restapiexample.com/api/v1'

  def initialize
    codigo  = Faker::Number.number(digits: 5)
    # or make it instance variable if you need it in the request further
    # @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)
    @options = { id: codigo, name: nome, salary: salario, age: idade }
  end

  def create 
    @headers = {
      'Accept' => 'application/vnd.tasksmanager.v2',
      'Content-Type' => 'application/json'
    }

    self.class.post('/create', body: @options, headers: @headers) 
  end

  def retrieve
    self.class.get('/employee/1', query: @options) 
    # or if you need to pass the id only, not sure how works the service
    # self.class.get('/employee/1', query: { id: @codigo }) 
    # self.class.get("/employee/#{ @codigo }")
  end 
end

> client = Crud.new # here you generate @options
> client.create
> client.retrieve

请阅读红宝石中的变量-局部变量,实例变量和全局变量之间有什么区别。全局变量应在极少数情况下使用,更多时候需要实例/局部变量。

© www.soinside.com 2019 - 2024. All rights reserved.