LoginSignup
0
0

More than 3 years have passed since last update.

rbenvで環境切り替えたとき用にRubyのrequire一覧を出すTool

Posted at

TL;DR (長い三行で)

rbenvでRubyのVersionを入れ替えたときに,Gemが入ってなくてrequire xxxでエラーが出る
・エラー出るたびにgem install xxxするのしんどい
・いまあるrequire xxxを全部リストアップするToolつくるで

できたもの

gen_require_lines.rb
#! /usr/bin/env ruby
#! ruby
# ENCODING: UTF-8

#### SEARCH ALL .RB FILES UNDER PWD
def get_rb_files(root_dir)
  rb_files = []

  Dir.entries(root_dir).each { |entry|
    next if entry.start_with?('.')

    entry_full_path = "#{root_dir}/#{entry}"

    case File.ftype(entry_full_path)
      when 'directory'
        sub_results = get_rb_files(entry_full_path)
        rb_files += sub_results

      when 'file'
        if entry.end_with?('.rb')
          rb_files << entry_full_path
        end

      else
        # NOP.
    end
  }

  return rb_files
end

total_rb_files = get_rb_files(Dir.pwd)
total_rb_files.sort!

#### PARSE EACH .RB
require_lines = []
total_rb_files.each { |rb|
  File.open(rb) { |file|
    file.each_line { |line|
      line.force_encoding('UTF-8')
      line.chomp!
      line.scrub!
      line.strip!

      if !line.match(/^require\s/).nil?
        require_lines << line
      end
    }
  }
}
require_lines.uniq!
require_lines.sort!

#### OUTPUT
require_lines.each { |line|
  puts line
}

まとめると

こんなTool作るハメになる前に,外部依存関係はちゃんと管理しましょう.

---///

0
0
3

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
0
0