3

Using Mechanize, I need to find some way to limit requests to 1 per second(or 1 every 5 seconds, or 2 every minute, etc the point is find some way to rate limit requests).

Searching, this seems to be the way to begin to approach the issue: pre/post connect hooks. Only I don't exactly know what to do with them or how to approach, I'm guessing from my level and research I need to do a lambda or proc that says 'hey wait a second', seems basic enough.

My question is basically for an example or another clue on how to do this. I tried several lambdas(and I'm at a low level of understanding in what exactly this would do):

@agent.pre_connect_hooks << lambda { |pc| sleep 1 }

but this just turns my requests to errors:

ArgumentError: wrong number of arguments (2 for 0)

Even beginning to go through the mechanize code yields little for me so far.

Any input and learning guidance appreciated.

kkurian
  • 3,844
  • 3
  • 30
  • 49
blueblank
  • 4,724
  • 9
  • 48
  • 73

3 Answers3

4

Your lambda needs 2 arguments:

agent.pre_connect_hooks << lambda do |agent, request|
  sleep 1
end
Venkat D.
  • 2,979
  • 35
  • 42
1

You may also pass a Method:

def my_pre_hook(agent, request)
  # Do fun stuff.
end

agent.pre_connect_hooks << method(:my_pre_hook)
Richard Michael
  • 1,540
  • 16
  • 19
1

Use a Proc instead :

@agent.pre_connect_hooks << Proc.new { sleep 1 }

Kassym Dorsel
  • 4,773
  • 1
  • 25
  • 52