Reputation: 107
I am using devise and have created a service object - everything works as expected and perfectly. However I want to know how I would include the current_user? as the moment I have to always pass in the current_user or user_signed_in? variables which is annoying when I am using the same methods in different classes and views how would I go about doing this?
Currently I have this for testing:
class User
class GetStart
attr_reader :current_user
def initialize(user)
@current_user = user
p current_user
end
end
end
Upvotes: 4
Views: 2888
Reputation: 11235
current_user
is usually a helper method of ApplicationController which means it will only be accessible within your controllers and views. This is a good thing -- your service object has no business accessing current_user
directly since current_user is created from information passed in the request/session which is a concern of the controller.
In my opinion, your approach is correct, it's preferable to pass your user object in as an external object (i.e. dependency injection) than directly couple it to method within a separate object. After all, does your service object need to know or care whether user
is from the session?
Also, as was mentioned, keep in mind that attr_reader
creates an instance variable for the class, so you should have @current_user = user
.
Upvotes: 5