Skip to main content
search
0
codingRuby&Rails

Ruby実行中プログレスバーを表示するgem「ruby-progressbar」

By 2022年3月31日No Comments

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

OptionDefaultDescription
:titleProgressThe title of the progress bar.
:total100The total number of the items that can be completed.
:starting_at0The 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_markempty spaceThe 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.
:lengthfull width if possible, otherwise 80The preferred width of the entire progress bar including any format options.
:output$stdoutAll output will be sent to this object. Can be any object which responds to “.print” “.flush” “.tty?” “.puts”.
:smoothing0.1See Smoothing Out Estimated Time Jitters.
:throttle_rate0.01See 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

参考URL:https://qiita.com/tbpgr/items/825a84120c3e9e53a7b2