4

I am using Ruby on Rails 3.2.9. A way to solve "Trouble on extending Rails in a sub-directory of the 'lib' directory" related to Custom Validators was to state the following code (note the directory where the file is located)

# lib/extension/rails/custom_validator.rb
class CustomValidator < ActiveModel::EachValidator
  # ...
end

and to put the config.autoload_paths += %W(#{config.root}/lib/extension/rails) statement in the config/application.rb file. This way the CustomValidator is correctly loaded when starting the server and my lib/ directory is organized as I'd expect.

However, I would like to know if that is a "proper" / "right" way to make these kind of things in RoR. In other words, is there a better approach to accomplish the same?


Note: In order to organize code in files I am thinking to namespace classes as-like the following:

# lib/extension/rails/custom_validator.rb
module Extension
  module Rails
    class CustomValidator < ActiveModel::EachValidator
      # ...
    end
  end
end

But, by using the above code, it seems that there isn't an easy way to make the CustomValidator to work, even if I state config.autoload_paths += %W(#{config.root}/lib) in the config/application.rb file.

Community
  • 1
  • 1
Backo
  • 18,291
  • 27
  • 103
  • 170

2 Answers2

0

In many cases custom validators belong to the application domain. So the best place for it is app/validators. There is a great post about this here http://blog.codeclimate.com/blog/2012/02/07/what-code-goes-in-the-lib-directory/

Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
  • 1
    In my case the customs validator could belong to many application domains since it is for general purposes. So it should go in the `lib/` directory (at least for me), even more after reading the linked post and related comments. – Backo Dec 16 '12 at 22:53
0

you can create a file under the lib/ directory that requires your rails extensions:

# lib/extension.rb
require 'extension/rails/custom_validator'
wacko
  • 3,384
  • 1
  • 15
  • 22