Module: Pakyow::Support::Inspectable

Defined in:
lib/pakyow/support/inspectable.rb

Overview

Customized inspectors for your objects.

Examples:

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>

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



28
29
30
31
32
# 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

Instance Method Details

#inspectObject

Recursion protection based on:

https://stackoverflow.com/a/5772445


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# 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