Class: Cybertrain::Flash

Inherits:
Object
  • Object
show all
Defined in:
cybertrain/flash.rb

Overview

Rails-style flash: values set with []= are queued for the NEXT request (SessionStore persists them into the session, then the following request’s SessionStore loads them back as “current”); flash.now writes straight into the current values, visible only for this request.

Controller#flash in an action, flash in a template. Keys and values are Strings. A message shows on exactly the next request that is not a static file, then is gone.

Unlike Rails, flash[:notice] reads only the messages that arrived with this request: a value set with flash[:notice] = ... is not readable until the next one. There is no keep or discard.

Examples:

Before a redirect

flash[:notice] = "Article was successfully created."
redirect_to article_path(@article), status: :see_other

On the page being rendered now

flash.now[:alert] = "Could not save."
render :new, status: :unprocessable_entity

In the layout

<% if flash[:notice] %><p class="notice"><%= flash[:notice] %></p><% end %>

Instance Method Summary collapse

Instance Method Details

#[](key) ⇒ String?

A message that arrived with this request (or was set with #now).

Parameters:

  • key (String, Symbol)

Returns:

  • (String, nil)


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

def [](key)
  @current[key.to_s]
end

#[]=(key, value) ⇒ Object

Queues a message for the next request.

Parameters:

  • key (String, Symbol)
  • value (Object) —

    stored as value.to_s



45
46
47
48
49
# File 'cybertrain/flash.rb', line 45

def []=(key, value)
  k = key.to_s
  @queued_order << k unless @queued.key?(k)
  @queued[k] = value.to_s
end

#each {|key, message| ... } ⇒ Object

Yields this request’s messages in order.

Yield Parameters:

  • key (String)
  • message (String)


75
76
77
# File 'cybertrain/flash.rb', line 75

def each
  @current_order.each { |k| yield(k, @current[k]) }
end

#empty? ⇒ Boolean

Returns true when this request has no messages.

Returns:

  • (Boolean) —

    true when this request has no messages



67
68
69
# File 'cybertrain/flash.rb', line 67

def empty?
  @current_order.empty?
end

#keys ⇒ Array<String>

Returns the keys of this request’s messages, in order.

Returns:

  • (Array<String>) —

    the keys of this request’s messages, in order



61
62
63
# File 'cybertrain/flash.rb', line 61

def keys
  @current_order.dup
end

#now ⇒ FlashNow

The messages for this request: flash.now[:alert] = "..." shows on the page rendered now and is not kept.

Returns:



55
56
57
# File 'cybertrain/flash.rb', line 55

def now
  FlashNow.new(self)
end