module Pakyow::Support::Inspectable

Customized inspectors for your objects.

@example

class FooBar
  include Pakyow::Support::Inspectable
  inspectable :@foo, :baz

  def initialize
    @foo = :foo
    @bar = :bar
  end

  def baz
    :baz
  end
end

FooBar.instance.inspect
=> #<FooBar:0x007fd3330248c0 @foo=:foo baz=:baz>

Public Class Methods

included(base) click to toggle source
# File lib/pakyow/support/inspectable.rb, line 28
def self.included(base)
  base.extend ClassMethods
  base.extend ClassState unless base.ancestors.include?(ClassState)
  base.class_state :__inspectables, inheritable: true, default: []
end

Public Instance Methods

inspect() click to toggle source

Recursion protection based on:

https://stackoverflow.com/a/5772445
# File lib/pakyow/support/inspectable.rb, line 47
def inspect
  inspection = String.new("#<#{self.class}:#{self.object_id}")

  if recursive_inspect?
    "#{inspection} ...>"
  else
    prevent_inspect_recursion do
      if self.class.__inspectables.any?
        inspection << " " + self.class.__inspectables.map { |inspectable|
          value = if inspectable.to_s.start_with?("@")
            instance_variable_get(inspectable)
          else
            send(inspectable)
          end

          "#{inspectable}=#{value.inspect}"
        }.join(", ")
      end

      inspection.strip << ">"
    end
  end
end

Private Instance Methods

inspected_objects() click to toggle source
# File lib/pakyow/support/inspectable.rb, line 73
def inspected_objects
  Thread.current[:inspected_objects] ||= {}
end
prevent_inspect_recursion() { || ... } click to toggle source
# File lib/pakyow/support/inspectable.rb, line 77
def prevent_inspect_recursion
  inspected_objects[object_id] = true; yield
ensure
  inspected_objects.delete(object_id)
end
recursive_inspect?() click to toggle source
# File lib/pakyow/support/inspectable.rb, line 83
def recursive_inspect?
  inspected_objects[object_id]
end