1

In a custom DataMapper setter, I'd like to check whether the value I'm setting is valid or not.

For instance:

class ToastMitten
  include DataMapper::Resource

  property :id, Serial
  property :wearer, Enum['Chuck Norris', 'Jon Skeet']
  property :first_worn_at, DateTime

  def wearer=(name)
    super
    if wearer.valid? # How can I do this?
      first_worn_at = Time.now
    end
  end

end

t = ToastMitten.new
t.wearer = 'Nathan Long' # invalid value; do NOT set first_worn_at
t.wearer = 'Jon Skeet'   # valid value; set first_worn_at

Can I check the validity of a single property like this without calling valid? on the object itself and looking through all the errors?

Nathan Long
  • 122,748
  • 97
  • 336
  • 451

1 Answers1

2

I'm trying to figure this out myself, here is the best solution I've found so far:

While I haven't found a method to check the validity of a single property, as in:

t.wearer.valid?

I have found that you can check the validity of the entire object prior to saving, and then check if there are errors on the property you are interested in like so:

if t.valid?
  # Everything is valid.
else
  # There were errors, let's see if there were any on the 'wearer' property...
  puts t.errors.on(:wearer)
end

I know that that isn't necessarily the answer you seek, but it's the best I've come up with so far. I'll post back if I find something better.

bradleygriffith
  • 948
  • 3
  • 11
  • 24