Class: Fatty::Counter

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

Overview

Counter accumulates and otherwise managed a numeric prefix count (e.g., "12").

Intended usage: counter.push_digit(1) counter.push_digit(2) n = counter.consume(default: 1) # => 12 (and clears)

Constant Summary collapse

MAX_DIGITS =
6

Instance Method Summary collapse

Constructor Details

#initializeCounter

Returns a new instance of Counter.



15
16
17
18
# File 'lib/fatty/counter.rb', line 15

def initialize
  @digits = +""
  @replace_next = false
end

Instance Method Details

#active?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/fatty/counter.rb', line 24

def active?
  !@digits.empty?
end

#clear!Object



28
29
30
31
32
# File 'lib/fatty/counter.rb', line 28

def clear!
  @digits.clear
  @replace_next = false
  self
end

#consume(default: nil) ⇒ Object



71
72
73
74
75
76
77
78
79
# File 'lib/fatty/counter.rb', line 71

def consume(default: nil)
  n = value
  if n.nil?
    default
  else
    clear!
    n
  end
end

#digitsObject



34
35
36
# File 'lib/fatty/counter.rb', line 34

def digits
  @digits.dup
end

#push_digit(n) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/fatty/counter.rb', line 38

def push_digit(n)
  if @replace_next
    @digits.clear
    @replace_next = false
  end
  if @digits.length < MAX_DIGITS
    @digits << n.to_i.to_s
  end
  self
end

#set(n) ⇒ Object



49
50
51
52
53
# File 'lib/fatty/counter.rb', line 49

def set(n)
  @digits = n.to_i.to_s
  @replace_next = false
  self
end

#to_sObject



20
21
22
# File 'lib/fatty/counter.rb', line 20

def to_s
  "Counter: #{@digits}; #{@replace_next}"
end

#universal_argument!Object



55
56
57
58
59
60
61
62
63
# File 'lib/fatty/counter.rb', line 55

def universal_argument!
  if active?
    set(value * 4)
  else
    set(4)
    @replace_next = true # next digit replaces the "4"
  end
  self
end

#valueObject



65
66
67
68
69
# File 'lib/fatty/counter.rb', line 65

def value
  if active?
    @digits.to_i
  end
end