Skip to content

Commit

Permalink
dict: improve type checking and conversation
Browse files Browse the repository at this point in the history
  • Loading branch information
mswart committed Sep 20, 2014
1 parent 52d9aff commit ef491d5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/acfs/model/attributes/dict.rb
Expand Up @@ -21,7 +21,8 @@ class Dict < Base
# @raise [TypeError] If object cannot be casted to a hash.
#
def cast_type(obj)
return obj.to_h if obj.respond_to? :to_a
return obj if obj.is_a? Hash
return obj.to_h if obj.respond_to? :to_h
raise TypeError.new "Cannot cast #{obj.inspect} to hash."
end
end
Expand Down
18 changes: 17 additions & 1 deletion spec/acfs/model/attributes/dict_spec.rb
Expand Up @@ -24,11 +24,27 @@
end

context 'with hashable object' do
let(:sample) { [[3, 4], ['test', true]] }
let(:sample) do
o = Object.new
class << o
def to_h
{3 => 4, 'test' => true}
end
end
o
end

it 'should cast object to hash' do
expect(subject.cast(sample)).to eq 3 => 4, 'test' => true
end
end

context 'with hash subclass' do
let(:sample) { HashWithIndifferentAccess.new :test => :foo, 34 => 12 }

it 'should return obj unmodified' do
expect(subject.cast(sample)).to be sample
end
end
end
end

0 comments on commit ef491d5

Please sign in to comment.