marcamillion marcamillion - 2 months ago 8
Ruby Question

How do I use instance variables initialized in my initialize method in other methods?

This is what my class looks like:

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

module YPCrawler
class PageCrawler
def initialize(url)
@url = 'http://www.someurl.com'
end

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

end
end


Yet when I get thrown into
pry
, I see this:

[1] pry(YPCrawler::PageCrawler)> @url
=> nil
[2] pry(YPCrawler::PageCrawler)> body
NameError: undefined local variable or method `body' for YPCrawler::PageCrawler:Class
from (pry):2:in `<class:PageCrawler>'
[3] pry(YPCrawler::PageCrawler)> document
NameError: undefined local variable or method `document' for YPCrawler::PageCrawler:Class
from (pry):3:in `<class:PageCrawler>'
[4] pry(YPCrawler::PageCrawler)> bizlistings
NameError: undefined local variable or method `bizlistings' for YPCrawler::PageCrawler:Class
from (pry):4:in `<class:PageCrawler>'
[5] pry(YPCrawler::PageCrawler)> url
NameError: undefined local variable or method `url' for YPCrawler::PageCrawler:Class
Did you mean? URI
from (pry):5:in `<class:PageCrawler>'
[6] pry(YPCrawler::PageCrawler)> @url
=> nil


Why can I not access
@url
that was initialized in my
def initialize
method?

Edit 1

Added Screenshots of what my code and the terminal PRY session really look like, since there was some disbelief about the position of my
binding.pry
.

code
terminal

Edit 2

My main
lib/yp-crawler.rb
file looks like this:

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

module YPCrawler
end


So the code that is run above is my
yp-crawler/page-crawler.rb
file, which I included in my
lib/yp-crawler.rb
file.

Edit 3

Here is a recording of my entire workflow. Please tell me what I am missing:

https://www.dropbox.com/s/jp1abthfkiplb4p/Pry-not-cooperating.webm?dl=0

Answer

I bet your code looks as follows:

module YPCrawler
  class PageCrawler
    attr_reader :url
    def initialize(url)
      @url = 'http://www.someurl.com'
    end

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

Even though you might have moved the binding.pry into method, most likely you did not reload the console, so it executes the "wrong" version.

From your screenshots it is clear that either file is not reloaded or you just made changes to wrong file.