flash-like implementation
January 13th, 2008
Flash is a Ruby on Rails method to show (mainly warning/error) messages. Camping has no such method, so i implemented an approach for error messages. The thing is, after a post method in the controller, the redirect creates a new instance for the controller, loosing the class instance variables set before.
So, after talking a bit with Zimbatm at #camping, we setup what could be a good solution: to use the @state session variable.
@state.error = ‘The unit is still operational, Dave. But it will fail within seventy-two hours’
The variable is cleared on the View layout method. Flash means just it. Show and clear. The layout code includes:
div(:class => 'error') { p @state.error.to_s; @state.error = ''; } unless @state.error.blank?
and the CSS .error class wraps the message inside a lightred box with a nice solid red border (say RoR?).
Dan Hoern said:
Yes, That’s a good way to do it.
I just did the same and included a small alert image inside the box. Good. Thank for the tip.
pedro said:
Dan,
nice. One could even move from the string to an Hash, and create different CSS styles for different messages. Like a background (image/color) for Warnings, one other for Errors, etc.
Error = {1 => {:class => 'e_nullfields', :msg => 'Fill all the required fields'},
2 => {:class => 'e_dataexists', :msg => 'Duplicate data'}
}
Then lets set an error:
@state.err = 1Finally, the layout would take a:
div(:class => Error[@state.err][:class]) { p Error[@state.err][:msg]; @state.err = ''; } unless @state.err.blank?Andy Junior said:
Hello,
I’m getting an error using the @state.myerror variable:
“NoMethodError undefined method ‘myerror’ for nil:NilClass:”
Not using your last comment code, just the first one.
pedro said:
Andy,
did you include the Session module ? @state is the session variable, so you need to use the camping/session module. Something like this:
require 'camping'
require 'camping/session'
Camping.goes :YourApp
module YourApp
include Camping::Session
end
From here, your Models, Controllers, Views, Helpers, etc in this file, or in separate files.