Class: RSpec::Support::Source

Inherits:
Object
  • Object
show all
Defined in:
lib/rspec/support/source.rb,
lib/rspec/support/source/node.rb,
lib/rspec/support/source/token.rb,
lib/rspec/support/source/location.rb

Overview

Represents a Ruby source file and provides access to AST and tokens.

Defined Under Namespace

Classes: ExpressionSequenceNode, File, Location, Node, Token

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source_string, path = nil) ⇒ Source

:nocov:



35
36
37
38
# File 'lib/rspec/support/source.rb', line 35

def initialize(source_string, path=nil)
  @source = RSpec::Support::EncodedString.new(source_string, Encoding.default_external)
  @path = path ? File.expand_path(path) : '(string)'
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



11
12
13
# File 'lib/rspec/support/source.rb', line 11

def path
  @path
end

#sourceObject (readonly)

Returns the value of attribute source.



11
12
13
# File 'lib/rspec/support/source.rb', line 11

def source
  @source
end

Class Method Details

.from_file(path) ⇒ Object



23
24
25
26
# File 'lib/rspec/support/source.rb', line 23

def self.from_file(path)
  source = File.read(path)
  new(source, path)
end

Instance Method Details

#astObject



54
55
56
57
58
59
60
61
# File 'lib/rspec/support/source.rb', line 54

def ast
  @ast ||= begin
    require 'ripper'
    sexp = Ripper.sexp(source)
    raise SyntaxError unless sexp
    Node.new(sexp)
  end
end

#inspectObject



46
47
48
# File 'lib/rspec/support/source.rb', line 46

def inspect
  "#<#{self.class} #{path}>"
end

#linesObject



42
43
44
# File 'lib/rspec/support/source.rb', line 42

def lines
  @lines ||= source.split("\n")
end

#nodes_by_line_numberObject



71
72
73
74
75
76
# File 'lib/rspec/support/source.rb', line 71

def 
  @nodes_by_line_number ||= begin
     = ast.select(&:location).group_by { |node| node.location.line }
    Hash.new { |hash, key| hash[key] = [] }.merge()
  end
end

#tokensObject



63
64
65
66
67
68
69
# File 'lib/rspec/support/source.rb', line 63

def tokens
  @tokens ||= begin
    require 'ripper'
    tokens = Ripper.lex(source)
    Token.tokens_from_ripper_tokens(tokens)
  end
end

#tokens_by_line_numberObject



78
79
80
81
82
83
# File 'lib/rspec/support/source.rb', line 78

def 
  @tokens_by_line_number ||= begin
     = tokens.group_by { |token| token.location.line }
    Hash.new { |hash, key| hash[key] = [] }.merge()
  end
end