最近Rubyを勉強してます(遅いって?)。Rubyのソースを見る度に、なぜか受け付け難い雰囲気を感じていたのですが、最近会う人会う人がRuby(on Rails)で開発しているよ的な発言をされているので、やむにやまれず触発された感じです。
言語学習はやっぱりコード書かなきゃと思いましたので、ここに晒す次第です。あまりデザインパターンに意味はありません。
クラス図
CommandExecutor.rb
class CommandExecutor
def initialize
@commands = Array.new
end
def setCommand cmd
@commands << cmd
end
def execute
@commands.each do |cmd|
cmd.execute
end
end
end
AbstractCommand.rb
class AbstractCommand
def initialize
@option = '';
@command = '';
end
def execute
%x{@command};
end
def setOption opt
@option = opt
end
end
CurrentDirCommand.rb
require 'AbstractCommand.rb'
class CurrentDirCommand < AbstractCommand
def initialize
@command = 'pwd';
end
def execute
STDOUT << %x{#{@command}}
end
end
ListCommand.rb
require 'AbstractCommand.rb'
class ListCommand < AbstractCommand
def initialize
@command = 'ls';
end
def execute
if @option.nil? then
cmd = @command
else
cmd = @command + @option
end
result = %x{#{cmd}}.split(/\n/)
STDOUT << result.join("\n") + "\n"
end
end
MakeDirCommand.rb
require 'AbstractCommand.rb'
class MakeDirCommand < AbstractCommand
def initialize
@command = 'mkdir';
end
def execute
if @option.nil? then
cmd = @command
else
cmd = @command + @option
end
STDOUT << %x{#{cmd}}
end
end
main.rb
#!/usr/bin/ruby
require 'CommandExecutor'
require 'ListCommand'
require 'CurrentDirCommand'
require 'MakeDirCommand'
# コマンド実行オブジェクトを new
executor = CommandExecutor.new
# pwd コマンド追加
pwd = CurrentDirCommand.new
executor.setCommand pwd
# lsコマンド追加
ls = ListCommand.new
ls.setOption ' -lk'
executor.setCommand ls
# mkdir コマンド追加
mkdir = MakeDirCommand.new
mkdir.setOption ' tmp'
executor.setCommand mkdir
# 全部実行
executor.execute
exit
呼び出し制限がJavaとは異なっていて、いまいち理解できてません。
でも細かいとこですが、括弧やセミコロン省略できるだけでも、よりプログラムの本質に集中できるというかタイピング数が少なくなるせいか、生産性は高いかもしれません。
どなたかこのソースに突っ込んでください。