Class: ElasticGraph::SchemaDefinition::Mixins::HasReadableToSAndInspect

Inherits:
Module
  • Object
show all
Defined in:
lib/elastic_graph/schema_definition/mixins/has_readable_to_s_and_inspect.rb

Overview

Dynamic mixin that provides readable output from ‘#to_s` and `#inspect`. The default output Ruby prints for these methods is quite unwieldy for all our schema definition types, because we have a large interconnected object graph and `Struct` classes print all their state. In fact, before implementing this, we observed output of more than 5 million characters long!

To use this module include a new instance of it:

include HasReadableToSAndInspect.new

Optionally, provide a block that, given an instance of the class, returns a string description for inclusion in the output:

include HasReadableToSAndInspect.new { |obj| obj.name }

Instance Method Summary collapse

Constructor Details

#initializeHasReadableToSAndInspect

Returns a new instance of HasReadableToSAndInspect.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/elastic_graph/schema_definition/mixins/has_readable_to_s_and_inspect.rb', line 29

def initialize
  if block_given?
    define_method :to_s do
      # @type self: HasReadableToSAndInspect
      "#<#{self.class.name} #{yield self}>"
    end
  else
    # When no block is given, we just want to use the stock `Object#to_s`, which renders the memory address.
    define_method :to_s do
      ::Object.instance_method(:to_s).bind_call(self)
    end
  end

  alias_method :inspect, :to_s
end