【问题标题】:Rails engines and namespacing. Cases where namespaces are required?Rails 引擎和命名空间。需要命名空间的情况?
【发布时间】:2012-08-30 10:58:46
【问题描述】:

我对引擎中的命名空间有点困惑。在使用 isolate_namespace 的 Rails 引擎中,

module Blog
  class Engine < Rails::Engine
    isolate_namespace Blorgh
  end
end

什么时候需要您引用带有命名空间Blog 的对象(例如Blog::PostPost)?

例如,在引擎的Post 资源的控制器中,只执行Post.find 可以吗?什么时候绝对需要你使用Blog::Post

同样在模型关联中,假设 Post has_many :comments。不知何故,我希望将其定义如下:

class Post < ActiveRecord::Base
  :has_many "blog/comments"
end

因为一切都是命名空间(模型,表名,...),但它看起来像 has_many :comments 只是工作。为什么在关联键中不使用命名空间,并且在主机应用程序中存在Comment 资源的情况下,rails 怎么知道我指的是哪个Comment

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rails-engines


    【解决方案1】:

    当你在某个模块中时,你可以引用该模块的其他成员而无需给出模块名称,例如:

    module Foo
    
      class Bar
        def initialize
          @baz = Baz.new # same as Foo::Baz.new
        end
      end
      class Baz
    
      end
    end
    

    如果Baz在当前模块中不存在,它将级联查找定义,最终调用const_missing(在此基础上构建了Rails中类的自动加载),如果没有则抛出错误找到了。

    here 已回答您的其余问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-20
      • 2014-03-19
      • 1970-01-01
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多