Rails rake stats 自定义文件目录代码统计及 UTF-8 编码问题解决

haibor · 2017年11月23日 · 最后由 haibor 回复于 2017年12月01日 · 3594 次阅读

1、修改文件 C:\Ruby22-x64\lib\ruby\gems\2.2.0\gems\railties-4.2.3\lib\rails\tasks\statistics.rake,增加自定义统计代码的目录。

TATS_DIRECTORIES = [
  %w(Controllers        app/controllers),
  %w(Helpers            app/helpers),
  %w(Jobs               app/jobs),
  %w(Models             app/models),
  %w(Mailers            app/mailers),
  %w(Javascripts        app/assets/javascripts),
  %w(Libraries          lib/),
  %w(APIs               app/apis),
  %w(Controller\ tests  test/controllers),
  %w(Helper\ tests      test/helpers),
  %w(Model\ tests       test/models),
  %w(Mailer\ tests      test/mailers),
  %w(Job\ tests      test/jobs),
  %w(Integration\ tests test/integration),
  %w(Functional\ tests\ (old)  test/functional),
  %w(Unit\ tests \ (old)       test/unit)
].collect do |name, dir|
  [ name, "#{File.dirname(Rake.application.rakefile_location)}/#{dir}" ]
end.select { |name, dir| File.directory?(dir) }

desc "Report code statistics (KLOCs, etc) from the application or engine"
task :stats do
  require 'rails/code_statistics'
  # 此处增加自定义代码统计的目录,增加了public目录下的html目录
   ::STATS_DIRECTORIES << ["html", "public"]
   #::STATS_DIRECTORIES << ["Services", "app/services"]
  CodeStatistics.new(*STATS_DIRECTORIES).to_s
end

2、某些文件中有 UTF-8 编码的异常问题。运行 rake stats 显示异常。

D:\nfvo>rake stats

rake aborted! ArgumentError: invalid byte sequence in UTF-8

处理方法:

修改文件:C:\Ruby22-x64\lib\ruby\gems\2.2.0\gems\railties-4.2.3\lib\rails\code_statistics_calculator.rb 中的 增加异常处理。

def add_by_file_path(file_path)
    File.open(file_path) do |f|
      self.add_by_io(f, file_type(file_path))
    end
    #此处增加以下两句处理UTF-8异常的代码
    rescue Exception => e
    puts "Exception raised while processing: #{file_path}: #{e.message}"
  end

最终 rake stats 的正常显示为: D:\oss>rake stats

需要 登录 后方可回复, 如果你还没有账号请 注册新账号