Class: Safebox::CLI
- Inherits:
-
Object
- Object
- Safebox::CLI
- Defined in:
- lib/safebox/cli.rb
Instance Method Summary collapse
- #delete(*args) ⇒ Object
- #file ⇒ Object
- #get(key) ⇒ Object
-
#initialize(defaults = {}) ⇒ CLI
constructor
A new instance of CLI.
- #list ⇒ Object
- #run(*argv) ⇒ Object
- #set(*args) ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(defaults = {}) ⇒ CLI
Returns a new instance of CLI.
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 36 37 38 39 |
# File 'lib/safebox/cli.rb', line 8 def initialize(defaults = {}) @options = defaults @commands = { list: [nil, "Lists all keys and their values"], get: ["KEY", "Prints the given key to STDOUT"], set: ["KEY=VALUE [KEY=VALUE...]", "Sets the value of the given keys"], delete: ["KEY [KEY...]", "Delete the given keys"], } indent = " " * 4 @parser = OptionParser.new do |opts| opts. = "Usage: safebox [options] [command]" opts.version = Safebox::VERSION opts.separator "" opts.separator "Commands:" width = 33 @commands.each do |command, (arguments, description)| command = "#{command} #{arguments}" opts.separator indent + command.ljust(width) + description end opts.separator "" opts.separator "Common options:" opts.separator indent + "-h, --help" opts.separator indent + "-v, --version" opts.on("-f", "--file [SAFEBOX]", "Safebox file (safe.box)") do |file| @options[:file] = file end end end |
Instance Method Details
#delete(*args) ⇒ Object
70 71 72 73 74 75 76 77 |
# File 'lib/safebox/cli.rb', line 70 def delete(*args) did_change = false args.each do |key| did_change = true if hash.has_key?(key) hash.delete(key) end safebox.write(hash) if did_change end |
#file ⇒ Object
83 84 85 |
# File 'lib/safebox/cli.rb', line 83 def file @options[:file] or "./safe.box" end |
#get(key) ⇒ Object
56 57 58 59 |
# File 'lib/safebox/cli.rb', line 56 def get(key) $stdout.print hash.fetch(key) { Kernel.abort "no such key: #{key}" } $stdout.puts if $stdout.tty? end |
#list ⇒ Object
50 51 52 53 54 |
# File 'lib/safebox/cli.rb', line 50 def list hash.each do |key, value| $stdout.puts "#{key}=#{value}" end end |
#run(*argv) ⇒ Object
41 42 43 44 45 46 47 48 |
# File 'lib/safebox/cli.rb', line 41 def run(*argv) command, *args = @parser.parse!(argv) if command and @commands.include?(command.to_sym) public_send(command, *args) true end end |
#set(*args) ⇒ Object
61 62 63 64 65 66 67 68 |
# File 'lib/safebox/cli.rb', line 61 def set(*args) args.each do |arg| key, value = arg.split("=", 2) hash[key] = value end safebox.write(hash) end |
#to_s ⇒ Object
79 80 81 |
# File 'lib/safebox/cli.rb', line 79 def to_s @parser.to_s end |