marcamillion marcamillion - 2 months ago 6
Ruby Question

How do I reference a method in a different class from a method in another class?

I have a module and class in a file

lib/crawler/page-crawler.rb
that looks like this:

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


Then I have another module & class in another file
lib/crawler/listing-crawler.rb
that looks like this:

require 'oga'
require 'pry'

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

def extract_busines_name
binding.pry
end

end
end


However, when I try to run this script
ruby lib/yp-crawler.rb
which executes the
page-crawler.rb
file above and works without the
YPCrawler
call, I get this error:

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


The issue is on this line:

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


So how do I call that other from within my iterator in my
page-crawler.rb
?

Edit 1

When I just do `ListingCrawler.new listing['id'], I get the following error:

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


Edit 2

Here is the directory structure of my project:

directory-structure

Edit 3

My
yp-crawler.rb
looks like this:

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

module YPCrawler
end

Answer

In your yp-crawler.rb file, based on the structure that you posted, you should have something like:

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