Classes as Singletons : Singletons « Design Patterns « Ruby






Classes as Singletons


class ClassBasedLogger
  ERROR = 1
  WARNING = 2
  INFO = 3

  @@log = File.open('log.txt', 'w')
  @@level = WARNING

  def self.error(msg)
    @@log.puts(msg)
    @@log.flush
  end

  def self.warning(msg)
    @@log.puts(msg) if @@level >= WARNING
    @@log.flush
  end

  def self.info(msg)
    @@log.puts(msg) if @@level >= INFO
    @@log.flush
  end

  def self.level=(new_level)
    @@level = new_level
  end

  def self.level
    @@level
  end
end

ClassBasedLogger.level = ClassBasedLogger::INFO

ClassBasedLogger.info('A')
ClassBasedLogger.warning('B')
ClassBasedLogger.error('C')

 








Related examples in the same category

1.define class methods by using a class within a class's singleton class like the code
2.Define a singleton method, one that is tied to a single object
3.Singleton a class
4.Modules as Singletons
5.include Singleton