solnic / virtus

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

Strict mode and empty values #335

Open samstickland opened 8 years ago

samstickland commented 8 years ago

I feel like I must be missing something obvious. Using Virtus as to support an HTML form must be one of the intended use cases, no?

I have some fields, some with custom rails validations, some optional. Out of the box Virtus will store the original string value when coercion fails. So if someone puts 'aaa' into my DateTime field it now stores 'aaa'. I can't enable strict mode because that doesn't seem to allow nil values for my optional values.

So it seems like the only solution is to add additional rails validations to check the stored datatypes? At which point it seems like I'm not really using virtus at all? I could do this with "include ActiveModel::Model" and regular attr_accessor statements.

Am I missing something or have I misunderstood the intended use of this gem?

grantspeelman commented 8 years ago

I was thinking the same thing and considering how would the interface for something like this look.

Maybe something like this:

class NewFeatureRequest
  include Virtus.model(store_coercion_errors: true)

  attribute :title, String
  attribute :date_requested, Date
end

feature = NewFeatureRequest.new('title' => 'Store Failed Coercions', 'date_requested' => 'Not Sure')
expect(feature.date_requested).to eq('Not Sure')
expect(feature.coercion_errors['date_requested']).to be_kind_of(Virtus::CoercionError)