Skip to content
This repository has been archived by the owner on Apr 17, 2018. It is now read-only.

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

Open
ders opened this issue Nov 13, 2013 · 0 comments
Open

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

ders opened this issue Nov 13, 2013 · 0 comments

Comments

@ders
Copy link

ders commented Nov 13, 2013

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 >
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant