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

Fix JSON encode #99

Merged
merged 2 commits into from
Mar 18, 2015
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.chomp.each_char do |char|
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use strip or rstrip unless you really mean to get rid of the last character rather than just whitespace.

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