The users of my Rails app tend to have multiple accounts to login. Cookies are used to store the names of those accounts in each user’s browser as comma separated values. This makes it easier for my users to switch between accounts.
I created a helper module to handle all the dirty work related to cookies:
module StoredAccountsHelper
def store_account(account)
names = stored_accounts.unshift(account.name)
cookies.permanent[:accounts] = names.uniq.join(',')
end
def discard_accounts
cookies.delete(:accounts)
end
def stored_accounts
cookies[:accounts]&.split(',') || []
end
def account_options
stored_accounts&.sort&.map
end
def only_one_stored_account?
stored_accounts.count == 1
end
def find_stored_account
@account = Account.activated.where(:name => params[:account]).first
unless @account
flash[:notice] = t('views.not_permitted')
redirect_to new_stored_account_path
discard_accounts
end
end
def stored_accounts_present
if stored_accounts.empty?
redirect_to new_stored_account_path
end
end
end
This helper works and has stood the test of time, however it feels wrong to me. Shouldn’t all the methods be methods of a class (e.g. named AccountsStore
) rather than those of a helper module?
That way, I could do things like:
accounts_store = AccountsStore.new(@account)
accounts_store.add(@account)
accounts_store.remove(@account)
accounts_store.list_all
accounts_store.options
etc.
But unfortunately, cookies can only be used in controllers and helpers if I am informed correctly.
Is there a more elegant logic to add values to and remove values from a cookie in Rails?
Thanks for any pointers.