Class: Nitro::Flashing::Flash

Inherits:
Hash
  • Object
show all
Defined in:
lib/nitro/flash.rb

Overview

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.

Instance Method Summary collapse

Constructor Details

#initializeFlash



25
26
27
28
# File 'lib/nitro/flash.rb', line 25

def initialize
  super
  @dirty = {}
end

Instance Method Details

#[]=(key, val) ⇒ Object



30
31
32
33
# File 'lib/nitro/flash.rb', line 30

def []=(key, val)
  super
  keep(key)
end

#cleanObject

:nodoc:



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/nitro/flash.rb', line 47

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

#discard(key = nil) ⇒ Object

Discard the specific key or the whole Flash.



43
44
45
# File 'lib/nitro/flash.rb', line 43

def discard(key = nil)
  set_dirty(key)
end

#join(key, sep = ', ') ⇒ Object

Join helper



96
97
98
99
100
101
102
103
104
# File 'lib/nitro/flash.rb', line 96

def join(key, sep = ', ')
  value = self[key]
  
  if value.is_a? Array
    return value.join(sep)
  else
    return value
  end
end

#keep(key = nil) ⇒ Object

Keep the specific key or the whole Flash.



37
38
39
# File 'lib/nitro/flash.rb', line 37

def keep(key = nil)
  set_dirty(key, false)
end

#pop(key) ⇒ Object

Pop a value from an array flash variable.



83
84
85
86
87
88
89
90
91
92
# File 'lib/nitro/flash.rb', line 83

def pop(key)
  if arr = self[key]
    if arr.is_a? Array
      return arr.pop
    else
      return arr
    end
  end
  return nil
end

#push(key, value) ⇒ Object

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 # => []



73
74
75
76
77
78
79
# File 'lib/nitro/flash.rb', line 73

def push(key, value)
  if value.is_a? Array
    (self[key] ||= []).concat(value)
  else
    (self[key] ||= []) << value
  end
end