module Nitro #-- # This module adds flashing support to the Controllers. #++ module Flashing def self.append_features(base) super base.before 'flash.discard' #base.after 'flash.clean' end # A Flash is a special hash object that lives in the session. # The values stored in the Flash are typically maintained # for the duration of one request. After the request is over, # the Hash is cleared. # # You may want to use the Flash to pass error messages or # other short lived objects. class Flash < Hash def initialize super @dirty = {} end def []=(key, val) super keep(key) end # Keep the specific key or the whole Flash. def keep(key = nil) set_dirty(key, false) end # Discard the specific key or the whole Flash. def discard(key = nil) set_dirty(key) end def clean # :nodoc: keys.each do |k| unless @dirty[k] set_dirty(k) else delete(k) @dirty.delete(k) end end # remove externaly updated keys. (@dirty.keys - keys).each { |k| @dirty.delete k } end # :section: Helpers # Push a value in an array flash variable. # # === Example # # flash.push :errors, 'This is the first error' # flash.push :errors, 'This is the second error' # # flash[:errors] # => [] def push(key, value) if value.is_a? Array (self[key] ||= []).concat(value) else (self[key] ||= []) << value end end # Pop a value from an array flash variable. def pop(key) if arr = self[key] if arr.is_a? Array return arr.pop else return arr end end return nil end # Join helper def join(key, sep = ', ') value = self[key] if value.is_a? Array return value.join(sep) else return value end end private def set_dirty(key = nil, flag = true) if key @dirty[key] = flag else keys.each { |k| @dirty[k] = flag } end end end # A Flash for the current request only. #-- # gmosx: crap, not really needed! #++ class FlashNow end private def flash session[:FLASH] ||= Flash.new end # Some useful aspects. # Marks flash entries as used and expose the flash to the # view. def init_flash flash.discard end # Deletes the flash entries that were not marked for # keeping. def clean_flash flash.clean end end end # * George Moschovitis