在“lib/"目录中实现自定义验证器是一种正确的方法吗? [英] Is it a proper way to implement a custom validator in the 'lib/' directory?

查看:38
本文介绍了在“lib/"目录中实现自定义验证器是一种正确的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ruby on Rails 3.2.9.一种解决在'lib'目录的子目录中扩展Rails的问题"与自定义验证器 用于说明以下代码(注意文件所在的目录)

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

andconfig.autoload_paths += %W(#{config.root}/lib/extension/rails) 语句放在 config/application.rb 文件.这样,CustomValidator 在启动服务器时会正确加载,并且我的 lib/ 目录按照我的预期进行组织.

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.

但是,我想知道这是否是在 RoR 中制作这些东西的正确"/正确"方式.换句话说,是否有更好的方法来完成相同的任务?

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

但是,通过使用上面的代码,似乎没有一种简单的方法可以使 CustomValidator 工作,即使我声明 config.autoload_paths += %W(#{config.root}/lib)config/application.rb 文件中.

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.

推荐答案

你可以在 lib/ 目录下创建一个需要你的 rails 扩展的文件:

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

# lib/extension.rb
require 'extension/rails/custom_validator'

这篇关于在“lib/"目录中实现自定义验证器是一种正确的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆