module RubySelectiveInspect

Public Class Methods

included(base_class) click to toggle source

Add to classes that include this module some convenient class mathods to blacklist or whitelist methods by default.

# File lib/ruby_selective_inspect.rb, line 74
def self.included(base_class)
  base_class.class_eval do
    alias_method :default_inspect, :inspect
  end
  base_class.extend ClassMethods
  base_class.include InstanceMethods
end
perform_inspect(target, *whitelist) click to toggle source

Public: Inspects the given object in a customizable way.

target - The Object to be inspected. whitelist - The names of the instance variables to output.

Examples

RubySelectiveInspect.inspect(player, :id, :name)
# =>

Returns the String that describes the objects and its internals.

# File lib/ruby_selective_inspect.rb, line 53
def self.perform_inspect(target, *whitelist)
  klass = target.class
  return target.inspect if !klass.include?(self) && whitelist.size == 0

  whitelist = klass.get_inspectionable_vars if whitelist.size == 0
  if whitelist.size == 0
    whitelist = target.instance_variables.map{ |s| s[1..-1] } - klass.get_uninspectionable_vars
  end

  fields = whitelist.map do |var_name|
    name = '@' + var_name.to_s
    var_content = target.instance_variable_get(name)
    "#{name}=#{var_content.inspect}"
  end

  string = "#<#{klass.name}:#{target.object_id} "
  string + fields.join(", ") + ">"
end