ruby - 为什么 # 会出现未定义的方法 `xpath'?

标签 ruby ruby-on-rails-3 nokogiri

我有以下 XML 结构:

<agencies>
  <city>
    <name>New York</name>
    <address>Street A, 101</address>
    <phone>111-222-333</phone>
  </city>
  <city>
    <name>Chicago</name>
    <address>Street B, 201</address>
    <phone>111-222-333</phone>
  </city>
</agencies>

我正在尝试创建一个 Ruby 类来使用它。

我创建了类文件:

require 'nokogiri'

class Agency

  def initialize(arg)
    @file = arg.gsub(/-/,'_')
    @doc = Nokogiri::XML(open("db/agencies/#{@file}.xml"))
  end

  def find_offices
    @doc.xpath('//agencies/city').map do |i|
      { 'name' => xpath('name') }
    end
    #@entries = @doc.xpath('//agencies/city').map do |i|
    #  { 'name' => xpath('name').inner_text, 'address' => xpath('address').inner_text, 'phone' => xpath('phone').inner_text }
    #end
  end
end

对于我的 Controller ,我有:

class AgenciesController < ApplicationController

  def index
    @prefectures = Prefecture.all
  end

  def list
    @prefecture = Agency.new(params[:prefecture_name])
    @offices = @prefecture.find_offices
  end
end

list 方法返回以下错误:

NoMethodError in AgenciesController#list

undefined method `xpath' for #<Agency:0x9e7f280>
Rails.root: /home/kleber/projects/rails_apps/job_board2

Application Trace | Framework Trace | Full Trace
app/models/agency.rb:13:in `block in find_offices'
app/models/agency.rb:12:in `map'
app/models/agency.rb:12:in `find_offices'
app/controllers/agencies_controller.rb:9:in `list'

最佳答案

这部分看起来很有趣:

def find_offices
    @doc.xpath('//agencies/city').map do |i|
      { 'name' => xpath('name') }
    end

您为 xpath() 查询返回的每个元素创建一个局部变量 i,但不使用它。您正在调用 xpath('name'),但我没有在可以调用的类(或全局范围内)上看到 xpath() 的定义.

你的意思是写一些更像这样的东西吗? (未经测试):

      { 'name' => i.xpath('name') }

关于ruby - 为什么 # 会出现未定义的方法 `xpath'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11110822/

相关文章:

ruby-on-rails - 在 Controller 中排序数组

Ruby 遍历数组中的每个元素 n 次

ruby-on-rails - 自定义 rake :stats

ruby - bing 和 yahoo 搜索引擎的 Mechanize

ruby - Nokogiri 通过 XML 解析失败

ruby-on-rails - 如何在 Ruby on Rails 中使用子 Controller ?

ruby-on-rails - Ruby 使用数据库属性总和更新属性

ruby-on-rails - 如何将 h4 标签添加到 refinerycms 编辑器?

ruby-on-rails - rails 3 : What is the difference between an Engine and a Gem?

ruby-on-rails - Bundler 找不到 gem "nokogiri"的兼容版本