class Mago::Detector

Magic numbers detector.

@example

detector = Mago::Detector.new('./Rakefile', './lib')
detector.run # => #<Mago::Report ...>

Constants

DEFAULT_IGNORE

Numbers which are ignored by default

Public Class Methods

new(file_paths = [], options = {}) click to toggle source

@param file_paths [String] ruby files @param options [Hash]

@option options :ignore [Array<Numeric>] numbers which must be ignored

# File lib/mago/detector.rb, line 15
def initialize(file_paths = [], options = {})
  @file_paths = file_paths
  @report = Report.new
  @ignore = options[:ignore] || DEFAULT_IGNORE
end

Public Instance Methods

on_error(&block) click to toggle source

Set callback to be called when error occurs.

# File lib/mago/detector.rb, line 37
def on_error(&block)
  @on_error = block
end
on_file(&block) click to toggle source

Set callback to be called when file processing is finished.

# File lib/mago/detector.rb, line 32
def on_file(&block)
  @on_file = block
end
run() click to toggle source

Process files and build a report.

@return [Mago::Report]

# File lib/mago/detector.rb, line 24
def run
  @file_paths.each do |path|
    process_file(path)
  end
  @report
end

Private Instance Methods

handle_error(error) click to toggle source

Add error to report and call on_error callback if it's set.

@param error [String]

@return [void]

# File lib/mago/detector.rb, line 71
def handle_error(error)
  @on_error.call(error) if @on_error
  @report.errors << error
end
process_file(path) click to toggle source

Process a file and add a result to the report.

@param path [String]

@return [void]

# File lib/mago/detector.rb, line 49
def process_file(path)
  code      = File.read(path)
  sexp_node = RubyParser.new.parse(code)
  file      = Mago::RubyFile.new(path)

  sexp_processor = Mago::SexpProcessor.new(file, @ignore)
  sexp_processor.process(sexp_node)

  @report.files << file
  @on_file.call(file) if @on_file
rescue Errno::ENOENT => err
  handle_error(err.message)
rescue Racc::ParseError, Encoding::CompatibilityError => err
  msg = "#{path} has invalid ruby code. " << err.message
  handle_error(msg)
end