Skip to content

Commit

Permalink
Handle circular dependencies. We don't need to log deeper than 3 levels.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonas Pfenniger committed Jun 26, 2013
1 parent 7aa20c0 commit bc39467
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 10 deletions.
3 changes: 2 additions & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
lines (0.1.16)
lines (0.1.18)

GEM
remote: http://rubygems.org/
Expand All @@ -26,6 +26,7 @@ PLATFORMS
ruby

DEPENDENCIES
bundler (~> 1.3)
lines!
parslet
rdoc
Expand Down
29 changes: 20 additions & 9 deletions lib/lines.rb
Original file line number Diff line number Diff line change
Expand Up @@ -237,16 +237,24 @@ def map(klass, &rule)
@mapping[klass] = rule
end

attr_accessor :max_depth

protected

attr_reader :mapping

def initialize
@mapping = {}
@max_depth = 3
end

def objenc_internal(x)
x.map{|k,v| "#{keyenc(k)}=#{valenc(v)}" }.join(' ')
def objenc_internal(x, depth=0)
depth += 1
if depth > max_depth
'...'
else
x.map{|k,v| "#{keyenc(k)}=#{valenc(v, depth)}" }.join(' ')
end
end

def keyenc(k)
Expand All @@ -257,10 +265,10 @@ def keyenc(k)
end
end

def valenc(x)
def valenc(x, depth)
case x
when Hash then objenc(x)
when Array then arrenc(x)
when Hash then objenc(x, depth)
when Array then arrenc(x, depth)
when String, Symbol then strenc(x)
when Numeric then numenc(x)
when Time, Date then timeenc(x)
Expand All @@ -272,16 +280,19 @@ def valenc(x)
end
end

def objenc(x)
'{' + objenc_internal(x) + '}'
def objenc(x, depth)
'{' + objenc_internal(x, depth) + '}'
end

def arrenc(a)
def arrenc(a, depth)
depth += 1
# num + unit. Eg: 3ms
if a.size == 2 && a.first.kind_of?(Numeric) && is_literal?(a.last.to_s)
numenc(a.first) + strenc(a.last)
elsif depth > max_depth
'[...]'
else
'[' + a.map{|x| valenc(x)}.join(' ') + ']'
'[' + a.map{|x| valenc(x, depth)}.join(' ') + ']'
end
end

Expand Down
6 changes: 6 additions & 0 deletions spec/lines_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,12 @@ def expect_dump(obj)
expect_dump(foo: [3, :ms]).to eq('foo=3ms')
expect_dump(foo: [54.2, 's']).to eq('foo=54.2s')
end

it "knows how to handle circular dependencies" do
x = {}
x[:x] = x
expect_dump(x).to eq('x={x={x={...}}}')
end
end

describe Lines::UniqueIDs do
Expand Down

0 comments on commit bc39467

Please sign in to comment.