davydovanton / shallow_attributes

Simple and lightweight Virtus analog.
MIT License
101 stars 18 forks source link

Error when assigning `nil` to an Array type #22

Closed caioeps closed 6 years ago

caioeps commented 6 years ago

Hi! I'm facing an issue when assigning a nil value to an Array type attribute.

Context:

class User
  include ShallowAttributes
  attribute :arr, Array, of: Integer, default: []
end

user = User.new arr: nil
#=> ShallowAttributes::Type::InvalidValueError: Invalid value "" for type "Array"

However, when not passing arr it works as expected.

user = User.new
#=> #<User arr=[]>

Is this the expected behaviour? I can create a PR if you want to, I'm needing this :)

davydovanton commented 6 years ago

hey, I think raising error for arr: nil is expected behaviour. What do you want to see here?

caioeps commented 6 years ago

I was expecting to build an object with an empty array instead. Something like this:

user = User.new arr: nil
#=> #<User arr=[]>
davydovanton commented 6 years ago

okay, but nil is not Array type. In this case you need to use Null | Array type 🤔

AlexWayfer commented 6 years ago

I think he's expecting input.to_a at coercing (nil.to_a #=> []).

caioeps commented 6 years ago

Oh, I see. In this case I'll have to implement my own Array type. I was actually wondering if it wasn't supposed to use the default value if passing nil as argument. Thanks for taking your time to answer me! Great gem, though :)