• Stars
    star
    421
  • Rank 99,157 (Top 3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 9 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A terminal spinner for tasks that have non-deterministic time frame.
tty logo

TTY::Spinner

Gem Version Actions CI Build status Maintainability Coverage Status

A terminal spinner for tasks that have non-deterministic time frame.

TTY::Spinner provides independent spinner component for TTY toolkit.

Available spinner formats demo

Installation

Add this line to your application's Gemfile:

gem "tty-spinner"

And then execute:

$ bundle

Or install it yourself as:

$ gem install tty-spinner

Contents

1. Usage

TTY::Spinner by default uses :classic type of formatter and requires no parameters:

spinner = TTY::Spinner.new

In addition you can provide a message with :spinner token and format type you would like for the spinning display:

spinner = TTY::Spinner.new("[:spinner] Loading ...", format: :pulse_2)

spinner.auto_spin # Automatic animation with default interval

sleep(2) # Perform task

spinner.stop("Done!") # Stop animation

This would produce animation in your terminal:

⎺ Loading ...

And when finished output:

_ Loading ... Done!

Use TTY::Spinner::Multi to synchronize multiple spinners:

spinners = TTY::Spinner::Multi.new("[:spinner] top")

sp1 = spinners.register "[:spinner] one"
# or sp1 = ::TTY::Spinner.new("[:spinner] one")
# spinners.register sp1
sp2 = spinners.register "[:spinner] two"

sp1.auto_spin
sp2.auto_spin

sleep(2) # Perform work

sp1.success
sp2.success

The spinners when done will display:

β”Œ [βœ”] top
β”œβ”€β”€ [βœ”] one
└── [βœ”] two

For more usage examples please see examples directory

2. TTY::Spinner API

2.1 spin

The main workhorse of the spinner is the spin method.

Looping over spin method will animate a given spinner.

loop do
  spinner.spin
end

2.2 auto_spin

To perform automatic spinning animation use auto_spin method like so:

spinner.auto_spin

The speed with which the spinning happens is determined by the :interval parameter. All the spinner formats have their default intervals specified (see).

2.2.1 pause

After calling auto_spin you can pause spinner execution:

spinner.pause

2.2.2 resume

You can continue any paused spinner:

spinner.resume

2.3 run

Use run passing a block with a job that will automatically display spinning animation while the block executes and finish animation when the block terminates. The block yields a spinner instance.

spinner.run do |spinner|
  ...
end

Optionally you can provide a stop message to display when animation is finished.

spinner.run("Done!") do |spinner|
  ...
end

2.4 start

In order to set start time or reuse the same spinner after it has stopped, call start method:

spinner.start

2.5 stop

In order to stop the spinner call stop. This will finish drawing the spinning animation and return to new line.

spinner.stop

You can further pass a message to print when animation is finished.

spinner.stop("Done!")

2.5.1 success

Use success call to stop the spinning animation and replace the spinning symbol with check mark character to indicate successful completion.

spinner = TTY::Spinner.new("[:spinner] Task name")
spinner.success("(successful)")

This will produce:

[βœ”] Task name (successful)

2.5.2 error

Use error call to stop the spinning animation and replace the spinning symbol with cross character to indicate error completion.

spinner = TTY::Spinner.new("[:spinner] Task name")
spinner.error("(error)")

This will produce:

[βœ–] Task name (error)

2.6 update

Use update call to dynamically change label name(s).

Provide an arbitrary token name(s) in the message string, such as :title

spinner = TTY::Spinner.new("[:spinner] :title")

and then pass token name and value:

spinner.update(title: "Downloading file1")

next start animation:

spinner.run { ... }
# => | Downloading file1

Once animation finishes you can kick start another one with a different name:

spinner.update(title: "Downloading file2")
spinner.run { ... }

2.7 reset

In order to reset the spinner to its initial frame do:

spinner.reset

2.8 join

One way to wait while the spinning animates is to join the thread started with start method:

spinner.join

Optionally you can provide timeout:

spinner.join(0.5)

2.9 tty?

The spinner will not write any output if the output stream is not a TTY. You can check this with:

spinner.tty?

2.10 log

To output log messages to the console above a spinner use the log method:

spinner.log("Print this log message to the console")

3. Configuration

There are number of configuration options that can be provided to customise the behaviour of a spinner.

3.1 :format

Use one of the predefined spinner styles by passing the formatting token :format

spinner = TTY::Spinner.new(format: :pulse_2)

All spinner formats that TTY::Spinner accepts are defined in /lib/tty/spinner/formats.rb

If you wish to see all available formats in action run the formats.rb file in examples folder like so:

bundle exec ruby examples/formats.rb

3.2 :frames

If you wish to use custom formatting use the :frames option with either array or string of characters.

spinner = TTY::Spinner.new(frames: [".", "o", "0", "@", "*"])

3.3 :interval

The :interval option accepts integer representing number of Hz units, for instance, frequency of 10 will mean that the spinning animation will be displayed 10 times per second.

spinner = TTY::Spinner.new(interval: 20) # 20 Hz (20 times per second)

3.4 :hide_cursor

Hides cursor when spinning animation performs. Defaults to false.

spinner = TTY::Spinner.new(hide_cursor: true)

3.5 :clear

After spinner is finished clears its output. Defaults to false.

spinner = TTY::Spinner.new(clear: true)

3.6 :success_mark

To change marker indicating successful completion use the :success_mark option:

spinner = TTY::Spinner.new(success_mark: "+")

3.7 :error_mark

To change marker indicating error completion use the :error_mark option:

spinner = TTY::Spinner.new(error_mark: "x")

3.8 :output

The spinner only outputs to a console and when output is redirected to a file or a pipe it does nothing. This is so, for example, your error logs do not overflow with spinner output.

You can change where console output is streamed with :output option:

spinner = TTY::Spinner.new(output: $stdout)

The output stream defaults to stderr.

4. Events

TTY::Spinner emits :done, :success and :error event types when spinner is stopped.

4.1 done

This event is emitted irrespective of the completion method. In order to listen for this event you need to register callback:

spinner.on(:done) { ... }

4.2 success

This event is fired when success call is made. In order to respond to the event, you need to register callback:

spinner.on(:success) { ... }

4.3 error

This event is fired when error completion is called. In order to respond to the event, you need to register callback:

spinner.on(:error) { ... }

5. TTY::Spinner::Multi API

5.1 register

Create and register a TTY::Spinner under the multispinner

new_spinner = multi_spinner.register("[:spinner] Task 1 name", options)
# or
#   spinner = ::TTY::Spinner.new("[:spinner] one")
#   sp1 = multi_spinner.register(spinner)

If no options are given it will use the options given to the multi_spinner when it was initialized to create the new spinner. If options are passed, they will override any options given to the multi spinner.

5.2 auto_spin

To create a top level spinner that tracks activity of all the registered spinners, the multispinner has to have been given a message on initialization:

multi_spinner = TTY::Spinner::Multi.new("[:spinner] Top level spinner")

The top level multi spinner will perform spinning animation automatically when at least one of the registered spinners starts spinning.

If you register spinners without any tasks then you will have to manually control when the multi_spinner finishes by calling stop, success or error (see manual).

Alternatively, you can register spinners with tasks that will automatically animate and finish spinners when respective tasks are done (see async tasks).

The speed with which the spinning happens is determined by the :interval parameter. All the spinner formats have their default intervals specified (see).

5.2.1 manual async

In case when you wish to have full control over multiple spinners, you will need to perform all actions manually.

For example, create a multi spinner that will track status of all registered spinners:

multi_spinner = TTY::Spinner::Multi.new("[:spinner] top")

and then register spinners with their formats:

spinner_1 = spinners.register "[:spinner] one"
spinner_2 = spinners.register "[:spinner] two"

Once registered, you can set spinners running in separate threads:

spinner_1.auto_spin
spinner_2.auto_spin

Finally, you need to stop each spinner manually, in our case we mark the second spinner as failure which in turn will stop the top level multi spinner automatically and mark it as failure:

spinner_1.success
spinner_2.error

The result may look like this:

β”Œ [βœ–] top
β”œβ”€β”€ [βœ”] one
└── [βœ–] two

5.2.2 auto async tasks

In case when you wish to execute async tasks and update individual spinners automatically, in any order, about their task status use #register and pass additional block parameter with the job to be executed.

For example, create a multi spinner that will track status of all registered spinners:

multi_spinner = TTY::Spinner::Multi.new("[:spinner] top")

and then register spinners with their respective tasks:

multi_spinner.register("[:spinner] one") { |sp| sleep(2); sp.success("yes 2") }
multi_spinner.register("[:spinner] two") { |sp| sleep(3); sp.error("no 2") }

Finally, call #auto_spin to kick things off:

multi_spinner.auto_spin

If any of the child spinner stops with error then the top level spinner will be marked as failure.

5.3 stop

In order to stop the multi spinner call stop. This will stop the top level spinner, if it exists, and any sub-spinners still spinning.

multi_spinner.stop

5.3.1 success

Use success call to stop the spinning animation and replace the spinning symbol with a check mark character to indicate successful completion. This will also call #success on any sub-spinners that are still spinning.

multi_spinner.success

5.3.2 error

Use error call to stop the spinning animation and replace the spinning symbol with cross character to indicate error completion. This will also call #error on any sub-spinners that are still spinning.

multi_spinner.error

5.4 :style

In addition to all configuration options you can style multi spinner like so:

multi_spinner = TTY::Spinner::Multi.new("[:spinner] parent", style: {
  top: ". "
  middle: "|-> "
  bottom: "|__ "
})

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/piotrmurach/tty-spinner. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

  1. Fork it ( https://github.com/piotrmurach/tty-spinner/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Code of Conduct

Everyone interacting in the TTY::Spinner project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

Copyright

Copyright (c) 2014 Piotr Murach. See LICENSE for further details.

More Repositories

1

tty

Toolkit for developing sleek command line apps.
Ruby
2,472
star
2

tty-prompt

A beautiful and powerful interactive command line prompt
Ruby
1,418
star
3

github

Ruby interface to GitHub API
Ruby
1,132
star
4

finite_machine

A minimal finite state machine with a straightforward syntax.
Ruby
802
star
5

pastel

Terminal output styling with intuitive and clean API.
Ruby
628
star
6

rspec-benchmark

Performance testing matchers for RSpec
Ruby
584
star
7

tty-progressbar

Display a single or multiple progress bars in the terminal.
Ruby
415
star
8

loaf

Manages and displays breadcrumb trails in Rails app - lean & mean.
Ruby
404
star
9

tty-command

Execute shell commands with pretty output logging and capture stdout, stderr and exit status.
Ruby
397
star
10

tty-markdown

Convert a markdown document or text into a terminal friendly output.
Ruby
303
star
11

tty-logger

A readable, structured and beautiful logging for the terminal
Ruby
291
star
12

github_cli

GitHub on your command line. Use your terminal, not the browser.
Ruby
264
star
13

tty-table

A flexible and intuitive table generator
Ruby
183
star
14

tty-box

Draw various frames and boxes in your terminal window
Ruby
177
star
15

awesome-ruby-cli-apps

A curated list of awesome command-line applications in Ruby.
Ruby
159
star
16

rack-policy

Rack middleware for the EU ePrivacy Directive compliance in Ruby Web Apps
Ruby
147
star
17

tty-pie

Draw pie charts in your terminal window
Ruby
138
star
18

necromancer

Conversion from one object type to another with a bit of black magic.
Ruby
135
star
19

strings

A set of useful functions for transforming strings.
Ruby
127
star
20

coinpare

Compare cryptocurrency trading data across multiple exchanges and blockchains in the comfort of your terminal
Ruby
109
star
21

tty-exit

Terminal exit codes.
Ruby
100
star
22

strings-case

Convert strings between different cases.
Ruby
95
star
23

tty-reader

A set of methods for processing keyboard input in character, line and multiline modes.
Ruby
85
star
24

tty-option

A declarative command-line parser
Ruby
84
star
25

merkle_tree

A merkle tree is a data structure used for efficiently summarizing sets of data, often one-time signatures.
Ruby
83
star
26

tty-screen

Terminal screen detection - cross platform, major ruby interpreters
Ruby
83
star
27

verse

[DEPRECATED] Text transformations
Ruby
71
star
28

tty-cursor

Terminal cursor movement and manipulation of cursor properties such as visibility
Ruby
68
star
29

supervision

Write distributed systems that are resilient and self-heal.
Ruby
66
star
30

tty-file

File manipulation utility methods
Ruby
65
star
31

tty-config

A highly customisable application configuration interface for building terminal tools.
Ruby
61
star
32

benchmark-trend

Measure performance trends of Ruby code
Ruby
59
star
33

tty-font

Terminal fonts
Ruby
58
star
34

lex

Lex is an implementation of lex tool in Ruby.
Ruby
56
star
35

tty-tree

Print directory or structured data in a tree like format
Ruby
56
star
36

strings-truncation

Truncate strings with fullwidth characters and ANSI codes.
Ruby
49
star
37

tty-pager

Terminal output paging - cross-platform, major ruby interpreters
Ruby
39
star
38

tty-color

Terminal color capabilities detection
Ruby
35
star
39

slideck

Present Markdown-powered slide decks in the terminal.
Ruby
34
star
40

strings-inflection

Convert between singular and plural forms of English nouns
Ruby
31
star
41

tty-link

Hyperlinks in your terminal
Ruby
31
star
42

tty-platform

Operating system detection
Ruby
29
star
43

tty-sparkline

Sparkline charts for terminal applications.
Ruby
29
star
44

tty-editor

Opens a file or text in the user's preferred editor
Ruby
27
star
45

communist

Library for mocking CLI calls to external APIs
Ruby
25
star
46

splay_tree

A self-balancing binary tree optimised for fast access to frequently used nodes.
Ruby
24
star
47

equatable

Allows ruby objects to implement equality comparison and inspection methods.
Ruby
24
star
48

minehunter

Terminal mine hunting game.
Ruby
23
star
49

rotation.js

Responsive and mobile enabled jQuery plugin to help create rotating content.
JavaScript
22
star
50

strings-numeral

Express numbers as string numerals
Ruby
20
star
51

strings-ansi

Handle ANSI escape codes in strings
Ruby
19
star
52

benchmark-malloc

Trace memory allocations and collect stats
Ruby
19
star
53

tty-which

Cross-platform implementation of Unix `which` command
Ruby
17
star
54

tty-runner

A command routing tree for terminal applications
Ruby
12
star
55

benchmark-perf

Benchmark execution time and iterations per second
Ruby
12
star
56

impact

Ruby backend for Impact.js framework
Ruby
8
star
57

queen

English language linter to hold your files in high esteem.
Ruby
8
star
58

pastel-cli

CLI tool for intuitive terminal output styling
Ruby
7
star
59

dotfiles

Configuration files for Unix tools
Vim Script
7
star
60

tty-markdown-cli

CLI tool for displaying nicely formatted Markdown documents in the terminal
Ruby
7
star
61

static_deploy

Automate deployment of static websites
Ruby
6
star
62

tenpin

Terminal tenpin bowling game
Ruby
4
star
63

tytus

Helps you manage page titles in your Rails app.
Ruby
3
star
64

tty.github.io

TTY toolkit website.
SCSS
2
star
65

peter-murach.github.com

Personal webpage
JavaScript
2
star
66

wc.rb

A Ruby clone of Unix wc utility.
Ruby
2
star
67

exportable

Rails plugin to ease exporting tasks.
Ruby
1
star
68

capistrano-git-stages

Multistage capistrano git tags
Ruby
1
star
69

tabster

Ruby
1
star
70

leek

Cucumber steps and RSpec expectations for command line apps
Ruby
1
star
71

unicorn.github.io

Website for the github_api and github_cli ruby gems.
CSS
1
star
72

tty-color-cli

CLI tool for terminal color capabilities detection
Ruby
1
star
73

finite_machine.github.io

Website for finite_machine Ruby gem
SCSS
1
star
74

strings-wrapping

Wrap strings with fullwidth characters and ANSI codes
Ruby
1
star