Class: Achoo::UI::MonthChooser

Inherits:
Object
  • Object
show all
Defined in:
lib/achoo/ui/month_chooser.rb

Instance Method Summary collapse

Instance Method Details

#chooseObject



8
9
10
11
12
13
14
15
16
17
# File 'lib/achoo/ui/month_chooser.rb', line 8

def choose
  loop do
    answer = Term::ask "Period ([#{one_month_ago}] | YYYYMM)"
    begin
      return handle_answer(answer)
    rescue ArgumentError => e
      puts e
    end
  end
end

#handle_answer(answer) ⇒ Object



19
20
21
22
23
24
# File 'lib/achoo/ui/month_chooser.rb', line 19

def handle_answer(answer)
  period = !answer || answer.empty? ? one_month_ago : answer
  period =~ /\A \d{4} (?: 0\d | 1[0-2]) \z/x \
  or raise ArgumentError.new('Invalid month')
  period
end

#one_month_agoObject



26
27
28
29
30
31
32
33
34
35
# File 'lib/achoo/ui/month_chooser.rb', line 26

def one_month_ago
  now   = Time.now
  year  = now.year
  
  # Use -2 + 1 to shift range from 0-11 to 1-12 
  month = (now.month - 2)%12 + 1
  year -= 1 if month > now.month
  
  sprintf "%d%02d", year, month
end