Class: ImproveYourCode::Source::SourceCode

Inherits:
Object
  • Object
show all
Defined in:
lib/improve_your_code/source/source_code.rb

Constant Summary collapse

IO_IDENTIFIER =
'STDIN'
STRING_IDENTIFIER =
'string'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code:, origin:, parser: default_parser) ⇒ SourceCode

Returns a new instance of SourceCode.



21
22
23
24
25
26
# File 'lib/improve_your_code/source/source_code.rb', line 21

def initialize(code:, origin:, parser: default_parser)
  @origin = origin
  @diagnostics = []
  @parser = parser
  @code = code
end

Instance Attribute Details

#originObject (readonly)

Returns the value of attribute origin.



19
20
21
# File 'lib/improve_your_code/source/source_code.rb', line 19

def origin
  @origin
end

Class Method Details

.from(source) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/improve_your_code/source/source_code.rb', line 28

def self.from(source)
  case source
  when File then new(code: source.read, origin: source.path)
  when IO then new(code: source.readlines.join, origin: IO_IDENTIFIER)
  when Pathname then new(code: source.read, origin: source.to_s)
  when String then new(code: source, origin: STRING_IDENTIFIER)
  end
end

Instance Method Details

#diagnosticsObject



43
44
45
46
47
# File 'lib/improve_your_code/source/source_code.rb', line 43

def diagnostics
  parse_if_needed

  @diagnostics
end

#syntax_treeObject



49
50
51
# File 'lib/improve_your_code/source/source_code.rb', line 49

def syntax_tree
  parse_if_needed
end

#valid_syntax?Boolean

Returns:

  • (Boolean)


37
38
39
40
41
# File 'lib/improve_your_code/source/source_code.rb', line 37

def valid_syntax?
  diagnostics.none? do |diagnostic|
    %i[error fatal].include?(diagnostic.level)
  end
end