Iñaki Baz Castillo wrote:
> Humm, I don't like adding "include Logging" to every classes I use since
> sometimes I use objects, sometimes classes, so I'd also need to "extend"
> some classes not just "include".
You could use meta programming to include Logging in all nested classes
and modules of your top-level module:
module FooBar
# ... code from previous e-mail ...
# recursively adds Logging functionality to all nested classes
extender = lambda do |k|
k.constants.map {|c| k.const_get c }.
select {|c| c.is_a? Class or c.is_a? Module }.
each do |c|
c.extend Logging
extender[c]
end
end
extender[self]
end
>> # Using a LOG object
>> module FooBar
>> LOG = Logger.new
>>
>> class FooBar::Baz
>> def oh_no
>> LOG.debug "oh no!"
>> end
>> end
>> end
>
> Ok, in this case you use a constant (LOG). This is the same I do now but
> I use a global variable ($log). Is more ellegant using a constant?
Yes, in my opinion. A constant is constrained to the walls of your
library's top-level module, whereas a global variable is not.
Therefore, unless someone was modifying your library, they would not be
able to access your constant.
--
Posted via http://www.ruby-forum.com/.