Class: SyntaxTree::StringLiteral

Inherits:
Node
  • Object
show all
Defined in:
lib/syntax_tree/node.rb

Overview

StringLiteral represents a string literal.

"string"

Instance Attribute Summary collapse

Attributes inherited from Node

#location

Instance Method Summary collapse

Methods inherited from Node

#construct_keys, #pretty_print, #to_json

Constructor Details

#initialize(parts:, quote:, location:, comments: []) ⇒ StringLiteral

Returns a new instance of StringLiteral.



8268
8269
8270
8271
8272
8273
# File 'lib/syntax_tree/node.rb', line 8268

def initialize(parts:, quote:, location:, comments: [])
  @parts = parts
  @quote = quote
  @location = location
  @comments = comments
end

Instance Attribute Details

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



8266
8267
8268
# File 'lib/syntax_tree/node.rb', line 8266

def comments
  @comments
end

#partsObject (readonly)

Array[ StringEmbExpr | StringDVar | TStringContent ]

the parts of the

string literal



8260
8261
8262
# File 'lib/syntax_tree/node.rb', line 8260

def parts
  @parts
end

#quoteObject (readonly)

String

which quote was used by the string literal



8263
8264
8265
# File 'lib/syntax_tree/node.rb', line 8263

def quote
  @quote
end

Instance Method Details

#accept(visitor) ⇒ Object



8275
8276
8277
# File 'lib/syntax_tree/node.rb', line 8275

def accept(visitor)
  visitor.visit_string_literal(self)
end

#child_nodesObject Also known as: deconstruct



8279
8280
8281
# File 'lib/syntax_tree/node.rb', line 8279

def child_nodes
  parts
end

#deconstruct_keys(_keys) ⇒ Object



8285
8286
8287
# File 'lib/syntax_tree/node.rb', line 8285

def deconstruct_keys(_keys)
  { parts: parts, quote: quote, location: location, comments: comments }
end

#format(q) ⇒ Object



8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
# File 'lib/syntax_tree/node.rb', line 8289

def format(q)
  if parts.empty?
    q.text("#{q.quote}#{q.quote}")
    return
  end

  opening_quote, closing_quote =
    if !Quotes.locked?(self)
      [q.quote, q.quote]
    elsif quote.start_with?("%")
      [quote, Quotes.matching(quote[/%[qQ]?(.)/, 1])]
    else
      [quote, quote]
    end

  q.group(0, opening_quote, closing_quote) do
    parts.each do |part|
      if part.is_a?(TStringContent)
        value = Quotes.normalize(part.value, closing_quote)
        separator = -> { q.breakable(force: true, indent: false) }
        q.seplist(value.split(/\r?\n/, -1), separator) do |text|
          q.text(text)
        end
      else
        q.format(part)
      end
    end
  end
end