Class: Spinner

Inherits:
Object
  • Object
show all
Defined in:
lib/spinner.rb

Constant Summary collapse

VERSION =
"0.3.0".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*tasks) ⇒ Spinner

Returns a new instance of Spinner.



9
10
11
12
13
# File 'lib/spinner.rb', line 9

def initialize(*tasks)
  @queue = tasks
  @width = 0
  @chars = %w{ | / - \\ }
end

Instance Attribute Details

#queueObject (readonly)

Returns the value of attribute queue.



7
8
9
# File 'lib/spinner.rb', line 7

def queue
  @queue
end

Instance Method Details

#spin!Object

Starts executing the queued tasks.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/spinner.rb', line 44

def spin!
  # Handle no tasks in the queue.
  return unless @queue.any?

  # Mark the current time in order to calculate the total duration.
  start_time = Time.now

  # Pluralize the number of tasks in the queue.
  task_counter = "#{@queue.size} task" << (@queue.size == 1 ? '' : 's')

  # Update the print width.
  @width = (@width + (@queue.size.to_s.length + 2) * 2) + 1

  # Execute each task in sequence.
  @queue.each_with_index do |task, i|
    run_task(task, i+1)
  end

  # Reset this spinner instance so that it can be reused.
  reset!

  # Mark the completion time and calculate the duration.
  end_time = Time.now
  time_taken = distance_of_time_in_words(start_time, end_time)

  # Print the completion message.
  print("Done! #{task_counter} completed in #{time_taken} :-)\n")
end

#task(title = nil, task_name = nil, &block) ⇒ Object

Injects a new task into the queue.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/spinner.rb', line 16

def task(title=nil, task_name=nil, &block)
  # Handle no task being supplied.
  return @queue.map(&:title) unless block_given? || task_name

  # Set default title.
  title = 'Executing' unless title

  # Tasks can be given a block to evaluate or
  # a rake task name to invoke.
  if block_given?
    task_block = block
  elsif task_name
    task_block = Rake::Task[task_name]
  end

  # Inject the task into the queue.
  @queue << [ title, task_block ]

  # Amend the output width if necessary.
  if @width < title.length
    @width = title.length
  end

  # Return the new list of tasks.
  @queue.map(&:first)
end