Idapted TechTeam Rotating Header Image

Ruby Design Patten — Command patten

Share a design patten: Command patten. Migration in Ruby On Rails is a good example of Command patten.
Bellow is code about how to create a Command patten in Ruby.

The code bellow defined CreateFile and CopyFile two classes, use Command patten and Composite patten log requests, and support undoable operations.

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
class Command
  attr_reader :description
 
  def initialize(description)
    @description = description
  end
 
  def execute
  end
end

class CreateFile < Command
  def initialize(file_name)
    super("create file: #{file_name}")
  end
 
  def execute
    puts "creating file"
  end
 
  def unexecute
    puts "deleting created file"
  end
end

class CopyFile < Command
  def initialize(file_name)
    super("copy file: #{file_name}")
  end
 
  def execute
    puts "copying file"
  end
 
  def unexecute
    puts "deleting copied file"
  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.reverse.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("file"))
cmds.add_command(CopyFile.new("file"))
puts "description".ljust(60, "=")
puts cmds.description

puts "execute".ljust(60, "=")
cmds.execute

puts "unexecute".ljust(60, "=")
cmds.unexecute