Set class variable from module

I want to have separate logs for my application. I created the 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 any of my models I can add:

include MyApp::MyLog

and use it as (the log file will appear in .../log/cat.log):

Cat.logger.info 'test'

I tried using this method includedon Catand models Dog, and I have this 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 I first try to use my log for the model Dog, I will have a log file named Dog( /dog.log).

How can I set a class variable @@loggerfrom a module for each class with the correct initialized registrar?

+4
source share
1 answer

, instance_variable, .

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

:

module A
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods

    def logger
      puts @logger
      @logger ||= name
    end
  end
end

class B
  include A
end

class C
  include A
end

B.logger
#
B.logger
# B
C.logger
#
B.logger
# B
C.logger
# C

, nil, , , , , , B, , nil,

Ruby vs. class class

+3

Source: https://habr.com/ru/post/1627801/


All Articles