views:

21

answers:

2

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?

A: 

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

apeacox
Is it the bug? It's not native soulition...
petRUShka
don't know about this in rails3, I knew that with rails 2.3 files in lib/ are lazy-loaded when used in some part of the app. by the way it solved my problem :P
apeacox
+1  A: 

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.

Nick Ragaz