Sha256: 25501e04d56f5d8150653b36ec940ee2b8319d46c5b1a7e62f2380bf0228c9eb

Contents?: true

Size: 1.13 KB

Versions: 5

Compression:

Stored size: 1.13 KB

Contents

module Arx

  # Restricts +inspect+ to dump a whitelist of methods on an object.
  # It will always provide `object_id` at a minimum.
  # @private
  module Inspector

    # Overwrites the object's own inspect method.
    def inspect
      pairs = {}

      self.class.inspector_fields.each do |field|
        pairs[field] = self.send(field).inspect
      rescue
      end

      "#<#{self.class.name}:#{self.object_id} #{pairs.map {|k,v| "#{k}=#{v}"}.join(", ")}>"
    end

    class << self
      # Returns the +inspected+ instance variable, or sets it if undefined.
      def inspected
        @inspected ||= []
      end

      # Defines helper +inspector_fields+ instance variable & method, and +inspector+ instance method on the target object.
      # @param [Object] source An arbitrary object (the object that +includes+ the +Inspector+ module).
      def included(source)
        inspected << source
        source.class_eval do
          def self.inspector(*fields)
            @inspector_fields = *fields
          end

          def self.inspector_fields
            @inspector_fields ||= []
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
arx-1.1.0 lib/arx/inspector.rb
arx-1.0.1 lib/arx/inspector.rb
arx-1.0.0 lib/arx/inspector.rb
arx-0.3.2 lib/arx/inspector.rb
arx-0.3.1 lib/arx/inspector.rb