Module: Foobara::TruncatedInspect

Constant Summary collapse

MAX_LENGTH =
200

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.truncatedObject

Returns the value of attribute truncated.



4
5
6
# File 'foobara-util-0.0.11/lib/foobara/truncated_inspect.rb', line 4

def truncated
  @truncated
end

Class Method Details

.truncating(object) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'foobara-util-0.0.11/lib/foobara/truncated_inspect.rb', line 6

def truncating(object)
  if truncated
    if truncated.include?(object)
      "..."
    else
      truncated << object
      yield
    end
  else
    begin
      self.truncated = Set[object]
      yield
    ensure
      self.truncated = nil
    end
  end
end

Instance Method Details

#inspectObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'foobara-util-0.0.11/lib/foobara/truncated_inspect.rb', line 27

def inspect
  TruncatedInspect.truncating(self) do
    instance_vars = instance_variables.map do |var|
      truncate = false

      value = instance_variable_get(var)

      is_array = value.is_a?(::Array)
      is_hash = value.is_a?(::Hash)

      if is_array
        truncate = value.size > 10 || value.any? { |v| v.is_a?(::Array) || v.is_a?(::Hash) }
      elsif is_hash
        truncate = value.size > 10 || value.keys.any? { |k| !k.is_a?(::Symbol) && !k.is_a?(::String) }
        truncate ||= value.values.any? { |v| v.is_a?(::Array) || v.is_a?(::Hash) }
      end

      value = if truncate
                is_array ? "[...]" : "{...}"
              else
                value.inspect
              end

      "#{var}=#{value}"
    end

    instance_vars = instance_vars.join(", ")

    result = "#<#{self.class.name}:0x#{object_id.to_s(16)} #{instance_vars}>"

    if result.size > MAX_LENGTH
      result = "#{result[0..(MAX_LENGTH - 5)]}...>"
    end

    result
  end
end