Class: RubyNext::Language::Rewriters::SquigglyHeredoc

Inherits:
Base
  • Object
show all
Defined in:
lib/ruby-next/language/rewriters/2.3/squiggly_heredoc.rb

Constant Summary collapse

NAME =
"squiggly-heredoc"
SYNTAX_PROBE =
"txt = <<~TXT\n  bla\n      TXT"
MIN_SUPPORTED_VERSION =
Gem::Version.new("2.3.0")

Instance Attribute Summary

Attributes inherited from Base

#locals

Instance Method Summary collapse

Methods inherited from Base

ast?, #initialize, #s

Methods inherited from Abstract

ast?, #initialize, text?, unsupported_syntax?, unsupported_version?

Constructor Details

This class inherits a constructor from RubyNext::Language::Rewriters::Base

Instance Method Details

#on_str(node) ⇒ Object Also known as: on_dstr, on_xstr



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/ruby-next/language/rewriters/2.3/squiggly_heredoc.rb', line 11

def on_str(node)
  node = super(node) if defined?(super_method)
  return node unless node.loc.respond_to?(:heredoc_body) && node.loc.expression.source.include?("<<~")

  context.track! self

  replace(node.loc.expression, node.loc.expression.source.tr("~", "-"))

  heredoc_loc = node.loc.heredoc_body.join(node.loc.heredoc_end)
  heredoc_source, heredoc_end = heredoc_loc.source.split(/\n([^\n]+)\z/)

  indent = heredoc_source.lines.map { |line| line.match(/^\s*/)[0].size }.min

  new_source = heredoc_source.gsub!(%r{^\s{#{indent}}}, "")

  replace(heredoc_loc, [new_source, heredoc_end].join("\n"))

  node
end