class SpecFileGenerator::KlassExtractor

Public Class Methods

new(source_file) click to toggle source
# File lib/spec_file_generator/klass_extractor.rb, line 7
def initialize(source_file)
  @source_file = source_file
end

Public Instance Methods

call() click to toggle source
# File lib/spec_file_generator/klass_extractor.rb, line 11
def call
  ensure_source_file_exist!

  @module_acc = []
  @spec_name = nil
  look_for_class(ast)

  return @spec_name unless @spec_name.nil?

  raise ClassDeclarationMissingError,
        "Please check content of source file (#{@source_file}). " \
        "Class declaration must present in order to generate spec file."
end

Private Instance Methods

ast() click to toggle source

rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity

# File lib/spec_file_generator/klass_extractor.rb, line 44
def ast
  Parser::CurrentRuby.parse(File.read(@source_file))
rescue Parser::SyntaxError => e
  raise SpecFileGenerator::SyntaxError,
        "Please check content of source file (#{@source_file}). " \
        "It seems to have incorrect ruby syntax:\n#{e}"
end
ensure_source_file_exist!() click to toggle source
# File lib/spec_file_generator/klass_extractor.rb, line 52
def ensure_source_file_exist!
  raise IncorrectSourceFileError, @source_file unless File.file?(@source_file)
end
look_for_class(ast) click to toggle source

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity

# File lib/spec_file_generator/klass_extractor.rb, line 28
def look_for_class(ast)
  return unless ast.is_a?(Parser::AST::Node) && @spec_name.nil?

  case ast.type
  when :module
    @module_acc.push(ast.to_sexp_array[1].last.to_s)
    ast.children.map(&method(:look_for_class))
  when :class
    module_names = @module_acc.empty? ? "" : "#{@module_acc.join("::")}::"
    @spec_name = module_names + ast.to_sexp_array[1].last.to_s
  when :begin
    ast.children.map(&method(:look_for_class))
  end
end