rubysh.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. require 'open3'
  2. class Cmd
  3. def initialize(*args)
  4. @stdin = ""
  5. @cmd = ""
  6. args.flatten.each do |a|
  7. @cmd = @cmd + a.to_s + " "
  8. end
  9. @cmd.strip!
  10. end
  11. def +@()
  12. return Open3.capture2(@cmd,:stdin_data=>@stdin)[0];
  13. end
  14. def -@()
  15. system("echo \"#{@stdin}\" | #{@cmd}")
  16. end
  17. def to_s()
  18. return @cmd
  19. end
  20. class << self
  21. public :define_method
  22. end
  23. attr_writer :stdin
  24. end
  25. class String
  26. class << self
  27. public :define_method
  28. end
  29. end
  30. $programs = {}
  31. ENV["PATH"].split(File::PATH_SEPARATOR).each do |dir|
  32. if Dir.exist?(dir)
  33. Dir.entries(dir).each do |prog|
  34. if File.executable?(File.join(dir,prog))
  35. pname = prog.sub(/\.exe/,"")
  36. $programs[pname] = prog
  37. Cmd.define_method(pname) do |*args|
  38. @cmd = @cmd + " | " + $programs[pname]
  39. args.flatten.each do |a|
  40. @cmd = @cmd + " " + a.to_s
  41. end
  42. return self
  43. end
  44. if not "".respond_to?(pname)
  45. String.define_method(pname) do |*args|
  46. newCommand = Cmd.new($programs[pname], args)
  47. newCommand.stdin = self
  48. return newCommand
  49. end
  50. end
  51. end
  52. end
  53. end
  54. end
  55. module Rubysh
  56. def method_missing(m,*args)
  57. if $programs.has_key?(m.to_s)
  58. return Cmd.new(m,args)
  59. else
  60. throw NameError
  61. end
  62. end
  63. end
  64. extend Rubysh