Class: Rjq::AST::Variable

Inherits:
Node
  • Object
show all
Defined in:
lib/rjq/ast.rb

Instance Attribute Summary collapse

Attributes inherited from Node

#source_span

Instance Method Summary collapse

Methods inherited from Node

#assign_value, #invalid_path_message, #take, #with_source_span

Constructor Details

#initialize(name) ⇒ Variable

Returns a new instance of Variable.



270
271
272
# File 'lib/rjq/ast.rb', line 270

def initialize(name)
  @name = name
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



268
269
270
# File 'lib/rjq/ast.rb', line 268

def name
  @name
end

Instance Method Details

#eval(_input, context) ⇒ Object

Raises:



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/rjq/ast.rb', line 274

def eval(_input, context)
  return [ENV.to_h] if @name == 'ENV'

  if @name == 'ARGS'
    positional = context.variables.fetch('ARGS.positional', [])
    named = context.variables.fetch('ARGS.named', {})
    return [{ 'positional' => positional, 'named' => named }]
  end
  if @name == '__loc__'
    return [{ 'file' => source_span&.filename || context.options.fetch(:source_path, '<top-level>'),
              'line' => source_span&.line || 1 }]
  end

  raise RuntimeError, "variable $#{@name} is not defined" unless context.variables.key?(@name)

  [context.variables[@name]]
end

#paths(input, context) ⇒ Object

Raises:



292
293
294
295
296
297
# File 'lib/rjq/ast.rb', line 292

def paths(input, context)
  return [context.binding_variable_paths.fetch(@name)] if context.binding_variable_paths.key?(@name)

  result = eval(input, context).first
  raise InvalidPathError.new(invalid_path_message(result, input, context), result)
end