-
-
Save JakeAustwick/1362217 to your computer and use it in GitHub Desktop.
proxymanager.rb by jake232 - refactoring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ProxyManager | |
class Proxy | |
attr_reader :address | |
attr_accessor :last_used | |
def initialize(address, last_used=nil) | |
@address = address | |
@last_used = last_used | |
end | |
def used_since?(time) | |
@last_used && @last_used > time | |
end | |
end | |
def self.from_proxy_file(path="proxies.txt", delay=10) | |
proxies = IO.readlines(path).map { |line| line.strip } | |
new(proxies, delay) | |
end | |
def initialize(proxies, delay=10) | |
raise ArgumentError, "proxies must contain at least 1 proxy" if proxies.empty? | |
@proxies = proxies | |
@delay = delay | |
@records = proxies.map { |address| Proxy.new(address) } | |
end | |
# @return [Proxy] | |
# A proxy that hasn't been used for at least #delay seconds. | |
# If none is available, the method will block until one becomes available | |
def get | |
# find all electable proxies | |
choices = @records.select { |proxy| proxy.used_since?(last_time) } | |
# if no proxy was electable, find the one that's ready the soonest, then wait until | |
# it is ready | |
if choices.empty? | |
proxy = @records.min_by { |proxy| proxy.last_used } | |
nap_time = @delay - (Time.now - proxy.last_used) | |
sleep(nap_time) if nap_time > 0 | |
# use randomly one of the ready proxies | |
else | |
proxy = choices.sample | |
end | |
proxy.last_used = Time.now | |
proxy | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment