Module: SDL2::Debug

Defined in:
lib/sdl2/debug.rb

Overview

This class manages logging output

Constant Summary collapse

ENABLED =
Hash.new do 
  false # Always defaults to false
end
STATE =
{
  log_to: STDERR,
  recursion: 0,
  last_caller: [],
}

Class Method Summary collapse

Class Method Details

.enable(obj) ⇒ Object

Takes an instance or a class to enable for debugging. NOTE: If you only enable a single instance, then you will not see messages from the class-level.



37
38
39
# File 'lib/sdl2/debug.rb', line 37

def self.enable(obj)
  ENABLED[obj] = true
end

.enabled?(obj) ⇒ Boolean

Returns true if the instance It will return true if the object inherits from a class enabled for debugging.

Returns:

  • (Boolean)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/sdl2/debug.rb', line 18

def self.enabled?(obj)
  # Immediately return true if we are debugging this instance specifically.
  return true if ENABLED[obj] 
  # Otherwise, check if the object is a class or get it's class.
  klass = obj.kind_of?(Class) ? obj : obj.class
  # And until there is no more superclass.
  until klass == nil
    # Return true if the class is enabled for debugging.
    return true if ENABLED[klass]
    # Otherwise keep searching.
    klass = klass.superclass
  end
  # If we got this far, it is a bust.
  false
end

.log(src, &msg_block) ⇒ Object

This will log a message from a method. The source object is required (usually self) and this is how debugging is controlled. The message must be specified in a block which will never be evaluated unless debugging is enabled for the source. The source class will be identified along with the method name calling log in the output.



46
47
48
49
50
51
52
53
54
55
# File 'lib/sdl2/debug.rb', line 46

def self.log(src, &msg_block)
  return unless klass = enabled?(src)
  method_name =  /.*`(.*)'/.match(caller.first)[1]
  is_class = src.kind_of?(Class)
  klass = is_class ? src : src.class
  msg_start = "#{klass.to_s}#{is_class ? '::' : '#'}#{method_name} >"     
  msg = msg_block.nil? ? "No message" : msg_block.call
  STATE[:log_to].puts(caller.first)
  STATE[:log_to].puts(msg_start + msg)
end