RailsアプリケーションのModelクラスのコードにDBのテーブルで定義されているカラムの情報を追加してくれる便利なGemがあります。
ソースコードに書いてしまうとDRYでないので、必要な時に計算する方法を考えてみます。
rake taskとして実装すると、railsコマンドとして実行できてかっこいいのではないでしょうか? 次のイメージです。
~ bin/rails model:annotate[computer] id integer user_name string maker string memory string release_year integer created_at datetime updated_at datetime
実装はこんな感じです。
namespace :model do task :annotate, [:name] => [:environment] do |_, args| Object.const_get(args[:name].capitalize).columns.each do |c| printf "%20s %10s \n", c.name, c.type end end end
lib/tasks/model.rake
として保存します。
残念な点は実行時間の長さです。 実行するたびにRailsアプリケーションを全部読み込むので、小さなRailsアプリケーションでも実行に1秒ぐらい掛かります。
参考
- ruby - How to pass command line arguments to a rake task - Stack Overflow
- How to convert a string to a constant in Ruby? - Stack Overflow
- ActiveRecordからカラムの型情報を得る - @ledsun blog
- ruby - Nicely formatting output to console, specifying number of tabs - Stack Overflow
- Kernel.#format (Ruby 3.0.0 リファレンスマニュアル)