Class: Poro::ContextFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/poro/context_factory.rb

Overview

This class serves as both the base class for all context factories, and the root class for retriving the application’s context factory.

Defined Under Namespace

Classes: FactoryError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&context_factory_block) ⇒ ContextFactory

Takes a factory block that delivers a configured context for the class passed to it.



33
34
35
36
# File 'lib/poro/context_factory.rb', line 33

def initialize(&context_factory_block)
  @context_factory_block = context_factory_block
  @context_cache = {}
end

Class Method Details

.has_instance?Boolean

Returns true if a context factory instance is configured.

Returns:

  • (Boolean)


27
28
29
# File 'lib/poro/context_factory.rb', line 27

def self.has_instance?
  return (@instance != nil)
end

.instanceObject

Returns the context factory instance for the application. Returns nil if none is set.

One normally gets this via Context.factory, but it doesn’t make a difference.

Raises:

  • (RuntimeError)


13
14
15
16
# File 'lib/poro/context_factory.rb', line 13

def self.instance
  raise RuntimeError, "No context factory configured for this application." if @instance.nil?
  return @instance
end

.instance=(instance) ⇒ Object

Sets the context factory instance for the application.

One normally sets this via Context.factory, but it doesn’t make a difference.

Raises:

  • (TypeError)


21
22
23
24
# File 'lib/poro/context_factory.rb', line 21

def self.instance=(instance)
  raise TypeError, "Cannot set an object of class #{instance.class} as the application's context factory." unless instance.kind_of?(self) || instance.nil?
  @instance = instance
end

Instance Method Details

#context_managed_class?(klass) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/poro/context_factory.rb', line 38

def context_managed_class?(klass)
  return klass && klass.include?(Poro::Persistify)
end

#fetch(klass) ⇒ Object

Fetches the context for a given class, or returns nil if the given object should not have a context.

This is the most basic implementation possible, though, like any context factory must do, it guarantees that the same Context instance will be returned for the same class throughout the lifetime of the application so that configuration subsequent to generation is honored.

Subclasses are expected to call this method instead of running the factory block directly.

Raises:



52
53
54
55
56
57
58
# File 'lib/poro/context_factory.rb', line 52

def fetch(klass)
  raise FactoryError, "Cannot create a context for class #{klass.inspect}, as it has not been flagged for persistence.  Include Context::Persistify to fix." unless self.context_managed_class?(klass)
  if( !@context_cache.has_key?(klass) )
    @context_cache[klass] = build(klass)
  end
  return @context_cache[klass]
end