class SlimLint::Linter::RuboCop

Runs RuboCop on Ruby code extracted from Slim templates.

Private Instance Methods

extract_lints_from_offenses(offenses, source_map) click to toggle source

Aggregates RuboCop offenses and converts them to {SlimLint::Lint}s suitable for reporting.

@param offenses [Array<RuboCop::Cop::Offense>] @param source_map [Hash]

# File lib/slim_lint/linter/rubocop.rb, line 56
def extract_lints_from_offenses(offenses, source_map)
  offenses.select { |offense| !config['ignored_cops'].include?(offense.cop_name) }
          .each do |offense|
    @lints << Lint.new(self,
                       document.file,
                       source_map[offense.line],
                       offense.message)
  end
end
find_lints(ruby, source_map) click to toggle source

Executes RuboCop against the given Ruby code and records the offenses as lints.

@param ruby [String] Ruby code @param source_map [Hash] map of Ruby code line numbers to original line

numbers in the template
# File lib/slim_lint/linter/rubocop.rb, line 31
def find_lints(ruby, source_map)
  rubocop = ::RuboCop::CLI.new

  filename = document.file ? "#{document.file}.rb" : 'ruby_script.rb'

  with_ruby_from_stdin(ruby) do
    extract_lints_from_offenses(lint_file(rubocop, filename), source_map)
  end
end
lint_file(rubocop, file) click to toggle source

Defined so we can stub the results in tests

@param rubocop [RuboCop::CLI] @param file [String] @return [Array<RuboCop::Cop::Offense>]

# File lib/slim_lint/linter/rubocop.rb, line 46
def lint_file(rubocop, file)
  rubocop.run(rubocop_flags << file)
  OffenseCollector.offenses
end
rubocop_flags() click to toggle source

Returns flags that will be passed to RuboCop CLI.

@return [Array<String>]

# File lib/slim_lint/linter/rubocop.rb, line 69
def rubocop_flags
  flags = %w[--format SlimLint::OffenseCollector]
  flags += ['--config', ENV['SLIM_LINT_RUBOCOP_CONF']] if ENV['SLIM_LINT_RUBOCOP_CONF']
  flags += ['--stdin']
  flags
end
with_ruby_from_stdin(ruby) { || ... } click to toggle source

Overrides the global stdin to allow RuboCop to read Ruby code from it.

@param ruby [String] the Ruby code to write to the overridden stdin @param _block [Block] the block to perform with the overridden stdin @return [void]

# File lib/slim_lint/linter/rubocop.rb, line 81
def with_ruby_from_stdin(ruby, &_block)
  original_stdin = $stdin
  stdin = StringIO.new
  stdin.write(ruby)
  stdin.rewind
  $stdin = stdin
  yield
ensure
  $stdin = original_stdin
end