Skip to content

Commit

Permalink
boolean attributes should be able to be set to nil without converting…
Browse files Browse the repository at this point in the history
… to false
  • Loading branch information
mguterl committed Feb 24, 2011
1 parent 503a1ec commit c09084c
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
5 changes: 4 additions & 1 deletion lib/serialized_attributes/types.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ def parse(input) input.blank? ? nil : input.to_f end

class Boolean < AttributeType
def parse(input) input && input.respond_to?(:to_i) ? (input.to_i > 0) : input end
def encode(input) input ? 1 : 0 end
def encode(input)
return nil if input.nil?
input ? 1 : 0
end
end

class String < AttributeType
Expand Down
2 changes: 1 addition & 1 deletion test/serialized_attributes_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ def setup

test "defines #active_before_type_cast method on the model" do
assert @record.respond_to?(:active_before_type_cast)
assert_equal "0", @record.active_before_type_cast
assert_equal "", @record.active_before_type_cast
end

attributes[:string].each do |attr|
Expand Down
12 changes: 12 additions & 0 deletions test/types_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-
require File.dirname(__FILE__) + '/test_helper'

class SerializedAttributesTypesTest < ActiveSupport::TestCase

test "boolean type encodes nil properly" do
type = SerializedAttributes::Boolean.new

assert_equal nil, type.encode(nil)
end

end

0 comments on commit c09084c

Please sign in to comment.