solnic/virtus — Issue #76: Virtus::Attribute#value_coerced? not being used
Author: fgrehm
Created: 2012-02-26 04:57:23+00:00
State: open

Today I found out about this method and by doing a `git grep "value_coerced?"` I couldn't spot any use of it. Is it for some future feature or has it been forgotten?

On top of that, using the **Custom Attributes** example from README, is this code really expected to raise an error?

```
user = MyAppClass::User.new
user.info = {"email" => "john@domain.com"}

TypeError: can't convert Hash into String
from /home/fabio/.rvm/gems/ruby-1.8.7-p334@virtus/gems/json-1.6.5/lib/json/common.rb:148:in `initialize'
from /home/fabio/.rvm/gems/ruby-1.8.7-p334@virtus/gems/json-1.6.5/lib/json/common.rb:148:in `new'
from /home/fabio/.rvm/gems/ruby-1.8.7-p334@virtus/gems/json-1.6.5/lib/json/common.rb:148:in `parse'
from (irb):11:in `coerce'
from ./virtus/attribute.rb:191:in `set'
from ./virtus/attributes_accessor.rb:60:in `info='
from (irb):25
```

I mean, should we check if the value is an instance of the target class on custom attributes `#coerce` method (MyAppClass::Attributes::JSON in this case) or should Virtus bypass value coercion and just set the value? If the check is needed, the example should probably be updated to something like:

```
module MyAppClass
module Attributes
class JSON < Virtus::Attribute::Object
primitive Hash

def coerce(value)
if value.is_a? Hash
value
else
::JSON.parse value
end
end
end
end
end
```

I'm asking this because I noticed that on my current project we have some custom attributes that have that kind of checking on `#coerce` method in order to use the coerced value right away on specs.