diff options
author | Henrik Nyh <henrik@nyh.se> | 2013-02-09 15:47:22 +0100 |
---|---|---|
committer | Henrik Nyh <henrik@nyh.se> | 2013-02-09 15:47:22 +0100 |
commit | 045f0195e09828fad7770794ade996aa62664647 (patch) | |
tree | 2d7a908d47f6d177b14e39d0ca9f7f4851495c3b /guides/source | |
parent | 7c663f507f5b4f1f443949c92dbc375d42dbd6b8 (diff) | |
download | rails-045f0195e09828fad7770794ade996aa62664647.tar.gz rails-045f0195e09828fad7770794ade996aa62664647.tar.bz2 rails-045f0195e09828fad7770794ade996aa62664647.zip |
Validations guide: validates_with init clarification.
As discussed with @josevalim on Ruby Rogues Parley.
Diffstat (limited to 'guides/source')
-rw-r--r-- | guides/source/active_record_validations.md | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md index eaa47d4ebf..32641d04c1 100644 --- a/guides/source/active_record_validations.md +++ b/guides/source/active_record_validations.md @@ -618,6 +618,35 @@ class GoodnessValidator < ActiveModel::Validator end ``` +Note that the validator will be initialized *only once* for the whole application +life cycle, and not on each validation run, so be careful about using instance +variables inside it. + +If your validator is complex enough that you want instance variables, you can +easily use a plain old Ruby object instead: + +```ruby +class Person < ActiveRecord::Base + validate do |person| + GoodnessValidator.new(person).validate + end +end + +class GoodnessValidator + def initialize(person) + @person = person + end + + def validate + if some_complex_condition_involving_ivars_and_private_methods? + @person.errors[:base] << "This person is evil" + end + end + + # … +end +``` + ### `validates_each` This helper validates attributes against a block. It doesn't have a predefined |