aboutsummaryrefslogtreecommitdiffstats
path: root/guides
diff options
context:
space:
mode:
authorHenrik Nyh <henrik@nyh.se>2013-02-09 15:47:22 +0100
committerHenrik Nyh <henrik@nyh.se>2013-02-09 15:47:22 +0100
commit045f0195e09828fad7770794ade996aa62664647 (patch)
tree2d7a908d47f6d177b14e39d0ca9f7f4851495c3b /guides
parent7c663f507f5b4f1f443949c92dbc375d42dbd6b8 (diff)
downloadrails-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')
-rw-r--r--guides/source/active_record_validations.md29
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