Ruby Rails无法在类初始化方法中生成实例变量以生成HttpParty请求
我在通过Ruby类生成签名时遇到问题。当我进入docker容器时,我能够看到initialize方法中的所有实例变量都是nil,除了@api_key变量 我有以下课程Ruby Rails无法在类初始化方法中生成实例变量以生成HttpParty请求,ruby,httparty,Ruby,Httparty,我在通过Ruby类生成签名时遇到问题。当我进入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"
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
如您所见,通过generate_签名方法中的binding.pry,我可以看到实例变量:
生成签名所需的相对_uri方法没有在字符串中加载@form_id变量
这是控制器:
class FormsController < ApplicationController
def display_form
@form = SeamlessGov::Form.new().create_form
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"}]}
问题是什么?错误在于操作/计算的顺序
def initialize()
@api_key = ENV['SEAMLESS_GOV_API_KEY']
@signature = generate_signature # <= at this point, neither form_id nor timestamp are set. but api key is.
@form_id = ENV['SEAMLESS_GOV_FORM_ID']
@timestamp = Time.now.to_i.to_s
end
@SergioTulentsev我刚刚用create_form方法的输出更新了帖子。只显示api_键。啊,我现在明白了。在设置其他参数之前生成签名。但是api键已经设置好了,这就是为什么你只能看到它。用文本替换屏幕截图。从来没有一个好的理由将代码作为图像发布。
def initialize()
@api_key = ENV['SEAMLESS_GOV_API_KEY']
@signature = generate_signature # <= at this point, neither form_id nor timestamp are set. but api key is.
@form_id = ENV['SEAMLESS_GOV_FORM_ID']
@timestamp = Time.now.to_i.to_s
end