Consider I have a class located in /lib/foo/bar/baz.rb
, defined as following:
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:
class MyController < ApplicationController
def index
render json: ::Foo::Bar::Baz.new
end
end
which outputs JSON {name: "Baz"}
as one would expect.
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:
class MyController < ApplicationController
include ::Foo::Bar
def index
render json: ::Baz.new
end
end
Returns me the following error message: 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. render json: Baz.new
should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.