I would like to write a Ruby program that is basically a shell with custom commands. This means that after calling "ruby app.rb" the user will enter a shell which supports special commands that I wrote.
I used loop do ... end to create a basic loop that processes user input. I also used an array of strings to store all available commands, and a hash table with help messages for each available command. But this is very cumbersome.
I would like to know how to elegantly define custom commands with flags, some of which are mandatory (e.g. create -f "~/file.txt" --READONLY -v). Not only that, I need the "help" command of my shell to output info about every single custom command, including flags, AND to have a "menu" command that lists every available command. As a last resort, I thought of simply creating a bunch of .rb files for every command and then using OptionParser for flags and arguments, since I know of no way to make OptionParser work with functions instead of files.
This is what I came up with so far:
class Shell
@@input = ""
# List of all commands
@@commands = [
"help",
"exit"
]
# Help messages associated with commands
@@help_strings = Hash[
"help" => "Outputs this info.",
"exit" => "Closes the program."
]
def self.start
# bash clear screen command
system("clear")
loop do
print (">> ")
input = gets.chomp
case input
when "help"
for com in @@commands
puts("#{com}: #{@@help_strings[com]}")
end
when "exit"
# bash clear screen command
system("clear")
break
else
puts("Unknown commands: #{input}")
puts("Type \"help\" for more info.")
end
end
end
end
@@) and instead use constants here. Even better, since this apparently can't be instantiated, use amoduleinstead of aclass, or move all this to an instance method likeShell.new.start.@@inputshouldn't exist.inputis already a local variable in thestartblock, and it's not related to@@inputin any way.