Last Updated: February 25, 2016
·
381
· blazeeboy

Commandline Key Value Storage application

Commander gem is greate, it helped me generate command line application skeleton containing default behaviour like --help option to show help string (it generate it automatically)

try "ruby storage.rb --help"

and -t option to trace errors try "ruby storage.rb -t", and also it parses the command line arguments and options parameters and separated commands as blocks of code with description, examples, and options available.

everything was smooth after generatign the application using "commander init storage.rb", i hade to write my own logic inside commands code blocks.

i highly recommend you try it for your commandline scripts instead of writing yor own solution, just use it to help you, also it contains highline gem for the "ask" method, it help you ask user for input, password, choices...etc.

Gist : https://gist.github.com/9836018

#!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'json'
require 'psych'
require 'commander/import' # gem install commander
program :version, '0.0.1'
program :description, 'Simple Key Value Storage Commandline Script'

FILENAME = 'storage.json'
storage = File.exists?(FILENAME) ? JSON.parse(File.read(FILENAME)) : {}

command :c do |c|
  c.syntax = 'storage c key value'
  c.description = 'create new key with a value in our storage'
  c.example 'store myname key with my name as a value', 'ruby storage c myname emad elsaid hamed'
  c.action do |args, options|
    storage[args[0]] = args[1..-1].join(' ')
    File.write FILENAME, storage.to_json
  end
end

command :r do |c|
  c.syntax = 'storage r key'
  c.description = 'read a key value or all values from storage'
  c.example 'read my name', 'ruby storage r myname'
  c.action do |args, options|
    puts( args[0] ? storage[args[0]] : storage.to_yaml )
  end
end

command :d do |c|
  c.syntax = 'storage d key'
  c.description = 'delete a key from storage'
  c.example 'remove my name from storage', 'ruby storage d myname'
  c.action do |args, options|
    storage.delete args[0]
    File.write FILENAME, storage.to_json
  end
end