El Martes, 24 de Junio de 2008, Andrea Fazzi escribi:
> Iaki Baz Castillo ha scritto:
> > Hi, I use Logger class in a programm and since I need to log in lot of
> > different places (into classes, into methods...) I use a global variable
> > in this way:
> >
> >   $log = Logger.new
> >   $log.debug ...
> >
> > so I can use $log anywhere in the code. Is it ellegant and "the Ruby
> > way"?
> >
> > The other possibility I see is creating a class that stores the logger
> > instance into a @@class_variable (@@logger) and call class method
> > anywhere in the code:
> >
> >
> >   class MyLogger
> >
> >     @@logger = Logger.new
> >
> >     def self.debug(x)
> >       @@logger.debug(x)
> >     end
> >
> >     ...
> >   end
> >
> >   MyLogger.debug ...
> >
> > Which is a more ellegant way? is there other option?
> >
> > Thanks for any advice I could receive from you.
>
> Maybe and IMHO you can use a simple dependency injection pattern. You
> pass a Logger instance to the constructor of your classes. In this way
> you keep the logger object decoupled from other objects in the system.
> Moreover, testing will be easier (you can mock the logger implementation).
>
> require 'logger'
>
> class Container
>   def logger
>     @logger ||= Logger.new STDOUT
>   end
>   def foo
>     Foo.new(logger)
>   end
> end
>
> class Foo
>   def initialize(logger)
>     @logger = logger
>   end
>   def bar
>     @logger.info('Foo#bar invoked.')
>   end
> end
>
> c = Container.new
> c.foo.bar

That's a cool solution :)



-- 
Iaki Baz Castillo