Class: Spidr::SessionCache

Inherits:
Object
  • Object
show all
Defined in:
lib/spidr/session_cache.rb

Instance Attribute Summary

Instance Method Summary

Constructor Details

- (SessionCache) initialize(proxy = Spidr.proxy)

Creates a new session cache.

Parameters:

  • (Hash) proxy (defaults to: Spidr.proxy) — (Spidr.proxy) Proxy options.

Options Hash (proxy):

  • (String) :host N/A — The host the proxy is running on.
  • (Integer) :port N/A — The port the proxy is running on.
  • (String) :user N/A — The user to authenticate as with the proxy.
  • (String) :password N/A — The password to authenticate with.

Since:

  • 0.2.2


31
32
33
34
# File 'lib/spidr/session_cache.rb', line 31

def initialize(proxy=Spidr.proxy)
  @proxy = proxy
  @sessions = {}
end

Instance Attribute Details

- (Object) proxy

Proxy to use



9
10
11
# File 'lib/spidr/session_cache.rb', line 9

def proxy
  @proxy
end

Instance Method Details

- (Net::HTTP) [](url)

Provides an active HTTP session for a given URL.

Parameters:

  • (URI::HTTP, String) url — The URL which will be requested later.

Returns:

  • (Net::HTTP) — The active HTTP session object.


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/spidr/session_cache.rb', line 45

def [](url)
  # normalize the url
  url = URI(url.to_s) unless url.kind_of?(URI)

  key = [url.scheme, url.host, url.port]

  unless @sessions[key]
    session = Net::HTTP::Proxy(
      @proxy[:host],
      @proxy[:port],
      @proxy[:user],
      @proxy[:password]
    ).new(url.host,url.port)

    if url.scheme == 'https'
      session.use_ssl = true
      session.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end

    @sessions[key] = session
  end

  return @sessions[key]
end

- (SessionCache) clear

Clears the session cache.

Returns:

Since:

  • 0.2.2


105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/spidr/session_cache.rb', line 105

def clear
  @sessions.each_value do |sess|
    begin
      sess.finish
    rescue IOError
      nil
    end
  end

  @sessions.clear
  return self
end

- (nil) kill!(url)

Destroys an HTTP session for the given scheme, host and port.

Parameters:

  • (URI::HTTP, String) url — The URL of the requested session.

Returns:

  • (nil)

Since:

  • 0.2.2


80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/spidr/session_cache.rb', line 80

def kill!(url)
  # normalize the url
  url = URI(url.to_s) unless url.kind_of?(URI)

  key = [url.scheme, url.host, url.port]

  if (sess = @sessions[key])

    begin 
      sess.finish
    rescue IOError
    end

    @sessions.delete(key)
  end
end