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

#pretty_print, #to_json

Constructor Details

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

Returns a new instance of StringLiteral.



8162
8163
8164
8165
8166
8167
# File 'lib/syntax_tree/node.rb', line 8162

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



8160
8161
8162
# File 'lib/syntax_tree/node.rb', line 8160

def comments
  @comments
end

#partsObject (readonly)

Array[ StringEmbExpr | StringDVar | TStringContent ]

the parts of the

string literal



8154
8155
8156
# File 'lib/syntax_tree/node.rb', line 8154

def parts
  @parts
end

#quoteObject (readonly)

String

which quote was used by the string literal



8157
8158
8159
# File 'lib/syntax_tree/node.rb', line 8157

def quote
  @quote
end

Instance Method Details

#accept(visitor) ⇒ Object



8169
8170
8171
# File 'lib/syntax_tree/node.rb', line 8169

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

#child_nodesObject Also known as: deconstruct



8173
8174
8175
# File 'lib/syntax_tree/node.rb', line 8173

def child_nodes
  parts
end

#deconstruct_keys(keys) ⇒ Object



8179
8180
8181
# File 'lib/syntax_tree/node.rb', line 8179

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

#format(q) ⇒ Object



8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
# File 'lib/syntax_tree/node.rb', line 8183

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