Skip to content

Commit

Permalink
Simplify inspect of context
Browse files Browse the repository at this point in the history
  • Loading branch information
kanety committed Jul 25, 2023
1 parent 2b7ee00 commit ba6bbf3
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 24 deletions.
24 changes: 3 additions & 21 deletions lib/coactive/contexts/inspect.rb
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require_relative 'inspector'

module Coactive
module Contexts
module Inspect
Expand All @@ -11,27 +13,7 @@ def to_s

class_methods do
def inspect(data)
data.map { |k, v| "#{k}=#{Coactive::Contexts::Inspect.call(v)}" }.join(', ')
end
end

class << self
class_attribute :max_num, :max_length
self.max_num = 5
self.max_length = 300

def call(data)
if data.is_a?(Array)
str = data.take(max_num).map { |v| call(v) }.join(', ')
str += '...' if data.size > max_num
"[#{str}]"
elsif data.is_a?(Hash)
str = data.take(max_num).map { |k, v| "#{k}: #{call(v)}" }.join(', ')
str += '...' if data.size > max_num
"{#{str}}"
else
data.to_s.truncate(max_length)
end
data.map { |k, v| "#{k}=#{Coactive::Contexts::Inspector.call(v)}" }.join(', ')
end
end
end
Expand Down
48 changes: 48 additions & 0 deletions lib/coactive/contexts/inspector.rb
@@ -0,0 +1,48 @@
# frozen_string_literal: true

module Coactive
module Contexts
module Inspector
class << self
class_attribute :max_num, :max_length, :basic_classes
self.max_num = 3
self.max_length = 100
self.basic_classes = [Module, Symbol, String, Numeric, TrueClass, FalseClass, Regexp]

def call(data)
if data.is_a?(Array)
inspect_array(data)
elsif data.is_a?(Hash)
inspect_hash(data)
elsif basic_classes.any? { |klass| data.is_a?(klass) }
inspect_basic(data)
else
inspect_object(data)
end
end

private

def inspect_array(data)
str = data.take(max_num).map { |v| call(v) }.join(', ')
str += "..." if data.size > max_num
"[#{str}]"
end

def inspect_hash(data)
str = data.take(max_num).map { |k, v| "#{k}: #{call(v)}" }.join(', ')
str += "..." if data.size > max_num
"{#{str}}"
end

def inspect_basic(data)
data.inspect
end

def inspect_object(data)
"#<#{data.class}:#{data.object_id}>"
end
end
end
end
end
6 changes: 3 additions & 3 deletions spec/coactive/contexts/inspect_spec.rb
@@ -1,16 +1,16 @@
describe Coactive::Context do
it 'has to_s' do
context = described_class.new(in: 'in')
expect(context.to_s).to include('in=in')
expect(context.to_s).to include('in="in"')
end

it 'inspects short array' do
context = described_class.new(a: ["a", "b", "c", "d", "e", "f"])
expect(context.to_s).to include("[a, b, c, d, e...]")
expect(context.to_s).to include('["a", "b", "c"...]')
end

it 'inspects short hash' do
context = described_class.new(a: { a: "a", b: "b", c: "c", d: "d", e: "e", f: "f" })
expect(context.to_s).to include("a: a, b: b, c: c, d: d, e: e...")
expect(context.to_s).to include('{a: "a", b: "b", c: "c"...}')
end
end

0 comments on commit ba6bbf3

Please sign in to comment.