class Rack::Flash::FlashHash
Implements bracket accessors for storing and retrieving flash entries.
Attributes
Public Class Methods
# File lib/rack/flash.rb, line 12 def initialize(store, opts={}) raise Rack::Flash::SessionUnavailable \ .new('Rack::Flash depends on session middleware.') unless store @opts = opts @store = store if accessors = @opts[:accessorize] accessors.each { |opt| def_accessor(opt) } end end
Public Instance Methods
Remove an entry from the session and return its value. Cache result in the instance cache.
# File lib/rack/flash.rb, line 26 def [](key) key = key.to_s cache[key] ||= values.delete(key) end
Store the entry in the session, updating the instance cache as well.
# File lib/rack/flash.rb, line 32 def []=(key,val) key = key.to_s cache[key] = values[key] = val end
Mark existing entries to allow for sweeping.
# File lib/rack/flash.rb, line 56 def flag! @flagged = values.keys end
Checks for the presence of a flash entry without retrieving or removing it from the cache or store.
# File lib/rack/flash.rb, line 46 def has?(key) [cache, values].any? { |store| store.keys.include?(key.to_s) } end
Hide the underlying :__FLASH__ session key and only expose values stored in the flash.
# File lib/rack/flash.rb, line 68 def inspect '#<FlashHash @values=%s @cache=%s>' % [values.inspect, cache.inspect] end
# File lib/rack/flash.rb, line 51 def keys cache.keys | values.keys end
Store a flash entry for only the current request, swept regardless of whether or not it was actually accessed. Useful for AJAX requests, where you want a flash message, even though you're response isn't redirecting.
# File lib/rack/flash.rb, line 40 def now cache end
Remove flagged entries from flash session, clear flagged list.
# File lib/rack/flash.rb, line 61 def sweep! Array(flagged).each { |key| values.delete(key) } flagged.clear end
Human readable for logging.
# File lib/rack/flash.rb, line 73 def to_s values.inspect end
Private Instance Methods
Maintain an instance-level cache of retrieved flash entries. These entries will have been removed from the session, but are still available through the cache.
# File lib/rack/flash.rb, line 82 def cache @cache ||= {} end
Generate accessor methods for the given entry key if :accessorize is true.
# File lib/rack/flash.rb, line 93 def def_accessor(key) raise ArgumentError.new('Invalid entry type: %s' % key) if respond_to?(key) class << self; self end.class_eval do define_method(key) { |*args| val = args.first; val ? (self[key]=val) : self[key] } define_method("#{key}=") { |val| self[key] = val } define_method("#{key}!") { |val| cache[key] = val } end end
Helper to access flash entries from :__FLASH__ session value. This key is used to prevent collisions with other user-defined session values.
# File lib/rack/flash.rb, line 88 def values @store[:__FLASH__] ||= {} end