Skip to content

Commit 4718799

Browse files
committed
feat: allow formatting code with different base level of indentation
ref: #333
1 parent 358cce6 commit 4718799

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

lib/rufo/formatter.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ class Rufo::Formatter
44
include Rufo::Settings
55

66
INDENT_SIZE = 2
7+
DEFAULT_BASE_INDENTATION = 0
78
EMPTY_STRING = [:string_literal, [:string_content]]
89
EMPTY_HASH = [:hash, nil]
910

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

175+
@base_indentation = options.delete(:base_indentation) || DEFAULT_BASE_INDENTATION
176+
174177
init_settings(options)
175178
end
176179

@@ -186,6 +189,9 @@ def format
186189
remove_lines_before_inline_declarations
187190
@output.lstrip!
188191
@output = "\n" if @output.empty?
192+
if @base_indentation > 0
193+
insert_base_indent(@base_indentation)
194+
end
189195
end
190196

191197
def visit(node)
@@ -4214,4 +4220,13 @@ def block_arg_type(node)
42144220
node
42154221
end
42164222
end
4223+
4224+
def insert_base_indent(identation)
4225+
spaces = " " * identation
4226+
lines = @output.lines
4227+
lines.each do |line|
4228+
line.insert(0, spaces)
4229+
end
4230+
@output = lines.join
4231+
end
42174232
end

spec/lib/rufo/formatter_spec.rb

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,41 @@ def assert_format(code, expected = code, **options)
111111
}.to raise_error(Rufo::UnknownSyntaxError)
112112
end
113113
end
114+
115+
describe 'base_indentation option' do
116+
it 'formats with different indentation levels' do
117+
source = <<~SOURCE
118+
def foo
119+
puts "a"
120+
end
121+
SOURCE
122+
123+
# default identation level
124+
expect(Rufo.format(source)).to eq source
125+
126+
# level 2
127+
expected = <<-EXPECTED
128+
def foo
129+
puts "a"
130+
end
131+
EXPECTED
132+
expect(Rufo.format(source, base_indentation: 2)).to eq expected
133+
134+
# level 4
135+
expected = <<-EXPECTED
136+
def foo
137+
puts "a"
138+
end
139+
EXPECTED
140+
expect(Rufo.format(source, base_indentation: 4)).to eq expected
141+
142+
# level 6
143+
expected = <<-EXPECTED
144+
def foo
145+
puts "a"
146+
end
147+
EXPECTED
148+
expect(Rufo.format(source, base_indentation: 6)).to eq expected
149+
end
150+
end
114151
end

0 commit comments

Comments
 (0)