2012-02-20 115 views
0

我試圖構建一個與Yahoo Placemaker API進行交互的gem,但我遇到了一個問題。當我嘗試運行下面的代碼我得到:Ruby命名空間問題

NameError: uninitialized constant Yahoo::Placemaker::Net 
    from /Users/Kyle/.rvm/gems/ruby-1.9.2-p290/gems/yahoo-placemaker-0.0.1/lib/yahoo-placemaker.rb:17:in `extract' 
    from (irb):4 
    from /Users/Kyle/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `<main>' 

雅虎placemaker.rb

require "yahoo-placemaker/version" 
require 'json' 
require 'ostruct' 
require 'net/http' 

module Yahoo 
    module Placemaker 
    def self.extract (text = '') 
     host = 'wherein.yahooapis.com' 
     payload = { 
     'documentContent' => text, 
     'appid' => APP_ID, 
     'outputType' => 'json', 
     'documentType' => 'text/plain' 
     } 

     req = Net::HTTP::Post.new('/v1/document') 
     req.body = to_url_params(payload) 
     response = Net::HTTP.new(host).start do |http| 
     http.request(req) 
     end 
     json = JSON.parse(response.body) 
     Yahoo::Placemaker::Result.new(json) 
    end 
    end 
end 

回答

2

我還沒有搞清楚正是常量名稱解析Ruby中是如何工作的(我認爲規則是有點亂在這裏),但是從我的經驗,它很可能是Net正在擡頭在當前命名空間而不是全局命名空間中。嘗試使用完全合格的名稱:可能發生在這條線

::Net::HTTP::Post.new 

類似的問題:

Yahoo::Placemaker::Result 

你應該要麼::Yahoo::Placemaker::Result或更好Result取代它(因爲它生活在當前的命名空間)。

0

嘗試需要網/ HTTP之前。如果沒有定義,Ruby會回落到模塊中。

require 'net/http'

+0

忘了將這一點粘貼到我的文章。我更新了我的代碼示例。 – 2012-02-20 21:28:39

+0

你究竟在irb中運行得到這個錯誤? – iltempo 2012-02-20 21:49:13