Reputation: 4484
I want to namespace all my classes put in a app/cms
folder under Cms
module. So, let's say i have a following file:
# /app/cms/types/post.rb
class Cms::Types::Post
end
Rails assumes that class definition of a file put in this dir should be Types::Post
instead of Cms::Types::Post
. So, when calling Cms::Types::Post.new
, rails throws
LoadError (Unable to autoload constant Types::Post, expected /Users/xxx/workspace/personal/xxx/app/cms/types/post.rb to define it)
How can i namespace all these files under Cms
?
I'm on rails 5.2.0
Upvotes: 0
Views: 61
Reputation: 20253
What is Post
? I mean, what is the nature of Post
? For instance, is it a service?
If it were a service (for example), I would put it in:
/app/services/cms/types/post_service.rb
And then define it as:
class Cms::Types::PostService
end
If it were a type
(which seems like it might be a problematic name), then I would define it in:
/app/types/cms/post_type.rb
and define it as:
class Cms::PostType
end
In other words, name the directory under /app
using the description of what Post
is (just like rails does with models
, controllers
, etc.) and then add the description (in the singular form) to the end of your definition (rails does this with controllers
, helpers
, and mailers
, but not with models
).
Upvotes: 1
Reputation: 832
Normally, when you use namespace
you need to have your file structure as below:
module Cms
module Types
class Post
end
end
end
EDIT:
Also to make it, autoload the path, you could add the below line in your application.rb
:
config.autoload_paths << Rails.root.join('app', 'cms').to_s
Upvotes: 0