0

I'm using Mechanize with my app, and within the show action of my controller, I need to include a background job method (fillform).

Essentially, the app signs into an external website using the inputted username and password (from one user object), and then fills out many forms using that user's other inputted information (all of the order objects).

Then I destroy that user's information (for good measure, I actually just destroy all user info, as none is ever needed to be stored in the database once the background job request is sent.)

I need this the part where it fills out forms to be its own method as it needs to run as background job, and for my purposes it makes little sense to send user information as part of this background job.

The problem is that once I moved the objects' form-filling to a model method (fillform) call (that is, no longer part of the show action), the Mechanize agent failed to follow into the method, and the process failed. That is, it no longer recognizes that it is signed into this website and therefore the process fails, as the only way it can access the various internal URLs is by already being signed in. The same thing happens even if the method is not a background job, but just a regular model method.

So, how can I get the same Mechanize agent to follow into the fillform method? Please let me know if you need more information. (And I admittedly am a newbie at this, so there are some gaps in my understanding of working with MVC.)

In the Order controller:

def show
  @orders = Order.all
  @user = User.last(params[:user])
  agent = Mechanize.new
  agent.follow_meta_refresh = true

  page = agent.get('www.myurl.com')

  myform = page.form_with(:action => '/maint')

  myuserid_field = myform.field_with(:id => "username")
  myuserid_field.value = @user.myuserid
  mypass_field = myform.field_with(:id => "password")
  mypass_field.value = @user.mypass

  page = agent.submit(myform, myform.buttons.first)

  @orders.each do |order|
    order.delay.fillforms
  end

  User.destroy_all

end

In the Order model:

def fillforms
  internal_url = 'www.myurl.com/'+ keyword.gsub(/.*;/, '') + ''
  page = agent.get("#{internal_url}")
  entry_form = page.form_with(:name => "submit")
  some code here...
  page = agent.submit(entry_form, entry_form.buttons.first)
end
CodeBiker
  • 2,985
  • 2
  • 33
  • 36

1 Answers1

0

Finally figured this out, helped in part by Adam's answer here.

In my controller's show action, I changed the block to:

@order.each do |order|
  order.fillforms(order.id, agent)
end

And in the Order model, I changed the first two lines of the fillforms method to:

def fillforms(order_id, agent)
  order = Order.find(order_id)

Now Mechanize follows into the block, and the block consequently executes properly.

Community
  • 1
  • 1
CodeBiker
  • 2,985
  • 2
  • 33
  • 36