datamapper / dm-types

DataMapper plugin providing extra data types
http://datamapper.org/
MIT License
55 stars 80 forks source link

Exception when assigning an arbitrary string to a Json field #69

Open ders opened 10 years ago

ders commented 10 years ago

I'm going to suggest that assigning an arbitrary string to a Json field should result in a validation error rather than an exception.

I have a class defined as follows:

class Mymodel
  include DataMapper::Resource
  property :id, Serial
  property :jsonfield, Json
end

Assigning a hash or an array to jsonfield works as expected. The hash or array is properly json-ized in the data store, and when I read the field back, I get a hash/array that's identical to the original.

2.0.0p247 :001 > a = Mymodel.new
 => #<Mymodel @id=nil @jsonfield=nil>
2.0.0p247 :002 > a.jsonfield = ["Nancy", "Mary", "Phil"]
 => ["Nancy", "Mary", "Phil"]
2.0.0p247 :003 > a.jsonfield
 => ["Nancy", "Mary", "Phil"]
2.0.0p247 :004 >

Assigning a string to jsonfield causes the parser to interpret the string as a json-encoded hash or array. When I read the field back, I get the hash or array instead of the string representation.

2.0.0p247 :004 > a.jsonfield = '["Nancy", "Mary", "Phil"]'
 => "[\"Nancy\", \"Mary\", \"Phil\"]"
2.0.0p247 :005 > a.jsonfield
 => ["Nancy", "Mary", "Phil"]
2.0.0p247 :006 >

Assigning a string that is not a valid json representation of a hash or array raises an exception.

2.0.0p247 :006 > a.jsonfield = "Nancy"
MultiJson::LoadError: 795: unexpected token at 'Nancy'
...

I would expect this last case to result in a validation error, not an exception.

For comparison, no exception is raised when I assign "Nancy" to id. It simply won't validate.

2.0.0p247 :007 > a.id = "Nancy"
 => "Nancy"
2.0.0p247 :008 > a.valid?
 => false
2.0.0p247 :009 > a.errors[:id]
 => ["Id must be an integer"]
2.0.0p247 :010 >