davydovanton / shallow_attributes

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

How about introducing an `strict: false` option? #29

Closed f-mer closed 4 years ago

f-mer commented 5 years ago

I'm using this gem in combination with rails for coercing form input. I'm running into issues when trying to coerce DateTime and Time types. The problem is these fields can be blank ("") or invalid (Mo Oct 42 2001). In that case ActiveModel::Validations should take over and add a presence error. But before this can happen an error is raised during coercion.

I'm aware that this problem stems from the fact that I'm mixing validation logic into data-structures. But that's the pattern rails advocates and I'm not sure leaving the rails way is worth it.

Something like this would solve the problem as there is already an allow_nil option I think it's reasonable:

class Post
  include ShallowAttributes
  include ActiveModel::Validations

  attribute :publish_at, Time, strict: false

  validates :publish_at, presence: true
end

Implementation wise it could look something like this.

def coerce(value, options = {})
  # ..
rescue
  if options.fetch(:strict, true)
    raise
  else
    nil
  end
end

Any thoughts on this? I would be happy to supply a PR :)

javierseixas commented 4 years ago

I'm really interested in that feature! :+1: