Why am I getting a nil object instead of a shortlink from bitly?
I'm using a simple enough bitly implementation based on this example: http://www.appelsiini.net/2010/using-bitly-with-httparty
I put this file in the lib folder (bitly.rb)
require 'rubygems'
require 'httparty'
class Bitly
include HTTParty
base_uri "api.bit.ly"
@@login = "goldhat"
@@api开发者_Go百科_key = "R_xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
def self.shorten(url)
response = get("/v3/shorten?login=#{@@login}&apiKey=#{@@api_key}&longUrl=#{url}")
response["data"]["url"]
end
end
For some reason I'm getting a nil object. As though bitly doesn't even respond with any data. I tested it out in my console and my app and get the same error:
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
Any ideas?
Alternative to the DIY - you can find a well-tested Ruby gem for bit.ly here.
The problem isn't the Bitly code, it's that you're putting it in the lib/ directory in a Rails 3 application. To get lib/ loaded, you need the following in config/application.rb
:
config.autoload_paths += %W(#{config.root}/lib)
精彩评论