1

在自定义 DataMapper 设置器中,我想检查我设置的值是否有效。

例如:

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

我可以在不调用valid?对象本身并查看所有错误的情况下检查这样的单个属性的有效性吗?

4

1 回答 1

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.

于 2012-04-09T23:00:22.630 回答