【问题标题】:Ruby namespacing issuesRuby 命名空间问题
【发布时间】:2012-03-11 05:38:34
【问题描述】:

我正在尝试构建一个与 Yahoo Placemaker API 交互的 gem,但我遇到了一个问题。当我尝试运行以下代码时,我得到:

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>'

yahoo-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

【问题讨论】:

    标签: ruby syntax namespaces


    【解决方案1】:

    我还没有弄清楚 究竟 常量名称解析在 Ruby 中是如何工作的(我认为这里的规则有点混乱),但根据我的经验,很可能是 Net在当前命名空间而不是全局命名空间中。尝试使用完全限定名称:

    ::Net::HTTP::Post.new
    

    这一行可能会出现类似的问题:

    Yahoo::Placemaker::Result
    

    您应该将其替换为 ::Yahoo::Placemaker::Result 或更好的 Result(因为它位于当前命名空间中)。

    【讨论】:

      【解决方案2】:

      尝试要求 net/http 之前。如果没有定义,Ruby 会回退到模块中找到它。

      require 'net/http'

      【讨论】:

      • 忘记粘贴到我的帖子中。我已经更新了我的代码示例。
      猜你喜欢
      • 2011-05-05
      • 1970-01-01
      • 2011-02-05
      • 2015-07-07
      • 2013-03-26
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多