Rails3: validates_with, in what place I should put MyValidator?
I have an validator EmailValidator and class User:
class EmailValidator < ActiveModel::Validator
def validate(record)
record.errors[:base] << "error" unless record.email.scan("@")
end
class User < ActiveRecord::Base
validates_with EmailValidator
end
If I put EmailValidator definition in separate file in lib/ directory, or in user.rb after User class definition I get an error:
/usr/lib/ruby/gems/svn/gems/rspec-core-2.0.0.beta.16/lib/开发者_如何学编程rspec/core/backward_compatibility.rb:20:in `const_missing': uninitialized constant User::EmailValidator (NameError)
But if I put EmailValidator definition before User definition in user.rb like in example above it is ok.
In what place I should put EmailValidator?
You should be able to just put it in lib/email_validator.rb
in the latest Rails 3 HEAD, and have it autoload.
Are you using an older version?
For a brief time (i.e. until the commit was reverted), files in lib
were not being autoloaded -- and I believe this is still the goal, but the implementation was buggy so that change was reverted for now. To be safe and fully forward-compatible, add the following line to your config/application.rb
:
config.autoload_paths += %W( #{config.root}/lib )
Alternatively, if the code works in when using your app but not when running RSpec, then this could be a bug in RSpec rather than in Rails.
I resolved a similar problem putting something like this in
RAILS_APP/config/initializers/my_custom_file.rb
require 'mylibfile' # it will load file found in lib/mylibfile.rb
this solution pemits to load custom libs during application boot
精彩评论