LoginSignup
3
2

More than 5 years have passed since last update.

Ruby の coverage を使って一番長い条件式を調べる

Last updated at Posted at 2017-12-26

ruby 2.5 では coverage の機能が増えて分岐カバレッジが取得出来るようになったので、試しに一番長い条件式を取得するコードを書いてみました。

チェック用のサンプルコード

sample.rb
n = 5

if n < 5
  'low'
else
  'high'
end

case n
when 0
  'a'
when 1
  'b'
when 2
  'c'
when 3
  'd'
end

一番長い条件式を取得するためのコード (RUBY_VERSION >= "2.5.0")

get_longest_branch_code.rb
require "coverage"

Coverage.start(branches: true)
require_relative "sample"
result = Coverage.result

max_branch_size = 0
location = ""
longest_branch_code = ""

result.each do |filepath, coverage_data|
  source_code = File.readlines(filepath)
  branches = coverage_data[:branches]

  branches.each do |branch, _clauses|
    _condition_type, _clause_id, from_row, _from_col, to_row, _to_col = *branch
    branch_size = to_row - from_row + 1

    if max_branch_size < branch_size
      max_branch_size = branch_size
      location = "#{filepath}:#{from_row}"
      longest_branch_code = source_code[(from_row-1)..(to_row-1)].join
    end
  end
end

puts location
puts "longest branch code: (size #{max_branch_size})"
puts "-" * 80
puts longest_branch_code
puts "-" * 80

実行結果

~/Programming/ruby/sandbox ruby get_longest_branch_code.rb
/Users/siman/Programming/ruby/sandbox/sample.rb:9
longest branch code: (size 10)
--------------------------------------------------------------------------------
case n
when 0
  'a'
when 1
  'b'
when 2
  'c'
when 3
  'd'
end
--------------------------------------------------------------------------------

こんな感じで一番長い条件式が取得出来ました。

他にも有名なライブラリで試してみました。

  • active_support (5.1.4)

  • rubocop (0.52.0)

参考サイト

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2