diff --git a/lib/erb_lint/utils/offset_corrector.rb b/lib/erb_lint/utils/offset_corrector.rb index c7e648e..c4913c2 100644 --- a/lib/erb_lint/utils/offset_corrector.rb +++ b/lib/erb_lint/utils/offset_corrector.rb @@ -38,7 +38,9 @@ def remove_trailing(range, size) @corrector.remove_trailing(range_with_offset(range), size) end - def range_with_offset(range) + def range_with_offset(node_or_range) + range = to_range(node_or_range) + @processed_source.to_source_range( bound(@offset + range.begin_pos)..bound(@offset + (range.end_pos - 1)) ) @@ -50,6 +52,21 @@ def bound(pos) @bound_range.max, ].min end + + private + + def to_range(node_or_range) + case node_or_range + when ::RuboCop::AST::Node, ::Parser::Source::Comment + node_or_range.loc.expression + when ::Parser::Source::Range + node_or_range + else + raise TypeError, + 'Expected a Parser::Source::Range, Comment or ' \ + "Rubocop::AST::Node, got #{node_or_range.class}" + end + end end end end diff --git a/spec/erb_lint/linters/rubocop_spec.rb b/spec/erb_lint/linters/rubocop_spec.rb index 2a9d1eb..8c60c8e 100644 --- a/spec/erb_lint/linters/rubocop_spec.rb +++ b/spec/erb_lint/linters/rubocop_spec.rb @@ -95,6 +95,31 @@ it { expect(subject).to(eq("<%= safe_method %>\n")) } end + + context 'when autocorrecting from rubocop cops' do + let(:file) { <<~FILE } + <%= 'should_be_double_quoted' %> + FILE + + let(:linter_config) do + described_class.config_schema.new( + only: ['Style/StringLiterals'], + rubocop_config: { + AllCops: { + TargetRubyVersion: '2.7', + }, + 'Style/StringLiterals': { + EnforcedStyle: 'double_quotes', + Enabled: true, + }, + }, + ) + end + + subject { corrected_content } + + it { expect(subject).to(eq(%(<%= "should_be_double_quoted" %>\n))) } + end end context 'when multiple offenses are found in the same block' do diff --git a/spec/lib/erb_lint/utils/offset_corrector_spec.rb b/spec/lib/erb_lint/utils/offset_corrector_spec.rb new file mode 100644 index 0000000..ec825ec --- /dev/null +++ b/spec/lib/erb_lint/utils/offset_corrector_spec.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +require 'spec_helper' + +describe ERBLint::Utils::OffsetCorrector do + let(:processed_source) { ERBLint::ProcessedSource.new('file.rb', '<%= "" %>') } + + it 'supports node as argument' do + described_class + .new(processed_source, double(:corrector, remove: true), 0, 0..1) + .remove(node) + end + + private + + def node + parser = Parser::CurrentRuby.new(RuboCop::AST::Builder.new) + parser.parse(Parser::Source::Buffer.new('(string)').tap { |buffer| buffer.source = '""' }) + end +end