4. RequireLibrary
4.1. Overview
RequireLibrary is not a service—it is a mini-framework for registering service libraries with Needle so that they can be imported into other projects with a minimum of headache.
Currently, Needle supports Container#require
as the library import mechanism. This requires you to specify both the file containing the service registration method, as well as the Module that contains the method.
RequireLibrary takes some of the duplication out of the process by allowing application developers to register a callback hook with Needle, which will be invoked when the new Container#require_library
method is invoked.
4.2. Usage
For developers of service libraries, RequireLibrary provides a hook for registering their libraries with Needle:
module Foo module Bar def register_services( container ) ... end module_function :register_services if defined?(Needle.register_library) Needle.register_library( 'foo/bar', self ) end end end
The #register_services
method is Needle’s standard callback for registering a library’s services with the given container.
The next lines, though, check to see if Needle.register_library
is defined. This allows the library to be used even when Needle-Extras is not loaded, or even installed. If the method exists, it is invoked with the require
path of the file, and the module reference that contains the #register_services
method.
Then, consumers of the library can load it using RequireLibrary as follows:
require 'needle' reg = Needle::Registry.new reg.require_library 'foo/bar' ...
The call to Container#require_library
invokes Kernel#require
, and then looks to see if there is a hook registered for the 'foo/bar'
path. If there is, the hook is invoked, which (by default) invokes the #register_services
method, passing the current container as the parameter.