向 Twitter 发出 HTTP 请求时未定义方法“OAuth”api

Undefined method `OAuth' when making HTTP request to Twitter api

我在尝试向 Twitter 流发送请求时收到以下 OAuth 错误 api:

"#NoMethodError: undefined method `OAuth' for #TwitterMoment:0x007fa081d821f0"

def query
 authorisation_header = OAuth oauth_consumer_key=ENV["oauth_consumer_key"], oauth_nonce=ENV["oauth_nonce"], oauth_signature=ENV["oauth_signature"], oauth_signature_method=ENV["oauth_signature_method"], oauth_timestamp=ENV["oauth_timestamp"], oauth_token=ENV["oauth_token"], oauth_version=ENV["oauth_version"]
 response = HTTParty.get("https://stream.twitter.com/1.1/statuses/filter.json?locations=-#{@bounds}", headers: {"Authorization" => authorisation_header})
end

OAuth 包含在我的 gemfile 中。

任何想法将不胜感激!这是我的第一个 Stack Overflow 问题 :)

您在此处将 OAuth 用作 function/method,但该方法不存在。 oauth gem 中的任何地方都没有 def OAuth(...),所以它会爆炸并给你 NoMethodError。

Header example at the bottom of this question 来看,我认为您将 header 字符串与 Ruby 代码混淆了。

相反,您需要自己制作字符串(为了安全起见有点烦人),或者使用 the OAuth gem's 方法 (API) 来完成。

这里是an example from the OAuth github repo

consumer = OAuth::Consumer.new(
  options[:consumer_key],
  options[:consumer_secret],
  :site => "http://query.yahooapis.com"
)

access_token = OAuth::AccessToken.new(consumer)

response = access_token.request(
  :get,
  "/v1/yql?q=#{OAuth::Helper.escape(query)}&format=json"
)
rsp = JSON.parse(response.body)
pp rsp

此示例可能适合您(抱歉,我无法在本地进行测试):

def query
  consumer = OAuth::Consumer.new(
    ENV["oauth_consumer_key"],
    ENV["oauth_consumer_token"],
    site: "https://stream.twitter.com"
  )
  access_token = OAuth::AccessToken.new(consumer)

  response = access_token.request(
    :get,
    "/1.1/statuses/filter.json?locations=-#{OAuth::Helper.escape(@bounds)}"
  )
  response = JSON.parse(response.body)
  pp response  # Just a bit of debug printing for the moment; remove this later.
  response
end

补遗:

通常我可能会指示您使用现有的 Twitter 客户端 gem,例如 https://github.com/sferik/twitter,但在这种情况下,他们似乎没有实现 Moments API还没有。