Class: Seethe::Complexity

Inherits:
Object
  • Object
show all
Defined in:
lib/seethe/complexity.rb

Constant Summary collapse

ERBHandler =
ActionView::Template::Handlers::ERB.new

Instance Method Summary collapse

Constructor Details

#initialize(path, flog_cutoff) ⇒ Complexity

Returns a new instance of Complexity.



13
14
15
16
# File 'lib/seethe/complexity.rb', line 13

def initialize(path, flog_cutoff)
  @path = path
  @cutoff = flog_cutoff
end

Instance Method Details

#flog_totals_for(sexp) ⇒ Object



49
50
51
52
53
54
# File 'lib/seethe/complexity.rb', line 49

def flog_totals_for(sexp)
  flog = Flog.new
  flog.process(sexp)
  flog.calculate_total_scores
  flog.totals
end

#new_template(body, details = {format: :html}) ⇒ Object



18
19
20
# File 'lib/seethe/complexity.rb', line 18

def new_template(body, details={format: :html})
  ActionView::Template.new(body, "irrelevant", details.fetch(:handler) {ERBHandler}, details)
end

#processObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/seethe/complexity.rb', line 22

def process
  unless @path.is_a? Array
    @path = Seethe.glob_directory(@path)
  end
  totals = @path.inject({}) do |totals, file|
    begin
      ruby_source = File.read(file)
      ruby_source = ERBHandler.call(new_template(ruby_source)) if file.end_with?(".erb")
      sexp_parsed = RubyParser.new.parse(ruby_source)

      flog_totals = flog_totals_for(sexp_parsed) 
      mean = flog_totals.map { |k,v| v }.select { |v| v > @cutoff }.mean
      totals[file] = mean unless mean.nil?
    rescue Exception => e
      puts "Error parsing #{file} (#{e.message})"
    end
    totals
  end

  totals = totals.sort do |(ak,av), (bk,bv)|
    bv <=> av
  end

  # This really isn't necessary, but I like hashes.
  totals.inject({}) { |memo, ary| memo[ary[0]] = ary[1]; memo }
end