Class: Lafcadio::Context
- Inherits:
-
Object
- Object
- Lafcadio::Context
- 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
-
#createInstance(resourceName) ⇒ Object
:nodoc:.
-
#flush ⇒ Object
Flushes all cached ContextualServices.
-
#getResource(resourceName) ⇒ Object
:nodoc:.
-
#initialize ⇒ Context
constructor
A new instance of Context.
-
#method_missing(methId, *args) ⇒ Object
:nodoc:.
-
#setResource(resourceName, resource) ⇒ Object
:nodoc:.
Constructor Details
#initialize ⇒ Context
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 |
#flush ⇒ Object
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 |