Question

I'm trying to edit my Ruby file with Pry. There are few variables that are set in it, and for whatever reason I can't seem to cd into them because they aren't being defined even after I 'load' the file.

Here is the code:

require 'nokogiri'
require 'open-uri'

doc = Nokogiri.XML('<foo><bar /><foo>', nil, 'UTF-8') 

url = "http://superbook.eventmarketer.com/category/agencies/" 

puts "Finished!"

In Pry I do:

load "./AgencyListingScraper.rb"

and then this is the output:

7] pry(main)> load './AgencyListingScraper.rb'
Finished!
=> true
[8] pry(main)> 

Then when I try to do something like:

[8] pry(main)> url
NameError: undefined local variable or method `url' for main:Object
from (pry):6:in `__pry__'
[9] pry(main)> cd url
Error: Bad object path: url. Failed trying to resolve: url. #<NameError: undefined local     
variable or method `url' for main:Object>
[10] pry(main)> 

This is what I get.

I think I'm not loading the file correctly although I've been searching for hours and I can't figure out how to properly do this. I was doing it right months ago when I had made a scraper with Ruby, but this time I'm having trouble just getting started because of this bit.

Thanks for your help in advance!

Was it helpful?

Solution

Try it this way:

In your file include Pry and do a binding.pry:

require 'nokogiri'
require 'open-uri'
require 'pry'

doc = Nokogiri.XML('<foo><bar /><foo>', nil, 'UTF-8') 

url = "http://superbook.eventmarketer.com/category/agencies/" 

binding.pry
puts "Finished!"

Then run the file by executing:

ruby AgencyListingScraper.rb 

That should drop you into a Pry session where you can use commands like ls to see all of the variables.

Both the way you used Pry, and this way, work. However, the reason that load may not be working in your case is that local variables don't get carried over across files, like when you require one file from another.

Try loading this file:

#test.rb
y = "i dont get carried over cause i am a local variable"
b= "i dont get carried over cause i am a local variable"
AAA= "i am a constant so i carry over"
@per = "i am an instance var so i get carried over as well"

When you load it in Pry using load "test.rb" you can see that you can't get access to the local variables from that file.

OTHER TIPS

I found this question googling but the proposed solution did not work for me because the file I wanted to load was not a class nor a script but a complex ruby config file, so I was not able to inject pry in the code.

But I also found an answer in Reddit linked to this gist that was exactly what I was looking for.

Doing a

Pry.toplevel_binding.eval File.read("stuff.rb")

Will effectively execute the ruby code of the file stuff.rb in the current pry session, leaving the resulting objects for inspecting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top