ruby on rails - Set class variable from module -
i want have separate logs app. created following module:
module myapp module mylog def self.included(base) base.extend(classmethods) end module classmethods def logger @@logger ||= logger.new("#{rails.root}/log/#{self.name.underscore}.log") end end end end
then, in of models, can add:
include myapp::mylog
and use (log file appear in .../log/cat.log
):
cat.logger.info 'test'
i tried use method included
on cat
, dog
models, , have result:
cat.new.logger # => #<logger:0x007fe4516cf0b0 @progname=nil, ... @dev=#<file:/.../log/cat.log>, ... dog.new.logger # => #<logger:0x007fe4516cf0b0 @progname=nil, ... @dev=#<file:/.../log/cat.log>, ... (the same)
if try use logger dog
model first, have log file name dog
(/dog.log
).
how can set class variable @@logger
module each class correct initialized logger?
do not use class variable, use instance_variable
attached class.
module myapp module mylog def self.included(base) base.extend(classmethods) end module classmethods def logger @logger ||= logger.new("#{rails.root}/log/#{self.name.underscore}.log") end end end end
example:
module def self.included(base) base.extend classmethods end module classmethods def logger puts @logger @logger ||= name end end end class b include end class c include end b.logger # b.logger # b c.logger # b.logger # b c.logger # c
first time call method nil
, empty line, second time call method value equals class name, b
, , if called on new class again nil
, check answer
Comments
Post a Comment