Rails无法在类初始化方法中生成实例变量以生成httparty请求

时间:2018-07-12 21:29:29

标签: ruby httparty

我在通过Ruby类生成Signature时遇到问题。当我进入Docker容器时,我可以看到initialize方法中的所有实例变量都是nil期望的@api_key变量。

我有以下课程

require 'openssl'
require 'base64'

module SeamlessGov
  class Form
    include HTTParty
    attr_accessor :form_id
    base_uri "https://nycopp.seamlessdocs.com/api"

    def initialize()
      @api_key = ENV['SEAMLESS_GOV_API_KEY']
      @signature = generate_signature
      @form_id = ENV['SEAMLESS_GOV_FORM_ID']
      @timestamp = Time.now.to_i.to_s
    end

    def relative_uri
      "/form/#{@form_id}/elements"
    end

    def create_form
      self.class.get(relative_uri, headers: generate_headers)
    end

    private

    def generate_signature
      OpenSSL::HMAC.hexdigest('sha256', ENV['SEAMLESS_GOV_SECRET'], "GET+#{relative_uri}+#{@timestamp}")
      binding.pry
    end

    def generate_headers
      {
        "Authorization"  => "HMAC-SHA256 api_key='#{@api_key}' signature='#{@timestamp}'",
         Net::HTTP::ImmutableHeaderKey.new('AuthDate') => "#{@timestamp}"
      }
    end
  end
end

如您所见,在binding.pry方法的generate_signature中,我可以看到实例变量:enter image description here

生成签名所需的relative_uri方法不会在字符串中加载@form_id变量。

这是控制器:

class FormsController < ApplicationController
  def display_form
    @form = SeamlessGov::Form.new().create_form
  end
end

解决net/http标头区分大小写: lib/net_http

require 'net/http'

class Net::HTTP::ImmutableHeaderKey
  attr_reader :key

  def initialize(key)
    @key = key
  end

  def downcase
    self
  end

  def capitalize
    self
  end

  def split(*)
    [self]
  end

  def hash
    key.hash
  end

  def eql?(other)
    key.eql? other.key.eql?
  end

  def to_s
    def self.to_s
      key
    end
    self
  end
end

如果我呼叫create_form,则输出为:

{"error"=>true,
 "error_log"=>
  [{"error_code"=>"missing_date_headers",
    "error_message"=>"Request is missing date headers",
    "error_description"=>
     "{\"Host\":\"nycopp.seamlessdocs.com\",\"Connection\":\"close\",\"X-Real-IP\":\"71.249.243.7\",\"X-Forwarded-For\":\"71.249.243.7\",\"X-Forwarded-Host\":\"nycopp.seamlessdocs.com\",\"X-Forwarded-Port\":\"443\",\"X-Forwarded-Proto\":\"https\",\"X-Original-URI\":\"\\/api\\/form\\/\\/elements\",\"X-Scheme\":\"https\",\"Authorization\":\"HMAC-SHA256 api_key='h123xxxxxxxxxx' signature=''\",\"AuthDate\":\"\"}"},
   {"error_code"=>"external_auth_error", "error_message"=>"Date header is missing or timestamp out of bounds"}]}

出了什么问题?

1 个答案:

答案 0 :(得分:1)

错误是按照运算/计算的顺序进行的。

w,y