[英]Include doesn't work inside Rails controller
Consider I have a class located in /lib/foo/bar/baz.rb
, defined as following: 考虑我在/lib/foo/bar/baz.rb
有一个类,定义如下:
module Foo
module Bar
class Baz
def initialize
self.name = 'Baz'
end
end
end
end
I also have the following controller /controllers/my_controller.rb
, defined as following: 我还具有以下控制器/controllers/my_controller.rb
,定义如下:
class MyController < ApplicationController
def index
render json: ::Foo::Bar::Baz.new
end
end
which outputs JSON {name: "Baz"}
as one would expect. 会像预期的那样输出JSON {name: "Baz"}
。
The problem is if I try to include the Foo::Bar
module, so I don't have to prepend it to the Baz
class name each time I want to use it: 问题是如果我尝试包括Foo::Bar
模块,那么我不必每次都想使用它时将其添加到Baz
类名之前:
class MyController < ApplicationController
include ::Foo::Bar
def index
render json: ::Baz.new
end
end
Returns me the following error message: uninitialized constant Baz
. 返回以下错误消息: uninitialized constant Baz
。
Why??? 为什么???
I think you should try 我认为你应该尝试
include ::Foo::Bar
...
render json: Baz.new
::Baz
ensures finding the module Baz
in the top level namespace, so you should not use this syntax. ::Baz
确保在顶级名称空间中找到模块Baz
,因此您不应使用此语法。 render json: Baz.new
should work. render json: Baz.new
应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.