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]

Instance Attribute Summary

Attributes inherited from Selector

#next

Attributes inherited from Expression

#next, #value

Instance Method Summary collapse

Methods inherited from Selector

#==

Methods inherited from Expression

#indented, #literal?, #singular_query?, #type

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)


39
40
41
42
43
44
45
# File 'lib/janeway/ast/name_selector.rb', line 39

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

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

Parameters:

  • brackets (Boolean) (defaults to: false)

    request for bracket syntax

  • dot_prefix (Boolean) (defaults to: true)

    include . prefix, if shorthand notation is used



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/janeway/ast/name_selector.rb', line 22

def to_s(brackets: false, dot_prefix: true)
  # Add quotes and surrounding brackets if the name includes chars that require quoting.
  # These chars are not allowed in dotted notation, only bracket notation.
  special_chars = [' ', '.']
  brackets ||= special_chars.any? { |char| @value.include?(char) }
  if brackets
    name_str = quote(@value)
    "[#{name_str}]#{@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)


49
50
51
# File 'lib/janeway/ast/name_selector.rb', line 49

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