Module: ApplixHash::ClassMethods

Defined in:
lib/applix/hash.rb

Instance Method Summary collapse

Instance Method Details

#from_argv(argv, opts = {}) ⇒ Object

#from_argv builds hash from ARGV like argument vector according to following examples:

'-f'                  --> { :f      => true }
'--flag'              --> { :flag   => true }
'--flag:false'        --> { :flag   => false }
'--flag=false'        --> { :flag   => 'false' }
'--option=value'      --> { :option => "value" }
'--int=1'             --> { :int    => "1" }
'--float=2.3'         --> { :float  => "2.3" }
'--float:2.3'         --> { :float  => 2.3 }
'--txt="foo bar"'     --> { :txt    => "foo bar" }
'--txt:\'"foo bar"\'' --> { :txt    => "foo bar" }
'--txt:%w{foo bar}'   --> { :txt    => ["foo", "bar"] }
'--now:Time.now'      --> { :now    => #<Date: 3588595/2,0,2299161> }

remaining arguments(non flag/options) are inserted as [:args]. eg:

Hash.from_argv %w(--foo --bar=loo 123 now)

becomes

{ :foo => true, :bar => 'loo', :args => ["123", "now"] }


25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/applix/hash.rb', line 25

def from_argv argv, opts = {}
  args, h = argv.clone, {}
  while arg = args.first
    key, val = ApplixHash.parse(arg)
    break unless key
    h[key] = val
    args.shift
  end
  #[args, h]
  h[:args] = args
  h
end