transformable 0.0.4 → 0.0.5

Sign up to get free protection for your applications and to get access to all the features.
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
- new_value = yield(value)
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
@@ -1,3 +1,3 @@
1
1
  module Transformable
2
- VERSION = "0.0.4"
2
+ VERSION = "0.0.5"
3
3
  end
@@ -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
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: transformable
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.4
4
+ version: 0.0.5
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors: