General global registrar among modules / classes

What is the best (correct) way to share a log instance among many ruby ​​classes?

Right now I created the log as a global variable $ logger = Logger.new, but I have the feeling that there is a better way to do this without using the global var.

If I have the following:

module Foo class A class B class C ... class Z end 

What is the best way to exchange journal instances among all classes? Do I somehow declare / create a logger in the Foo module or just use the global $ logger fine?

+4
source share
2 answers

Add a constant to the module:

 module Foo Logger = Logger.new class A class B class C ... class Z end 

Then you can do Logger.log('blah') in your classes. Since we are obscuring the global Logger constant with Foo::Logger , this means that if you want to access the Logger class in the Foo module, you must use the scope permission: ::Logger .

+9
source

You can create a singleton Logger for your application, so each link will be to the same object.

 require 'singleton' class Logger include Singleton end l = Logger.instance k = Logger.instance puts k.object_id == l.object_id #returns true 
0
source

All Articles