ruby - 如何引用不同类中的方法和另一个类中的方法?

标签 ruby inheritance

我的文件 lib/crawler/page-crawler.rb 中有一个模块和类,如下所示:

require 'oga'
require 'net/http'
require 'pry'

module YPCrawler
  class PageCrawler

    attr_accessor :url

    def initialize(url)
      @url = url
    end

    def get_page_listings
      body = Net::HTTP.get(URI.parse(@url))
      document = Oga.parse_html(body)
      document.css('div.result')
    end

    newpage = PageCrawler.new "http://www.someurl"
    @listings = newpage.get_page_listings
    @listings.each do |listing|
      bizname = YPCrawler::ListingCrawler.new listing['id']
    end
  end
end

然后我在另一个文件 lib/crawler/listing-crawler.rb 中有另一个模块和类,如下所示:

require 'oga'
require 'pry'

module YPCrawler
  class ListingCrawler
    def initialize(id)
      @id = id
    end

    def extract_busines_name
      binding.pry
    end

  end
end

但是,当我尝试运行此脚本 ruby lib/yp-crawler.rb 时,它会执行上面的 page-crawler.rb 文件,并且无需 YPCrawler 调用,我收到此错误:

/lib/crawler/page-crawler.rb:23:in `block in <class:PageCrawler>': uninitialized constant YPCrawler::ListingCrawler (NameError)

问题就在这一行:

bizname = YPCrawler::ListingCrawler.new listing['id']

那么我如何从我的 page-crawler.rb 的迭代器中调用另一个?

编辑 1

当我刚刚执行 `ListingCrawler.new Listing['id'] 时,出现以下错误:

 uninitialized constant YPCrawler::PageCrawler::ListingCrawler (NameError)

编辑2

这是我的项目的目录结构:

directory-structure

编辑3

我的yp-crawler.rb看起来像这样:

require_relative "yp-crawler/version"
require_relative "crawler/page-crawler"
require_relative "crawler/listing-crawler"

module YPCrawler
end

最佳答案

在您的 yp-crawler.rb 文件中,根据您发布的结构,您应该具有如下内容:

require 'yp-crawler/version'
require 'crawler/listing-crawler'
require 'crawler/page-crawler'

关于ruby - 如何引用不同类中的方法和另一个类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39764748/

相关文章:

ruby-on-rails - 是否有用于使用 JSON-API 格式的 RESTful json api 的 gem? Rails 上的 Ruby

java - 使用关键字 'this'

C++多重继承方法重载

android - 在 Android 中使用子类

c++ - V8 继承的 FunctionTemplate 没有得到对父 FunctionTemplate 的更新

c++ - 在具有虚拟析构函数的基类的子类中不指定析构函数是否安全?

ruby-on-rails - 关于路由的基本 Ruby on Rails 问题

ruby - 如何在 Volt 中创建 jQuery 切换类?

ruby-on-rails - 为什么我的 Rails 数据库迁移没有创建列?

mysql - 使用 Ruby on Rails 进行安全/更好的 SQL 查询