Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
73 changes: 73 additions & 0 deletions spec/blocks_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# frozen_string_literal: true

require 'minitest/autorun'
require 'open3'

# rubocop:disable Metrics/BlockLength

describe 'Blocks' do
describe 'an empty block' do
it 'renders with one space' do
assert_equal_and_valid(
'loop {}',
'loop { }'
)
end
end

describe 'a block with a paramer and a body' do
it 'inserts a space arount the content and paramter' do
assert_equal_and_valid(
'loop {|el|el + 1}',
'loop { |el| el + 1 }'
)
end
end

describe 'a block with no parameter and a body' do
it 'surrounds the block content with one space' do
assert_equal_and_valid(
'loop { true}',
'loop { true }'
)
end
end

describe 'a block with a parameter and no body' do
it 'inserts one space around the parameter' do
assert_equal_and_valid(
'loop {|el| }',
'loop { |el| }'
)
end
end

def assert_equal_and_valid(input, expected)
result = apply_prettier(input)
assert_equal expected, result
ensure_valid(expected)
end

def ensure_valid(string)
_, stderr_str, status = Open3.capture3('ruby -c', stdin_data: string)
assert_equal status.success?, true, stderr_str
end

def apply_prettier(string)
file = write_string_to_tempfile(string)
run_prettier_on_file(file.path)
end

def write_string_to_tempfile(string)
Tempfile.new('prettier-ruby-test.rb').tap do |file|
file.write(string)
file.close
end
end

def run_prettier_on_file(path)
`bin/print #{path}`.rstrip
end
end

# rubocop:enable Metrics/BlockLength
5 changes: 4 additions & 1 deletion src/nodes/blocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,14 @@ const printBlock = (path, opts, print) => {
return concat([breakParent, doBlock]);
}

const blockContents = statements.body[0].body;
const blockContentsEmpty = blockContents.length === 0;

const braceBlock = concat([
" { ",
variables ? path.call(print, "body", 0) : "",
path.call(print, "body", 1),
" }"
blockContentsEmpty ? "}" : " }"
]);

return group(ifBreak(doBlock, braceBlock));
Expand Down
2 changes: 2 additions & 0 deletions test/cases/__snapshots__/blocks.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ end

loop { super_super_super_super_super_super_super_super_super_super_super_long }

loop { |i| }

loop { |i| 1 }

loop { |i; j| 1 }
Expand Down
2 changes: 2 additions & 0 deletions test/cases/blocks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
super_super_super_super_super_super_super_super_super_super_super_long
end

loop { |i| }

loop { |i| 1 }

loop { |i; j| 1 }
Expand Down