3

I am using Mechanize to crawl a site that requires login. The following code logs me in.

require 'mechanize'

agent = Mechanize.new
agent.get 'http://www.specialsite.com'

agent.page.form.txtEmail = 'myemail@email.com'
agent.page.form.txtPassword = 'myPassword'
agent.page.form.add_field! "__EVENTTARGET","btnLogin"
agent.page.form.add_field! "__EVENTARGUMENT",""
agent.page.form.submit


agent.page.link_with(:text => "Special Link").click

agent.page.form.txtSearch = "Search Text"
agent.page.form.add_field! "__EVENTTARGET","lbtnSearch"
agent.page.form.add_field! "__EVENTARGUMENT","" 
agent.page.form.submit

My question is, how do I run this code in the ruby IRB so that I can have access to the objects it defines like 'agent' to experiment with and generate the rest of the code I need?

I have tried 'load'. It runs the commands but it doesn't make the objects like 'agent' available.

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
user1077851
  • 111
  • 1
  • 5

4 Answers4

3

write this stuff in a textfile as it is, open IRB and type:

File.open("your_file","r").readlines.each{|line| eval(line)}

Does this help?

EDIT: the Textfile must exist in the same directory where you fire up IRB. General advantage: it is way easier to modify something in a textfile than to fiddle in a huge IRB one-liner.

Maximilian Stroh
  • 1,086
  • 1
  • 10
  • 26
2

Use pry:

require 'pry'
... your code
binding.pry

When you run the script it will stop at binding.pry and you have an irb-like repl (but better) where you can evaluate objects. Use exit to continue or exit-program to quit.

pguardiario
  • 53,827
  • 19
  • 119
  • 159
0

Since that is all repeatable code and you should try and implement DRY(Don't Repeat Yourself) when ever you can. I would through all this in a class and have a method that returns agent. Then in irb you would require the class and set your irb variable to class getmethod. And this way you already have the start of class that you will use for your project lator

Egryan
  • 717
  • 4
  • 15
0

I agree with @pguardiaro to use Pry

But here is how you do it in IRB:

binding.eval(File.read("your_file.rb"), "your_file.rb"

horseyguy
  • 29,455
  • 20
  • 103
  • 145