Class: Janeway::AST::NameSelector

Inherits:
Selector show all
Defined in:
lib/janeway/ast/name_selector.rb

Overview

A name selector, e.g. 'name', selects a named child of an object. The dot or bracket part is not captured here, only the name

Examples:

$.store
$[store]

Constant Summary collapse

SPECIAL_CHARS =

Chars that force bracket notation (they are not permitted in the dotted shorthand).

/[ .]/

Instance Attribute Summary

Attributes inherited from Expression

#next, #value

Instance Method Summary collapse

Methods inherited from Expression

#chain_of?, #indented, #literal?, #singular_query?, #type, type_name

Constructor Details

#initialize(value) ⇒ NameSelector

Returns a new instance of NameSelector.



15
16
17
18
# File 'lib/janeway/ast/name_selector.rb', line 15

def initialize(value)
  super
  raise "Invalid name: #{value.inspect}:#{value.class}" unless value.is_a?(String)
end

Instance Method Details

#quote(str) ⇒ String

put surrounding quotes on a string

Returns:

  • (String)


44
45
46
47
48
49
50
# File 'lib/janeway/ast/name_selector.rb', line 44

def quote(str)
  if str.include?("'")
    format('"%s"', str)
  else
    "'#{str}'"
  end
end

#to_s(brackets: false, dot_prefix: true, bracketed: false) ⇒ Object

Parameters:

  • brackets (Boolean) (defaults to: false)

    request for bracket syntax

  • dot_prefix (Boolean) (defaults to: true)

    include . prefix, if shorthand notation is used

  • bracketed (Boolean) (defaults to: false)

    caller already provided brackets (e.g. within a union); emit the quoted name only, without adding brackets



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/janeway/ast/name_selector.rb', line 28

def to_s(brackets: false, dot_prefix: true, bracketed: false)
  # Add quotes and surrounding brackets if the name includes chars that require quoting.
  brackets ||= @value.match?(SPECIAL_CHARS)
  if bracketed
    "#{quote(@value)}#{@next}"
  elsif brackets
    "[#{quote(@value)}]#{@next}"
  elsif dot_prefix
    ".#{@value}#{@next}"
  else # omit dot prefix after a descendant segment
    "#{@value}#{@next}"
  end
end

#tree(level) ⇒ Array

Parameters:

  • level (Integer)

Returns:

  • (Array)


54
55
56
# File 'lib/janeway/ast/name_selector.rb', line 54

def tree(level)
  [indented(level, "NameSelector:\"#{@value}\""), @next&.tree(level + 1)]
end