class RSpec::Support::Source

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

Constants

Location

@private Represents a source location of node or token.

Attributes

path[R]
source[R]

Public Class Methods

from_file(path) click to toggle source
# File lib/rspec/support/source.rb, line 21
def self.from_file(path)
  source = File.read(path)
  new(source, path)
end
new(source_string, path=nil) click to toggle source
# File lib/rspec/support/source.rb, line 27
def initialize(source_string, path=nil)
  @source = RSpec::Support::EncodedString.new(source_string, Encoding.default_external)
  @path = path ? File.expand_path(path) : '(string)'
end

Public Instance Methods

ast() click to toggle source
# File lib/rspec/support/source.rb, line 52
def ast
  @ast ||= begin
    require 'ripper'
    sexp = Ripper.sexp(source)
    raise SyntaxError unless sexp
    Node.new(sexp)
  end
end
inspect() click to toggle source
# File lib/rspec/support/source.rb, line 44
def inspect
  "#<#{self.class} #{path}>"
end
lines() click to toggle source
# File lib/rspec/support/source.rb, line 40
def lines
  @lines ||= source.split("\n")
end
nodes_by_line_number() click to toggle source
# File lib/rspec/support/source.rb, line 69
def nodes_by_line_number
  @nodes_by_line_number ||= begin
    nodes_by_line_number = ast.select(&:location).group_by { |node| node.location.line }
    Hash.new { |hash, key| hash[key] = [] }.merge(nodes_by_line_number)
  end
end
tokens() click to toggle source
# File lib/rspec/support/source.rb, line 61
def tokens
  @tokens ||= begin
    require 'ripper'
    tokens = Ripper.lex(source)
    Token.tokens_from_ripper_tokens(tokens)
  end
end
tokens_by_line_number() click to toggle source
# File lib/rspec/support/source.rb, line 76
def tokens_by_line_number
  @tokens_by_line_number ||= begin
    nodes_by_line_number = tokens.group_by { |token| token.location.line }
    Hash.new { |hash, key| hash[key] = [] }.merge(nodes_by_line_number)
  end
end