【问题标题】:Why am I getting a nil object instead of a shortlink from bitly?为什么我从 bitly 得到一个 nil 对象而不是一个短链接?
【发布时间】:2011-03-13 06:09:06
【问题描述】:

我正在使用基于此示例的足够简单的实现:http://www.appelsiini.net/2010/using-bitly-with-httparty

我把这个文件放在lib文件夹(bitly.rb)

require 'rubygems'
require 'httparty'
class Bitly
  include HTTParty
  base_uri "api.bit.ly"

  @@login   = "goldhat"
  @@api_key = "R_xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

  def self.shorten(url)
    response = get("/v3/shorten?login=#{@@login}&apiKey=#{@@api_key}&longUrl=#{url}")
    response["data"]["url"]
  end
end

由于某种原因,我得到了一个 nil 对象。好像 bitly 甚至没有响应任何数据。我在控制台和应用程序中对其进行了测试,得到了同样的错误:

NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]
        from c:/goldhat_production/lib/bitly.rb:9:in `shorten'
        from (irb):1

有什么想法吗?

【问题讨论】:

  • 您的代码按预期工作。您的错误似乎是由于代码中的其他问题(假设您收到 AR::Base 错误)。你能再贴一些代码吗?
  • 嗯,虽然我在控制台中输入 Bitly.shorten("stackoverflow.com") 时它不起作用,只是参考我上面粘贴的代码。
  • 试试 Bitly.shorten("stackoverflow.com")
  • 这没有按预期工作——确保你有完整的 http://stackoverflow.com
  • 问题肯定是加载问题,不是Bitly代码的问题。

标签: ruby-on-rails bit.ly httparty


【解决方案1】:

DIY 的替代方案 - 您可以为 bit.ly here 找到经过充分测试的 Ruby gem。

【讨论】:

  • 是的,这个 gem 对我有用,但需要我的共享服务器目前不支持的 ruby​​gems 版本
  • 知道了——现在看看你的代码,因为它绝对是一种更简单的方法。
【解决方案2】:

问题不在于 Bitly 代码,而在于您将其放在 Rails 3 应用程序的 lib/ 目录中。要加载 lib/,您需要在 config/application.rb 中提供以下内容:

config.autoload_paths += %W(#{config.root}/lib)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2012-08-01
    • 2019-06-07
    • 1970-01-01
    相关资源
    最近更新 更多