option_initializer 1.1.1 → 1.1.2
Sign up to get free protection for your applications and to get access to all the features.
- data/README.md +3 -2
- data/lib/option_initializer/version.rb +1 -1
- data/lib/option_initializer.rb +22 -3
- data/test/test_option_initializer.rb +3 -1
- metadata +1 -1
data/README.md
CHANGED
@@ -19,13 +19,14 @@ class Person
|
|
19
19
|
option_validator do |k, v|
|
20
20
|
case k
|
21
21
|
when :age
|
22
|
-
raise ArgumentError, "invalid age" if
|
22
|
+
raise ArgumentError, "invalid age" if v < 0
|
23
23
|
when :name
|
24
|
-
raise ArgumentError, "invalid name" if
|
24
|
+
raise ArgumentError, "invalid name" if v.empty?
|
25
25
|
end
|
26
26
|
end
|
27
27
|
|
28
28
|
def initialize opts
|
29
|
+
validate_options opts
|
29
30
|
@options = opts
|
30
31
|
end
|
31
32
|
|
data/lib/option_initializer.rb
CHANGED
@@ -1,6 +1,17 @@
|
|
1
1
|
require "option_initializer/version"
|
2
2
|
|
3
3
|
module OptionInitializer
|
4
|
+
def validate_options options
|
5
|
+
return if options.respond_to?(:option_validated?)
|
6
|
+
validators = self.class.const_get(:OptionInitializing).const_get(:VALIDATORS)
|
7
|
+
validators.each do |validator|
|
8
|
+
options.each do |k, v|
|
9
|
+
validator.call k, v
|
10
|
+
end
|
11
|
+
end
|
12
|
+
options
|
13
|
+
end
|
14
|
+
|
4
15
|
def self.included base
|
5
16
|
base.const_set :OptionInitializing, Class.new {
|
6
17
|
attr_reader :options
|
@@ -21,10 +32,18 @@ module OptionInitializer
|
|
21
32
|
# Convention. Deal with it.
|
22
33
|
if args.last.is_a?(Hash)
|
23
34
|
validate args.last
|
24
|
-
|
35
|
+
opts = opts.merge(args.last)
|
36
|
+
args.pop
|
25
37
|
else
|
26
|
-
|
38
|
+
opts = opts.dup
|
39
|
+
end
|
40
|
+
|
41
|
+
opts.instance_eval do
|
42
|
+
def option_validated?
|
43
|
+
true
|
44
|
+
end
|
27
45
|
end
|
46
|
+
args << opts
|
28
47
|
|
29
48
|
@base.new(*args, &block)
|
30
49
|
end
|
@@ -45,7 +64,7 @@ module OptionInitializer
|
|
45
64
|
def method_missing sym, *args, &block
|
46
65
|
# 1.8
|
47
66
|
if @base.instance_methods.map(&:to_sym).include?(sym)
|
48
|
-
|
67
|
+
new.send sym, *args, &block
|
49
68
|
else
|
50
69
|
raise NoMethodError, "undefined method `#{sym}' for #{self}"
|
51
70
|
end
|
@@ -40,6 +40,7 @@ class MyClass2
|
|
40
40
|
end
|
41
41
|
|
42
42
|
def initialize options
|
43
|
+
validate_options options
|
43
44
|
@options = options
|
44
45
|
end
|
45
46
|
|
@@ -104,7 +105,8 @@ class TestOptionInitializer < MiniTest::Unit::TestCase
|
|
104
105
|
assert_raises(ArgumentError) { MyClass2.aaa(-1) }
|
105
106
|
assert_raises(ArgumentError) { MyClass2.aaa(1).aaa(-1) }
|
106
107
|
assert_raises(ArgumentError) { MyClass2.aaa(1).aaa(1).new(:aaa => -2) }
|
107
|
-
assert_raises(ArgumentError) { MyClass2.aaa(1).aaa(1).new(:aaa =>
|
108
|
+
assert_raises(ArgumentError) { MyClass2.aaa(1).aaa(1).new(:aaa => 0) }
|
109
|
+
assert_raises(ArgumentError) { MyClass2.new(:aaa => 0) }
|
108
110
|
end
|
109
111
|
|
110
112
|
def test_readme
|