Class: Lafcadio::Context

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/lafcadio/util/Context.rb

Overview

The Context is a singleton object that manages ContextualServices. Each ContextualService is a service that connects in some way to external resources: ObjectStore connects to the database; Emailer connects to SMTP, etc.

Context makes it easy to ensure that each ContextualService is only instantiated once, which can be quite useful for services with expensive creation.

Furthermore, Context allows you to explicitly set instances for a given service, which can be quite useful in testing. For example, once LafcadioTestCase#setup has an instance of MockObjectStore, it calls

context.setObjectStore @mockObjectStore

which ensures that any future calls to ObjectStore.getObjectStore will return @mockObjectStore, instead of an instance of ObjectStore connecting test code to a live database.

Instance Method Summary collapse

Constructor Details

#initializeContext

Returns a new instance of Context.



23
24
25
# File 'lib/lafcadio/util/Context.rb', line 23

def initialize
	@resources = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(methId, *args) ⇒ Object

:nodoc:



50
51
52
53
54
55
56
57
58
59
# File 'lib/lafcadio/util/Context.rb', line 50

def method_missing(methId, *args) #:nodoc:
	methodName = methId.id2name
	if methodName =~ /^get(.*)$/
		getResource $1
	elsif methodName =~ /^set(.*)$/
		setResource $1, args[0]
	else
		super
	end
end

Instance Method Details

#createInstance(resourceName) ⇒ Object

:nodoc:



32
33
34
35
# File 'lib/lafcadio/util/Context.rb', line 32

def createInstance(resourceName) #:nodoc:
	resourceClass = eval resourceName
	resourceClass.new self
end

#flushObject

Flushes all cached ContextualServices.



28
29
30
# File 'lib/lafcadio/util/Context.rb', line 28

def flush
	@resources = {}
end

#getResource(resourceName) ⇒ Object

:nodoc:



37
38
39
40
41
42
43
44
# File 'lib/lafcadio/util/Context.rb', line 37

def getResource(resourceName) #:nodoc:
	resource = @resources[resourceName]
	unless resource
		resource = createInstance resourceName
		setResource resourceName, resource
	end
	resource
end

#setResource(resourceName, resource) ⇒ Object

:nodoc:



46
47
48
# File 'lib/lafcadio/util/Context.rb', line 46

def setResource(resourceName, resource) #:nodoc:
	@resources[resourceName] = resource
end