lib/slim_lint/linter/rubocop.rb in slim_lint-0.14.0 vs lib/slim_lint/linter/rubocop.rb in slim_lint-0.15.0
- old
+ new
@@ -1,9 +1,8 @@
require 'slim_lint/ruby_extractor'
require 'slim_lint/ruby_extract_engine'
require 'rubocop'
-require 'tempfile'
module SlimLint
# Runs RuboCop on Ruby code extracted from Slim templates.
class Linter::RuboCop < Linter
include LinterRegistry
@@ -28,22 +27,14 @@
# @param source_map [Hash] map of Ruby code line numbers to original line
# numbers in the template
def find_lints(ruby, source_map)
rubocop = ::RuboCop::CLI.new
- original_filename = document.file || 'ruby_script'
- filename = "#{File.basename(original_filename)}.slim_lint.tmp"
- directory = File.dirname(original_filename)
+ filename = document.file ? "#{document.file}.rb" : 'ruby_script.rb'
- Tempfile.open([filename, '.rb'], directory) do |f|
- begin
- f.write(ruby)
- f.close
- extract_lints_from_offenses(lint_file(rubocop, f.path), source_map)
- ensure
- f.unlink
- end
+ with_ruby_from_stdin(ruby) do
+ extract_lints_from_offenses(lint_file(rubocop, filename), source_map)
end
end
# Defined so we can stub the results in tests
#
@@ -74,10 +65,27 @@
#
# @return [Array<String>]
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
+
+ # 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]
+ 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
end
# Collects offenses detected by RuboCop.
class OffenseCollector < ::RuboCop::Formatter::BaseFormatter