
Rubyに動いてもらう時に簡単に値を返すだけのものであれば実行即完了となるので何も気にならなかったけれど、そこそこ時間のかかる作業をしてもらうときに実行したあとにターミナル(黒い画面のやつ)ではなんの表示もない(作ることもできるが、いちいちそのために考えるの面倒)と、「うごいてる?」と不安になったり今どのあたりまで進んでいるかなどもわからないので他の作業をするにしても時間がかかるものだと思っていても結果できてないとか、基本エラーが起きて修正していくつもりでいるので心許ない。
そこでよくターミナルのインストールやアップデートの時に表示される今進んでまっせ。という点滅やプログレスバーのようなアニメーションがあればなとおもって探したところ設定の簡単そうなgemがあったのでメモ。
Ruby/ProgressBar
https://github.com/jfelchner/ruby-progressbar
wiki
https://github.com/jfelchner/ruby-progressbar/wiki
インストール
gem install ruby-progressbar
スクリプトに添付
require 'ruby-progressbar'
若しくはGemfileに入れる場合
gem 'ruby-progressbar'
使い方の基本
progressbar = ProgressBar.create
カスタム
自分が試した方法
デフォルトの設定ではtotalが100に設定してある。
100以上の場合や数がわからない時にtotal: nilにすることで進捗率はわからないけれど、うねうねとうごいてまっせというのがわかる。
ProgressBar.create(:starting_at => 20, :total => nil)
配列を繰り返し実行する場合に100以上でもtotalに 配列.size で個数を渡せばうまいことバーを合わせてくれるので進捗もわかる。
ProgressBar.create(:total => 配列.size )
ちなみにそのtotalがデフォルトのままで100以上の操作をすると繰り返し
「WARNING: Your progress bar is currently at 100 out of 100 and cannot be incremented. In v2.0.0 this will become a ProgressBar::InvalidProgressError.」
と警告が表示されてしまうので注意。
他にも好みの設定がいろいろできるようなので今後も試してみたい。
カスタマイズ方法URL:https://github.com/jfelchner/ruby-progressbar/wiki/Options
Option | Default | Description |
---|---|---|
:title | Progress | The title of the progress bar. |
:total | 100 | The total number of the items that can be completed. |
:starting_at | 0 | The number of items that should be considered completed when the bar first starts. This is also the default number that the bar will be set to if “#reset” is called. |
:progress_mark | = | The mark which indicates the amount of progress that has been made. |
:remainder_mark | empty space | The mark which indicates the remaining amount of progress to be made. |
:format | %t: |%B| | The format string which determines how the bar is displayed. See Formatting. |
:length | full width if possible, otherwise 80 | The preferred width of the entire progress bar including any format options. |
:output | $stdout | All output will be sent to this object. Can be any object which responds to “.print” “.flush” “.tty?” “.puts”. |
:smoothing | 0.1 | See Smoothing Out Estimated Time Jitters. |
:throttle_rate | 0.01 | See Throttling. |
:unknown_progress_animation_steps | [‘=—‘, ‘-=–‘, ‘–=-‘, ‘—=’] | The graphical elements used to cycle when progress is changed but the total amount of items being processed is unknown. See Unknown Progress |