DEV Community

Shuichi Tamayose
Shuichi Tamayose

Posted on

Use `coverage` gem to check method call count in Ruby.

coverage gem of ruby 2.5 can get method coverage. so, I wrote a code to check the count of the method call.

sample code. (fizzbuzz.rb)

def fizz
  "Fizz"
end

def buzz
  "Buzz"
end

def fizzbuzz
  "FizzBuzz"
end

1.upto(100) do |n|
  if n % 15 == 0
    puts fizzbuzz
  elsif n % 3 == 0
    puts fizz
  elsif n % 5 == 0
    puts buzz
  else
    puts n
  end
end
Enter fullscreen mode Exit fullscreen mode

check code (RUBY_VERSION >= "2.5.0")
It use termianl-table to make the results easy to see.

require "coverage"
require "terminal-table"

Coverage.start(methods: true)
require_relative "fizzbuzz"
result = Coverage.result

rows = []

result.each do |filepath, coverage_data|
  filename = File.basename(filepath)
  methods = coverage_data[:methods]

  methods.each do |method_data, count|
    next if count.zero?

    defined_class, method_id, _from_row, _from_col, _to_row, _to_col = *method_data
    rows << [filename, defined_class, method_id, count]
  end
end

header = %w(filename defined_class method_id count)
rows.sort_by! { |e| -e.last }
table = Terminal::Table.new headings: header, rows: rows
puts table
Enter fullscreen mode Exit fullscreen mode

Result

.
.
# display fizzbuzz.rb result
.
.
+-------------+---------------+-----------+-------+
| filename    | defined_class | method_id | count |
+-------------+---------------+-----------+-------+
| fizzbuzz.rb | Object        | fizz      | 27    |
| fizzbuzz.rb | Object        | buzz      | 14    |
| fizzbuzz.rb | Object        | fizzbuzz  | 6     |
+-------------+---------------+-----------+-------+
Enter fullscreen mode Exit fullscreen mode

looks to good.

Top comments (1)

Collapse
 
ben profile image
Ben Halpern

Ah it's great to immediately visualize how this might look. I'd been thinking mostly abstractly about this component of 2.5. I'm really excited about the future of Ruby. I feel like Maz and the community are making nice improvements here and there whenever I look.