Class: TwDo

Inherits:
Object
  • Object
show all
Defined in:
lib/twdo.rb,
lib/twdo/api.rb

Defined Under Namespace

Classes: API, Error

Constant Summary collapse

MAX_CHAR =
119
MUST =
''
DONE =
''
SEPARATOR =
''

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#apiObject

Returns the value of attribute api.



12
13
14
# File 'lib/twdo.rb', line 12

def api
  @api
end

Class Method Details

.operation(name, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/twdo.rb', line 28

def self.operation(name, &block)
  define_method name do |arg|
    task = nil
    if arg.is_a? String
      if !list.assoc(arg)
        raise Error, "task '#{arg}' does not exist."
      end
      task = list.assoc(arg)
    elsif arg.is_a? Integer
      if !list[arg]
        raise Error, "task #{arg} does not exist."
      end
      task = list[arg]
    end
    block.call(task, list)
  end
end

Instance Method Details

#add(name) ⇒ Object



50
51
52
53
54
55
56
57
58
# File 'lib/twdo.rb', line 50

def add(name)
    if name =~ /^\d+$/
        raise Error, 'task name can not be number.'
    end
    if list.assoc(name)
        raise Error, 'task already exists.'
    end
    list << [name]
end

#init(names) ⇒ Object



60
61
62
# File 'lib/twdo.rb', line 60

def init(names)
    @list = names.map {|n| [n] }
end

#listObject



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/twdo.rb', line 14

def list
  return @list if @list
  lines = api.get.split(SEPARATOR)
  @list = lines.map do |l|
    if l =~ /^(#{MUST}|#{DONE})(.*)$/u
      task = [$2]
      task << :done if $1 == DONE
      task
    else
      raise Error, 'invalid format. please init your TwDo list.'
    end
  end
end

#update!Object



64
65
66
67
68
69
70
71
# File 'lib/twdo.rb', line 64

def update!
    desc = list.map {|item|
        prefix = item[1] == :done ? DONE : MUST
        prefix + item[0]
    }.join(SEPARATOR)
    raise 'Over max chars.' if desc.split(//u).size > MAX_CHAR
    api.set(desc)
end