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

ruby class instance variable vs. class variable


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -