Class: Transpec::BaseRewriter

Inherits:
Object
  • Object
show all
Defined in:
lib/transpec/base_rewriter.rb

Direct Known Subclasses

Converter, DynamicAnalyzer::Rewriter

Defined Under Namespace

Classes: OverlappedRewriteError

Instance Method Summary collapse

Instance Method Details

#rewrite(source, name = '(string)') ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/transpec/base_rewriter.rb', line 15

def rewrite(source, name = '(string)')
  source_buffer = create_source_buffer(source, name)
  ast = parse(source_buffer)

  source_rewriter = Parser::Source::Rewriter.new(source_buffer)
  failed_overlapping_rewrite = false
  source_rewriter.diagnostics.consumer = proc do
    failed_overlapping_rewrite = true
    fail OverlappedRewriteError
  end

  process(ast, source_rewriter)

  rewritten_source = source_rewriter.process
  rewritten_source = rewrite(rewritten_source, name) if failed_overlapping_rewrite

  rewritten_source
end

#rewrite_file!(file_path) ⇒ Object



8
9
10
11
12
13
# File 'lib/transpec/base_rewriter.rb', line 8

def rewrite_file!(file_path)
  source = File.read(file_path)
  rewritten_source = rewrite(source, file_path)
  return if source == rewritten_source
  File.write(file_path, rewritten_source)
end