Commit 98f2c788 authored by Rene Saarsoo's avatar Rene Saarsoo
Browse files

Create our own custom Singleton implementation.

Use it to abstract away the singleton logic in Logger.
parent 4d008d89
Loading
Loading
Loading
Loading
+2 −9
Original line number Diff line number Diff line
require 'singleton'
require 'jsduck/util/singleton'
require 'jsduck/util/os'

module JsDuck

  # Central logging of JsDuck
  class Logger
    include Singleton

    # Eliminate the need to add .instance. when calling Logger
    # methods.  So one can just call Logger.warn and behind the scenes
    # the Logger.instance.warn will be invoked.
    def self.method_missing(meth, *args, &block)
      Logger.instance.send(meth, *args, &block)
    end
    include Util::Singleton

    # Set to true to enable verbose logging
    attr_accessor :verbose
+36 −0
Original line number Diff line number Diff line

module JsDuck
  module Util

    # A more convenient Singleton implementation.
    #
    # With the standard ruby Singleton you need to call the methods of
    # your singleton instance as follows:
    #
    #     MyClass.instance.my_method()
    #
    # But with JsDuck::Util::Singleton you can skip the .instance. part:
    #
    #     MyClass.my_method()
    #
    # This also conveniently hides from the calling code the fact that
    # a class is implemented as Singleton - it could just as well only
    # have static methods.
    #
    module Singleton
      def self.included(base)
        base.class_eval do
          def self.instance
            @instance ||= self.new
          end

          # Redirect calls from MyClass.method to MyClass.instance.method
          def self.method_missing(meth, *args, &block)
            self.instance.send(meth, *args, &block)
          end
        end
      end
    end

  end
end