Skip to content
Open
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
15 changes: 15 additions & 0 deletions lib/rufo/formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ class Rufo::Formatter
include Rufo::Settings

INDENT_SIZE = 2
DEFAULT_BASE_INDENTATION = 0
EMPTY_STRING = [:string_literal, [:string_content]]
EMPTY_HASH = [:hash, nil]

Expand Down Expand Up @@ -171,6 +172,8 @@ def initialize(code, **options)
# can be added appropriately for heredocs for example.
@literal_elements_level = nil

@base_indentation = options.delete(:base_indentation) || DEFAULT_BASE_INDENTATION

init_settings(options)
end

Expand All @@ -186,6 +189,9 @@ def format
remove_lines_before_inline_declarations
@output.lstrip!
@output = "\n" if @output.empty?
if @base_indentation > 0
insert_base_indent(@base_indentation)
end
end

def visit(node)
Expand Down Expand Up @@ -4214,4 +4220,13 @@ def block_arg_type(node)
node
end
end

def insert_base_indent(identation)
spaces = " " * identation
lines = @output.lines
lines.each do |line|
line.insert(0, spaces)
end
@output = lines.join
end
end
37 changes: 37 additions & 0 deletions spec/lib/rufo/formatter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,41 @@ def assert_format(code, expected = code, **options)
}.to raise_error(Rufo::UnknownSyntaxError)
end
end

describe "base_indentation option" do
it "formats with different indentation levels" do
source = <<~SOURCE
def foo
puts "a"
end
SOURCE

# default identation level
expect(Rufo.format(source)).to eq source

# level 2
expected = <<-EXPECTED
def foo
puts "a"
end
EXPECTED
expect(Rufo.format(source, base_indentation: 2)).to eq expected

# level 4
expected = <<-EXPECTED
def foo
puts "a"
end
EXPECTED
expect(Rufo.format(source, base_indentation: 4)).to eq expected

# level 6
expected = <<-EXPECTED
def foo
puts "a"
end
EXPECTED
expect(Rufo.format(source, base_indentation: 6)).to eq expected
end
end
end