I have a Rails4 app and I'm trying to flash a custom message when a session times out due to inactivity.
I'm doing this by configuring the timeout_in
setting in devise.rb
:
Devise.setup do |config|
...
config.timeout_in = 30.minutes
...
end
and adding a custom rescue to my application controller:
rescue_from CanCan::AccessDenied do |exception|
if user_signed_in?
flash.now.alert = exception.message
render text: '', layout: true, status: 403
else
redirect_to new_user_session_path, notice: flash[:alert] || "You must login first"
end
end
Everything seems to be working fine... when the session times out, flash[:alert]
already has the correct message so I just use that and when the user tries to access a resource without logging in first then the "You must login first" message is returned.
This is the code in the the main.html.haml page that renders these alerts:
.container
.main-content
#flash
- flash.each do |type, msg|
%div{class: ('alert alert-dismissable fade in')}
%button.close{data: {dismiss: :alert}} ×
= msg
= yield
The problem is that once a while I see a flash with the text "True" appearing right below the session timeout message:
and I can't figure out where it's coming from. It seems that something is creating a flash message with that value. I wonder what am I doing wrong or if there a better way to display a session timeout messages. Any ideas?
Try outputting the type
of each flash – maybe Devise or something else is using the flash for other things than just messages. Read more about using the flash for other things than messages.
I wouldn't loop over all flash keys to render them – I'd explicitly render only the ones that are dedicated to messages (usually :notice
and :alert
).