ruby-on-rails – `app`目录下的命名空间
在我们的app目录中,我们希望一些子目录包含命名空间类,一些子目录包含顶级类.例如:
> app / models / user.rb定义:: User 我们的application.rb包含以下配置: config.paths = Rails::Paths::Root.new(Rails.root) config.paths.add 'app/models',eager_load: true config.paths.add 'app',eager_load: true 这在大多数情况下都可以正常工作,但有时在开发模式下并且启用了Rails的自动加载,这会导致加载错误的类.例如:: User被误认为是Operations :: User,反之亦然. 有没有办法配置此行为,以便它可以正常工作? 如果没有,我能想到的唯一解决方法是为appd和app_namespaced创建“命名空间”类的第二个目录.或者app / namespaced,因为app级代码应该驻留在app中.但这对我来说似乎是丑陋的变通办法. 编辑:@dgilperez要求的一个小例子: #?app/models/user.rb class User end # app/models/group.rb class Group def some_method #?Since we're in a top-level namespace,User should always # resolve to ::User. But,depending on some seemingly random # factors,it sometimes resolves to Operations::User. User.new end end # app/operations.rb module Operations end # app/operations/user/create.rb module Operations::User class Create def some_method # Here,as expected,I need to prefix with "::" as # 'User' would refer to the module we're currently in. # That's fine and works. ::User.new end end end 解决方法
是的,这是rails自动加载的缺点.默认情况下,它从/ app加载所有内容,但第一级目录结构不是名称的一部分.这样app / models / user.rb可以定义User,而不是要求它是Models :: User.
您不需要弄乱加载路径.这里提供了几种方法/解决方法. >在我当前的项目中,我们只是将命名空间目录加倍.这意味着如果我们想要定义ServiceObjects :: User :: Import,我们将它放入app / service_objects / service_objects / user / import.rb>我个人更喜欢这种方法的变体,即将所有“非标准”内容放入app / lib(可以是app / custom或任何你想要的东西).这样,目录名称没有奇怪的重复,所有自定义代码都包含得很好. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |