Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/dolly/property.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def initialize(key, class_name, default = nil)
end

def cast_value(value)
return set_default if value.nil?
return set_default if empty_value?(value)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of doing this, use blank?

return value unless class_name
return custom_class(value) unless respond_to?(klass_sym)
send(klass_sym, value)
Expand All @@ -29,6 +29,11 @@ def boolean?
[TrueClass, FalseClass].include?(class_name)
end

def empty_value?(value)
return value&.empty? if value.respond_to?(:empty?)
value.nil?
end

def string_value(value)
value.to_s
end
Expand Down
36 changes: 36 additions & 0 deletions test/support/property_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
require 'test_helper'

class TestHashDoc < Dolly::Document
property :roles, class_name: Hash, default: { teacher: {} }
end

class TestIntegerDoc < Dolly::Document
property :count, class_name: Integer, default: 0
end

class PropertyTest < Test::Unit::TestCase
test 'With a hash property with a default value' do
doc = TestHashDoc.new
assert_equal(doc.roles, { teacher: {} })
end

test 'With a hash property with an empty value it sets the default value' do
doc = TestHashDoc.new(roles: [])
assert_equal(doc.roles, { teacher: {} })
end

test 'With a hash property with a previous non empty value it preserves the value' do
doc = TestHashDoc.new(roles: { teacher: { 'user/[email protected]': {} } })
assert_equal(doc.roles, { teacher: { 'user/[email protected]': {} } })
end

test 'With an Integer property with a nil value it sets the default value' do
doc = TestIntegerDoc.new(count: nil)
assert_equal(doc.count, 0)
end

test 'With an Integer property with a previous non empty value it preserves the value' do
doc = TestIntegerDoc.new(count: 10)
assert_equal(doc.count, 10)
end
end