Class: HamlLint::RubyParser

Inherits:
Object
  • Object
show all
Defined in:
lib/haml_lint/ruby_parser.rb

Overview

Parser for the Ruby language.

This provides a convenient wrapper around the ‘parser` gem and the Astrolabe integration (now built-in to RuboCop, so no longer called Astrolabe) to go with it. It is intended to be used for linter checks that require deep inspection of Ruby code.

Instance Method Summary collapse

Constructor Details

#initializeRubyParser

Creates a reusable parser.



15
16
17
18
19
# File 'lib/haml_lint/ruby_parser.rb', line 15

def initialize
  require_parser
  @builder = ::RuboCop::AST::Builder.new
  @parser = ::Parser::CurrentRuby.new(@builder)
end

Instance Method Details

#parse(source) ⇒ Array

Parse the given Ruby source into an abstract syntax tree.

Parameters:

  • source (String)

    Ruby source code

Returns:

  • (Array)

    syntax tree in the form returned by Parser gem



35
36
37
38
39
40
41
# File 'lib/haml_lint/ruby_parser.rb', line 35

def parse(source)
  buffer = ::Parser::Source::Buffer.new('(string)')
  buffer.source = source

  @parser.reset
  @parser.parse(buffer)
end

#require_parserObject

Require the current parser version while suppressing the compliancy warning for minor version differences.



23
24
25
26
27
28
29
# File 'lib/haml_lint/ruby_parser.rb', line 23

def require_parser
  prev = $VERBOSE
  $VERBOSE = nil
  require 'parser/current'
ensure
  $VERBOSE = prev
end