Reputation: 1537
I use temporarily Rails as frontend app to communicate with an API.
After the authentication, I set the user_id
in a cookie.
I use the her
gem to call the User from the API and save it into an instance variable.
The issue is that I do this request on every page I and would like to do it once. It's like @current_user is reset after each page.
def current_user
#User.find -> Her model
@current_user ||= User.find(cookies.signed[:user_id]) if cookies.signed[:user_id]
end
Upvotes: 0
Views: 985
Reputation: 1773
There no clear solution because your user coming from API. You can try to do something like that:
#remember user attributes without references
session['user'] = @current_user.attributes #remember
@user = OpenStruct(session['user']) #load, allow call @user.name etc, but not @user.posts
#use class variable
class User
include Her::Model
@@tmp = {}
def remember
@@tmp[id] = self
#call job etc to delete user from tmp to prevent something that reminds "memory leak"
end
def self.local_find(id)
@@tmp[id]
end
end
def current_user
@current_user ||= User.local_find(cookies.signed[:user_id]) ||
User.find(cookies.signed[:user_id]) if cookies.signed[:user_id]
end
The main reason not to store(remember) objects in the session(long-term variable) is that if the object structure changes, you will get an exception.
Upvotes: 1