Class: TimingOutResource

Inherits:
Blank
  • Object
show all
Defined in:
lib/timingoutresource.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource, timeout, error = nil, &on_timeout) ⇒ TimingOutResource

Create a proxy object to a resource with a timeout so that the object can be freed/garbage collected after a specific time. After the timeout, all calls will raise a Timeout::Error (or the error you specified). Any method call before the timeout will reset the timer.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/timingoutresource.rb', line 27

def initialize(resource, timeout, error=nil, &on_timeout)
	@resource   = resource
	@timeout    = timeout
	@on_timeout = on_timeout
	@due        = Time.now+timeout
	@error      = error

	@sleeper    = Thread.new {
		until (now=Time.now) >= @due
			sleep(@due-now)
		end
		@on_timeout.call(@resource)
		@resource   = nil # enable garbage collection
		@on_timeout = nil # enable garbage collection
	}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/timingoutresource.rb', line 44

def method_missing(*args, &block)
	if @resource then
		@due = Time.now+@timeout
		@resource.__send__(*args, &block)
	elsif @error then
		Kernel.raise(@error)
	else
		Kernel.raise(Timeout::Error, "Resource no longer available")
	end
end

Class Method Details

.postpone(resource, by = nil) ⇒ Object

Postpone the timeout of a resource



17
18
19
20
# File 'lib/timingoutresource.rb', line 17

def self.postpone(resource, by=nil)
	by ||= @get.bind(resource).call(:@timeout)
	@set.bind(resource).call(:@due, Time.now+by)
end

.timeout(resource) ⇒ Object

Timeout a resource immediatly



11
12
13
14
# File 'lib/timingoutresource.rb', line 11

def self.timeout(resource)
	@set.bind(resource).call(:@due, Time.now-1)
	@get.bind(resource).call(:@sleeper).wakeup
end