Class: Ddate::CLI

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

Constant Summary collapse

FORMAT_RE =
%r{\A\+(.*)\z}
OPTION_RE =
%r{\A\-(\S)\z}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCLI

Returns a new instance of CLI.



11
12
13
# File 'lib/ddate/cli.rb', line 11

def initialize
  self.formatter = Ddate::Formatter.new
end

Instance Attribute Details

#formatterObject

Returns the value of attribute formatter.



9
10
11
# File 'lib/ddate/cli.rb', line 9

def formatter
  @formatter
end

Instance Method Details

#handle_options(option) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ddate/cli.rb', line 50

def handle_options(option)
  case option.downcase
  when 'h'
    Ddate::USAGE
  when 'f'
    Ddate::FORMATTER_USAGE
  when 'v'
    Ddate::VERSION_STRING
  else
    raise DdateException.new "unknown option: #{option}"
  end
end

#run(args) ⇒ Object



15
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
42
43
44
45
46
47
48
# File 'lib/ddate/cli.rb', line 15

def run(args)

  num_args = args.count
  case num_args
  when 0
    # no arguments, run with today's date
    today = Date.today
    year, month, day = today.year, today.month, today.day
  when 1
    arg = args.shift.to_s
    if (help = arg.to_s.match(OPTION_RE) {|m| handle_options($1)})
      return help
    elsif (self.formatter = arg.to_s.match(FORMAT_RE) {|m| Ddate::Formatter.new($1)})
      # do nothing, drop through
    else
      raise DdateException.new "not enough arguments"
    end
    today = Date.today
    year, month, day = today.year, today.month, today.day
  when 3
    year, month, day = args.map { |i| Integer(i) }
  when 4
    fmt = args.shift.to_s
    if (self.formatter = fmt.match(FORMAT_RE) {|m| Ddate::Formatter.new($1)})
      # do nothing, drop through
    else
      raise DdateException.new "first argument when 4 given must be a format"
    end
    year, month, day = args.map { |i| Integer(i) }
  else
    raise DdateException.new "wrong number of arguments"
  end
  Ddate::Converter.new(year, month, day, formatter).to_s
end