samuelkadolph / ruby-proxifier

MIT License
47 stars 28 forks source link

Proxy pool #6

Open troelskn opened 9 years ago

troelskn commented 9 years ago

Hi,

I needed a pool of proxies to cycle through and didn't see any direct support in this library. I've made a patch to supply this and thought others might benefit from it as well. If you'd like to include it in the library, I'll be happy to prepare a PR.

# An array of proxies to cycle through
class ProxyPool < Array

  def self.instance
    @instance ||= new
  end

  def initialize
    @lock = Mutex.new
    @pos = 0
  end

  def checkout
    if any?
      @lock.synchronize do
        next_item = self[@pos % length]
        @pos += 1
        next_item
      end
    end
  end

  module Hook
    def self.included(klass)
      klass.class_eval do
        def self.environment_proxy
          ProxyPool.instance.checkout || super
        end
      end
    end
  end

end # class ProxyPool

class TCPSocket
  include ProxyPool::Hook
end

Usage:

ProxyPool.instance << 'http://user:pass@proxy1.example.com'
ProxyPool.instance << 'http://user:pass@proxy2.example.com'
ProxyPool.instance << 'http://user:pass@proxy3.example.com'
holoiii commented 9 years ago

Very cool, I was looking for something just like this.

dare05 commented 9 years ago

How do you supply the array of proxies to cycle through?