Module: SyntaxTree::Quotes

Defined in:
lib/syntax_tree/node.rb

Overview

Responsible for providing information about quotes to be used for strings and dynamic symbols.

Constant Summary collapse

PAIRS =

The matching pairs of quotes that can be used with % literals.

{ "(" => ")", "[" => "]", "{" => "}", "<" => ">" }.freeze

Class Method Summary collapse

Class Method Details

.locked?(node, quote) ⇒ Boolean

If there is some part of this string that matches an escape sequence or that contains the interpolation pattern (“#{”), then we are locked into whichever quote the user chose. (If they chose single quotes, then double quoting would activate the escape sequence, and if they chose double quotes, then single quotes would deactivate it.)

Returns:

  • (Boolean)


3866
3867
3868
3869
3870
# File 'lib/syntax_tree/node.rb', line 3866

def self.locked?(node, quote)
  node.parts.any? do |part|
    !part.is_a?(TStringContent) || part.value.match?(/\\|#[@${]|#{quote}/)
  end
end

.matching(quote) ⇒ Object

Find the matching closing quote for the given opening quote.



3873
3874
3875
# File 'lib/syntax_tree/node.rb', line 3873

def self.matching(quote)
  PAIRS.fetch(quote) { quote }
end

.normalize(content, enclosing) ⇒ Object

Escape and unescape single and double quotes as needed to be able to enclose content with enclosing.



3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
# File 'lib/syntax_tree/node.rb', line 3879

def self.normalize(content, enclosing)
  return content if enclosing != "\"" && enclosing != "'"

  content.gsub(/\\([\s\S])|(['"])/) do
    _match, escaped, quote = Regexp.last_match.to_a

    if quote == enclosing
      "\\#{quote}"
    elsif quote
      quote
    else
      "\\#{escaped}"
    end
  end
end