class SimpleShell
A very simple shell operations implementation
Synopsis¶ ↑
shell = SimpleShell.new res = shell.ls puts res.out puts res.err puts res.S? (as $? wont work :->) commands = shell.in("/other/path") do |sh| sh.ls sh.rm "-r", "bar" end puts commands.first.out
Handling stdout and stderr¶ ↑
shell = SimpleShell.new shell.stdout_handler = ->(line) { do_something(line) } shell.do("./long_running.sh")
Off course the same goes for “‘shell.stderr_handler“`
Attributes
base[R]
commands[R]
env[R]
stderr_handler[RW]
stdout_handler[RW]
Public Class Methods
new(base=Dir.pwd, env={})
click to toggle source
Create a new shell instance. This is tied to a base dir, which defaults to Dir.pwd
SimpleShell.new SimpleShell.new("/path/to/base")
# File lib/simple_shell.rb, line 48 def initialize(base=Dir.pwd, env={}) if base.is_a?(Hash) env = base base = Dir.pwd end @base = base @env = env @commands = [] end
noisy()
click to toggle source
# File lib/simple_shell.rb, line 34 def self.noisy @noisy ||= false end
noisy=(noise)
click to toggle source
# File lib/simple_shell.rb, line 38 def self.noisy=(noise) @noisy = noise end
Public Instance Methods
S?()
click to toggle source
the S? of the last command
# File lib/simple_shell.rb, line 103 def S? @commands.last.S? end
in(dir) { |shell| ... }
click to toggle source
open up a sub shell at another directory
shell.in("/path/to/other") do |sub_shell| sub_shell.system("ls") sub_shell.in("/path/to/third") do |sub_sub_shell| ... end
# File lib/simple_shell.rb, line 67 def in(dir, &block) dir = File.join(@base, dir) if !File.exists?(dir) || dir !~ /^\// shell = SimpleShell.new(dir, @env) yield shell return shell.commands end
method_missing(name, *args, &block)
click to toggle source
funkyness for neat little shell access
shell.ls # = shell.system("ls") shell.rm %w(-rf foo/) # = shell.system("rm", "-rf", "foo/")
Calls superclass method
# File lib/simple_shell.rb, line 112 def method_missing(name, *args, &block) super rescue NoMethodError => e if args[0].is_a? Array args = args[0] end self.do(name.to_s, *args, &block) end
system(*args, &block)
click to toggle source
perform a command on the shell
shell.system("ls") shell.do("ls") shell.command("ls")
It is expected that arguments are provided as an array for security/safety purposes:
shell.system("rm", "-r", "-f", "foo/")
Returns a Command
instance
# File lib/simple_shell.rb, line 88 def system(*args, &block) command = nil Dir.chdir(@base) do command = Command.new(self) command.execute(*args, &block) end @commands << command return command end