validated_accessors 0.0.1 → 0.1.1
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/lib/validated_accessors.rb +16 -3
- data/test/validated_accessors_test.rb +12 -0
- metadata +1 -1
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA1:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 0a6c4ee83467065bfbdaa71fac141d0161f21069
|
4
|
+
data.tar.gz: fa715ffcb81ff64b6ec60e993977d1f22948f156
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: bebc63e716e077246b5d33de7fb50b470bd940efd8a19ab1778435ead76c3a3f485bf7fbac0e966ec7f902c8cc15d756eac9bb347a7de597a8c1e8317f566653
|
7
|
+
data.tar.gz: 6980ab432f0855c97d5b566de2be7337cde3f16fd59ca8f5d010d46b1b5d9437b57b0e51ed19747b75d704b422f28d52bf2fd8e92c4fc0df7922d8305594737f
|
data/lib/validated_accessors.rb
CHANGED
@@ -2,18 +2,31 @@
|
|
2
2
|
|
3
3
|
module ValidatedAccessors
|
4
4
|
|
5
|
-
VERSION = "0.
|
5
|
+
VERSION = "0.1.1"
|
6
6
|
|
7
|
-
def validated_accessor attribute, options
|
7
|
+
def validated_accessor attribute, options, &block
|
8
|
+
define_attribute_reader attribute
|
9
|
+
define_attribute_writter attribute, options, &block
|
10
|
+
end
|
11
|
+
|
12
|
+
private
|
8
13
|
|
14
|
+
def define_attribute_reader attribute
|
9
15
|
define_method attribute do
|
10
16
|
instance_variable_get "@#{ attribute }"
|
11
17
|
end
|
18
|
+
end
|
12
19
|
|
20
|
+
def define_attribute_writter attribute, options, &block
|
13
21
|
define_method "#{ attribute }=" do |value|
|
22
|
+
value = yield value if block_given?
|
23
|
+
unless options[:valid].include? value
|
24
|
+
raise ArgumentError,
|
25
|
+
"Invalid value: #{ value } for #{ attribute }."\
|
26
|
+
"(Valid values are: #{ options[:valid] })"
|
27
|
+
end
|
14
28
|
instance_variable_set "@#{ attribute }", value
|
15
29
|
end
|
16
|
-
|
17
30
|
end
|
18
31
|
|
19
32
|
end
|
@@ -2,6 +2,7 @@ setup do
|
|
2
2
|
class Foo
|
3
3
|
extend ValidatedAccessors
|
4
4
|
validated_accessor :bar, valid: [:two, :three]
|
5
|
+
validated_accessor :sym_bar, valid: [:two, :three] { |v| v.to_sym }
|
5
6
|
end
|
6
7
|
Foo.new
|
7
8
|
end
|
@@ -14,3 +15,14 @@ test 'let you assign valid values' do |foo|
|
|
14
15
|
foo.bar = :two
|
15
16
|
assert foo.bar == :two
|
16
17
|
end
|
18
|
+
|
19
|
+
test 'raise when you use assign invalid values' do |foo|
|
20
|
+
assert_raise ArgumentError do
|
21
|
+
foo.bar = :invalid
|
22
|
+
end
|
23
|
+
end
|
24
|
+
|
25
|
+
test 'enforce the type provided' do |foo|
|
26
|
+
foo.sym_bar = 'two'
|
27
|
+
assert foo.sym_bar == :two
|
28
|
+
end
|