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.

Use capitalized keys to denote system variables. Reserve lower case keys for user application variables.

Instance Method Summary collapse

Constructor Details

#initializeFlash

Returns a new instance of Flash.



28
29
30
31
# File 'lib/nitro/flash.rb', line 28

def initialize
  super
  @dirty = {}
end

Instance Method Details

#[]=(key, val) ⇒ Object



33
34
35
36
# File 'lib/nitro/flash.rb', line 33

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

#cleanObject

:nodoc:



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/nitro/flash.rb', line 50

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

#concat(key, arr) ⇒ Object

Another helper, concats a whole array to the given flash key.



103
104
105
106
107
# File 'lib/nitro/flash.rb', line 103

def concat(key, arr)
  for val in arr.to_a
    push key, val
  end
end

#discard(key = nil) ⇒ Object

Discard the specific key or the whole Flash.



46
47
48
# File 'lib/nitro/flash.rb', line 46

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

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

Join helper



111
112
113
114
115
116
117
118
119
# File 'lib/nitro/flash.rb', line 111

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.



40
41
42
# File 'lib/nitro/flash.rb', line 40

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

#pop(key) ⇒ Object

Pop a value from an array flash variable.



89
90
91
92
93
94
95
96
97
98
# File 'lib/nitro/flash.rb', line 89

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, *values) ⇒ 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 # => []



76
77
78
79
80
81
82
83
84
85
# File 'lib/nitro/flash.rb', line 76

def push(key, *values)
  val = self[key]
  val ||= []
  if values.size == 1
    val << values[0]
  else
    val << values
  end
  self[key] = val
end