Die Programmiersprache Ruby

Blog| Forum| Wiki  

Als kleine Erweiterung zur Plattformbestimmung hier ein Schema für die Möglichkeit Plattformunabhängig Kommandos auszuführen.


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
class Cmds
  @@RUBY_PLATFORM =
  case RUBY_PLATFORM.downcase
    when /linux|bsd|solaris|hpux|darwin/
      :unix
    when /mswin32|mingw32|bccwin32/
      :windows
    when /cygwin/
      :cygwin
    when /java/
      :java
    else
      :other
  end

  @@cmds = {
    :windows =>
    { :pwd => 'chdir',
      :cat => 'type <p1>' },
    :unix =>
    { :pwd => 'pwd',
      :cat => 'cat <p1>' },
    :cygwin =>
    {},
    :java =>
    {}
  }

  def self.method_missing(cmd, *par)
    unless @@cmds[@@RUBY_PLATFORM][cmd]
      raise "Command '#{cmd.to_s}' for platform '#{@@RUBY_PLATFORM.to_s}' not available"
    end
    `#{@@cmds[@@RUBY_PLATFORM][cmd].gsub(/<p(\d+)>/){par[Integer($1)-1]}}` 
  end
end


Anwendung, auch mit Parametern, anhand eines kleinen Beispiels zum Ausprobieren.


1
2
3
4
puts Cmds.pwd
cont = Cmds.cat 'huhu.txt'
p cont
puts Cmds.otto