Where to put constraint classes in Rails project

at.*_*at. 19 ruby-on-rails naming-conventions convention-over-configur ruby-on-rails-3 ruby-on-rails-3.2

Just curious about the best practices for Rails in where I put a custom constraints class that's used as a constraint in config/routes.rb. Seems like Rails.root/lib is where all user classes go. Is that appropriate for this? Should I be creating a directory inside for constraints? 2 empty directories exist there now, assets and tasks. Are there conventions for this?

axs*_*uul 21

lib/将是适当的地方.如果你想让它更干净,把它放进去lib/constraint/authenticated.rb并定义你的约束

module Constraint
  class Authenticated
    def matches?(request)
      # stuff
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

在你的 routes.rb

constraints Constraint::Authenticated.new do
  match 'account' => 'account#index'
end
Run Code Online (Sandbox Code Playgroud)

  • 我基本上完全相同的设置 - 除了我得到一个'NameError:未初始化的常量Constraint`错误.当我删除模块,并引用`MyConstraint.new`(没有命名空间)时,它可以工作.为什么在模块中包装它会抛出这样的错误?我真的想要那个命名空间> < (5认同)

小智 11

奇怪的是,指南没有说明该路径,但是lib/constraints甚至列在API中(ActionDispatch :: Routing :: Mapper :: Scoping):

如果路由过于复杂,您可以将此逻辑移出到类中.此类必须在matches?其上定义一个方法,如果应该授予用户访问该路由的权限,则返回true;如果用户不应该访问,则返回false.

class Iphone
  def self.matches?(request)
    request.env["HTTP_USER_AGENT"] =~ /iPhone/
  end
end
Run Code Online (Sandbox Code Playgroud)

此代码的预期位置是lib/constraints.

  • 虽然API建议使用`lib/constraints`,但我认为`app/constraints`是一个更合适的地方,因为后者是自动加载的,但前者不是.不过,这只是_my_练习. (7认同)
  • 它是否在开发中自动加载应该无关紧要.我根据这篇博文是否依赖于该特定类是否特定于域来做出决定:http://blog.codeclimate.com/blog/2012/02/07/what-c​​ode-goes-in-the-lib-目录/ (4认同)