solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 228 forks source link

Allow a default value when the attribute is assigned as nil, with the :allow_nil option #292

Open JanDintel opened 9 years ago

JanDintel commented 9 years ago

This MR adds the option :allow_nil to a Virtus::Attribute. The option allows the user to specify wether to use the default value of an attribute that got assigned as nil. The option will be false by default for backwards compatibility.

See gist for before and after examples

Related issues for this MR are: #291 and #172.

coveralls commented 9 years ago

Coverage Status

Coverage increased (+0.01%) when pulling a75ba02095e92151b558f50f72ccc1868318635d on JanDintel:allow-nil-option into 509327829720bae69f613021639f53c92ea9c2bf on solnic:master.

JanDintel commented 9 years ago

Could you have a look at this MR @elskwid?

JanDintel commented 9 years ago

Maybe you could have a look @solnic?

solnic commented 9 years ago

I will take a look yes! My initial reaction is "OMG NO" but maybe I'm missing something, I need to take a closer look. Will get back to you as soon as possible.

JanDintel commented 9 years ago

@solnic Maybe it's just the name of the option (:allow_nil) that puts you off. But I think this feature/fix is a good addition to Virtus, while staying backwards compatible in the API.

jpmoral commented 9 years ago

:+1: This also seems related to https://github.com/solnic/virtus/issues/235.

booch commented 8 years ago

I'm inclined to accept this, or something similar. Since we don't do validations, we can't just reject the whole object if one attribute contains something that we really don't want in our object. So at this level, I suppose it makes sense to ensure our object is in a useable state, whatever that might mean.

lime commented 7 years ago

I've encountered this need a couple of times; it would be great to be able to specify that an attribute falls back to the default when set to nil.

I wonder if this would be an easier feature to pull through if the naming was more explicit? I could see how :allow_nil could be misinterpreted as to mean something different.

Something like :fallback_to_default_on_nil would be hard to misunderstand, though it's quite a mouthful. Would maybe :default_on_nil be close enough..?

taryneast commented 6 years ago

Bump... I'd really like this functionality