问题
I have a file in my Rails 3.2.11 project called app/queries/visible_discussions.rb
which looks like the following:
class VisibleDiscussions
...
end
I'd like to namespace the query so that I can call it using something like Queries::VisibleDiscussions
so I tried to do the following:
module Queries
class VisibleDiscussions
...
end
end
However, I'm getting a uninitialized constant Queries (NameError)
when I try to call Queries::VisibleDiscussions
from the rails console.
Any ideas?
回答1:
if you add lib
to your autoload_paths then it will respect the namespacing under lib - lib/query/visible_discussions.rb
or create a new dir under app - say src and then nest your code there - app/src/query/visible_discussions.rb
i would use the 3rd style in your post for either of these, i.e.
module Query
class VisibleDiscussions
...
end
end
both of these solutions are annoying to me, there might be a way to tell rails to namespace directories under app, but i have no clue how it would be done
回答2:
Rails needs to know what directories to load (a part from the defaults). Try:
#config.application.rb
config.autoload_paths += %W(#{config.root}/queries)
来源:https://stackoverflow.com/questions/14348891/rails-3-trouble-with-namespaces-custom-classes-uninitialized-constant