Skip to content
This repository has been archived by the owner on Oct 5, 2023. It is now read-only.

Commit

Permalink
Merge pull request #99 from socialcast/fix-json-encode
Browse files Browse the repository at this point in the history
Fix JSON encode
  • Loading branch information
mandrews committed Mar 18, 2015
2 parents 4333bd4 + 2e336cb commit 82c8952
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 14 deletions.
34 changes: 29 additions & 5 deletions lib/masamune/schema/map.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def gets(*a)
line = __getobj__.gets(*a)
return unless line
return line if skip?
encode(line.split(separator)).join(separator)
encode(line, separator).join(separator)
end

private
Expand All @@ -43,12 +43,36 @@ def skip?
@store.json_encoding == :quoted
end

def encode(fields = [])
fields.map { |field| field =~ /^{|}$/ ? quote(field) : field }
def encode(line, separator)
fields = []
buffer = ''
nested = false
line.strip.each_char do |char|
case char
when '{'
buffer << char
nested = true
when '}'
buffer << char
nested = false
when separator
if nested
buffer << char
else
fields << quote(buffer)
buffer = ''
end
else
buffer << char
end
end
fields << quote(buffer)
fields.compact
end

def quote(field)
%Q{"#{field.gsub(/(?<!")"(?!")/, '""')}"}
def quote(buffer)
return buffer if buffer =~ /\A".*"\z/
%Q{"#{buffer.gsub('"', '""')}"}
end

def separator
Expand Down
26 changes: 17 additions & 9 deletions spec/masamune/schema/map_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -538,28 +538,36 @@

subject { encoder.gets }

context 'with raw json' do
context 'with raw empty json' do
before do
io.write '{"enabled":true}'
io.write '{},{}'
io.rewind
end
it { is_expected.to eq(%Q{"{""enabled"":true}"}) }
it { is_expected.to eq(%Q{"{}","{}"}) }
end

context 'with quoted json' do
context 'with raw quoted json' do
before do
io.write '"{""enabled"":true}"'
io.write '"{}","{}"'
io.rewind
end
it { is_expected.to eq(%Q{"{""enabled"":true}"}) }
it { is_expected.to eq(%Q{"{}","{}"}) }
end

context 'with partially quoted json' do
context 'with raw json' do
before do
io.write '{"enabled":true,"state":""}'
io.rewind
end
it { is_expected.to eq(%Q{"{""enabled"":true,""state"":""""}"}) }
end

context 'with quoted json' do
before do
io.write '{""enabled"":true}'
io.write '"{""enabled"":true,""state"":""""}"'
io.rewind
end
it { is_expected.to eq(%Q{"{""enabled"":true}"}) }
it { is_expected.to eq(%Q{"{""enabled"":true,""state"":""""}"}) }
end
end
end

0 comments on commit 82c8952

Please sign in to comment.