-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.rb
87 lines (86 loc) · 1.79 KB
/
command.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
require 'fileutils'
class Command
attr_reader :description
def initialize(description)
@description = description
end
def execute
end
end
class CreateFile < Command
def initialize(path, contents)
super("Create file: #{path}")
@path, @contents = path, contents
end
def execute
f = File.open(@path, 'w')
f.write(@contents)
f.close
end
def unexecute
File.delete(@path) if File.exists?(@path)
end
end
class DeleteFile < Command
def initialize(path)
super("Delete file: #{path}")
@path = path
end
def execute
if File.exists?(@path)
@contents = File.read(@path)
File.delete(@path)
end
end
def unexecute
f = File.open(@path, 'w')
f.write(@contents)
f.close
end
end
class CopyFile < Command
include FileUtils
def initialize(source, target)
super("Copy #{source} to #{target}")
@source, @target = source, target
end
def execute
if File.exists?(@source)
@contents = File.read(@source)
FileUtils.copy(@source, @target)
end
end
def unexecute
File.delete(@target) if File.exists?(@target)
unless File.exists?(@source)
f = File.open(@source, 'w')
f.write(@contents)
f.close
end
end
end
class CompositeCommand < Command
def initialize
@commands = []
end
def add_command(cmd)
@commands << cmd
end
def execute
@commands.each {|cmd| cmd.execute}
end
def unexecute
@commands.each {|cmd| cmd.unexecute}
end
def description
description = ''
@commands.each {|cmd| description += cmd.description + "\n"}
description
end
end
cmds = CompositeCommand.new
cmds.add_command(CreateFile.new('in.txt', "hello world\n"))
cmds.add_command(CopyFile.new('in.txt', 'out.txt'))
cmds.add_command(DeleteFile.new('in.txt'))
cmds.execute
cmds.unexecute