transformable 0.0.4 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- data/lib/transformable.rb +8 -2
- data/lib/transformable/version.rb +1 -1
- data/spec/transformable_spec.rb +35 -0
- metadata +1 -1
data/lib/transformable.rb
CHANGED
@@ -8,10 +8,16 @@ module Transformable
|
|
8
8
|
|
9
9
|
|
10
10
|
module ClassMethods
|
11
|
-
def clean(attr, &blk)
|
11
|
+
def clean(attr, options={}, &blk)
|
12
|
+
|
13
|
+
skip_nil = options.fetch(:skip_nil) { true }
|
12
14
|
|
13
15
|
define_method "#{attr}=" do |value|
|
14
|
-
|
16
|
+
if value.nil? and skip_nil
|
17
|
+
new_value = value
|
18
|
+
else
|
19
|
+
new_value = yield(value)
|
20
|
+
end
|
15
21
|
instance_variable_set("@#{attr}", new_value)
|
16
22
|
write_attribute(attr, new_value) if defined? ActiveRecord and defined? ActiveRecord::Base and is_a? ActiveRecord::Base
|
17
23
|
end
|
data/spec/transformable_spec.rb
CHANGED
@@ -6,10 +6,45 @@ class Foo
|
|
6
6
|
clean(:title) { |v| v.gsub(/\s/, "")}
|
7
7
|
end
|
8
8
|
|
9
|
+
class Bar
|
10
|
+
include Transformable
|
11
|
+
attr_accessor :title
|
12
|
+
clean(:title, :skip_nil => false) {|v| v.nil? ? "bar" : v }
|
13
|
+
end
|
14
|
+
|
15
|
+
class NoNils
|
16
|
+
include Transformable
|
17
|
+
attr_accessor :title
|
18
|
+
clean(:title) {|v| "bar" }
|
19
|
+
end
|
20
|
+
|
9
21
|
describe Transformable do
|
10
22
|
it "used the provided block to filter attributes" do
|
11
23
|
f = Foo.new
|
12
24
|
f.title = "bar bar"
|
13
25
|
f.title.should == "barbar"
|
14
26
|
end
|
27
|
+
|
28
|
+
context "when :skip_nil is not set (aka :skip_nil => true)" do
|
29
|
+
it "doesn't let nil values through to the block" do
|
30
|
+
n = NoNils.new
|
31
|
+
n.title = nil
|
32
|
+
n.title.should be_nil
|
33
|
+
end
|
34
|
+
end
|
35
|
+
|
36
|
+
|
37
|
+
context "when :skip_nil is set to false" do
|
38
|
+
it "lets nil values through" do
|
39
|
+
b = Bar.new
|
40
|
+
b.title = nil
|
41
|
+
b.title.should == "bar"
|
42
|
+
end
|
43
|
+
|
44
|
+
it "lets non-nil values through" do
|
45
|
+
b = Bar.new
|
46
|
+
b.title = "foobar"
|
47
|
+
b.title.should == "foobar"
|
48
|
+
end
|
49
|
+
end
|
15
50
|
end
|