cmdparser 1.0 → 1.1
Sign up to get free protection for your applications and to get access to all the features.
- data/README.md +25 -11
- data/lib/cmdparser.rb +48 -3
- data/lib/cmdparser/version.rb +1 -1
- metadata +1 -1
data/README.md
CHANGED
@@ -1,7 +1,6 @@
|
|
1
1
|
# Cmdparser
|
2
2
|
|
3
|
-
|
4
|
-
|
3
|
+
ruby's command provider
|
5
4
|
## Installation
|
6
5
|
|
7
6
|
Add this line to your application's Gemfile:
|
@@ -20,12 +19,27 @@ Or install it yourself as:
|
|
20
19
|
|
21
20
|
## Usage
|
22
21
|
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
22
|
+
```
|
23
|
+
require 'cmdparser'
|
24
|
+
|
25
|
+
CmdParser.new{
|
26
|
+
on ['help','-h'] do
|
27
|
+
print "help command\n"
|
28
|
+
end
|
29
|
+
on 'server' do
|
30
|
+
end
|
31
|
+
on 'server',['port','-p'] do |port|
|
32
|
+
print "port #{port}\n"
|
33
|
+
end
|
34
|
+
on 'server',['type','-t'] do |type|
|
35
|
+
print "type #{type}\n"
|
36
|
+
end
|
37
|
+
}.invoke
|
38
|
+
# filename : cmd.rb
|
39
|
+
# call : ./cmd.rb server port 80
|
40
|
+
# => port 80\n
|
41
|
+
# call : ./cmd.rb port 80
|
42
|
+
# =>
|
43
|
+
# call : ./cmd.rb server port 80 type http
|
44
|
+
# => port 80\ntype http
|
45
|
+
```
|
data/lib/cmdparser.rb
CHANGED
@@ -1,5 +1,50 @@
|
|
1
|
-
|
1
|
+
class CmdParser
|
2
|
+
|
3
|
+
def initialize &block
|
4
|
+
@procs = {}
|
5
|
+
if block
|
6
|
+
instance_eval &block
|
7
|
+
end
|
8
|
+
self
|
9
|
+
end
|
10
|
+
|
11
|
+
def on declaration=nil,args, &block
|
12
|
+
args = [args] if args.class != [].class
|
13
|
+
block_args = block.parameters
|
14
|
+
proc = { :arg_len => block_args.length, :block => block ,:declaration => declaration}
|
15
|
+
args.each{ |arg| @procs[arg] = proc }
|
16
|
+
end
|
17
|
+
|
18
|
+
def declaration? name
|
19
|
+
@procs.include? name
|
20
|
+
end
|
21
|
+
|
22
|
+
def invoke
|
23
|
+
skip = 0
|
24
|
+
ARGV.each_with_index do |v,i|
|
25
|
+
if skip > 0
|
26
|
+
skip -= 1
|
27
|
+
next
|
28
|
+
end
|
29
|
+
if !declaration? v
|
30
|
+
next
|
31
|
+
end
|
32
|
+
args = []
|
33
|
+
proc = @procs[v]
|
34
|
+
len = proc[:arg_len]
|
35
|
+
if !(!proc[:declaration] || declaration?(proc[:declaration]))
|
36
|
+
next
|
37
|
+
end
|
38
|
+
if len > 0
|
39
|
+
(1..len).each do |n|
|
40
|
+
if n + i < ARGV.length
|
41
|
+
args << ARGV[n + i]
|
42
|
+
skip += 1
|
43
|
+
end
|
44
|
+
end
|
45
|
+
end
|
46
|
+
proc[:block].call *args
|
47
|
+
end
|
48
|
+
end
|
2
49
|
|
3
|
-
module Cmdparser
|
4
|
-
# Your code goes here...
|
5
50
|
end
|
data/lib/cmdparser/version.rb
CHANGED