Reputation: 2071
I have some classes in app/services to which I gave a namespace. For example:
module MyArea
class A
end
end
Then, I want to use it in a Rails model. I tried calling it like this:
def models_method
MyArea::A.new
end
But Rails will through a uninitialized constant MyArea::A
error.
For me it doesn't make sense to call class A something like MyAreaA, as I think it's redundant. Isn't that the whole point of namespacing?
What is your suggestion in order to inform of the namespace and at the same time not being redundant?
Thank you.
Upvotes: 0
Views: 1200
Reputation: 11
@borjagvo it's possible your model where the service class MyArea::A
is being initialized is also namespaced
module ModelNamespace
class ActualModel
def models_method
::MyArea::A.new
end
end
end
You can fix it by prepending it with ::
which is the "Constant resolution operator"
Upvotes: 1
Reputation: 716
I think you are getting this error for your folder structure.
You have to add your namespace as follows:
Step 1. Create one folder named report
. In my case report
is my namespace. Change this name as per your requirement.
Step 2. Put your service file inside report
folder.
# app/services/report/meetings.rb
module Report
class Meetings
def your_method
# your codes here...
end
end
end
# or you can write like this.
class Report::Meetings
def your_method
# your codes here...
end
end
Step 3: Now you can call your method anywhere inside your rails app.
obj = Report::Meetings.new
obj.your_method
Happy Coding :-)
Upvotes: 1