Sha256: 27c7d31975bc6d29b358a6a86a05d082c94b43185bef0e8adcd6e1b179e7bae8

Contents?: true

Size: 1.55 KB

Versions: 2

Compression:

Stored size: 1.55 KB

Contents

require "stackable_flash/flash_stack"

module StackableFlash
  module StackLayer
    def self.included(base)
      base.send(:alias_method_chain, "[]=", "stacking")
    end

    define_method "[]_with_stacking=" do |key, value|
      if StackableFlash.stacking
        # Do it in a non-stacking block so we get normal behavior from flash[:notice] calls
        StackableFlash.not_stacked do
          # Make an array at the key, while providing a seamless upgrade to existing flashes
          #
          # Initial set to Array
          #
          # Principle of least surprise
          # flash[:notice] = ['message1','message2']
          # flash[:notice] # => ['message1','message2']
          #
          # Initial set to String
          #
          # Principle of least surprise
          # flash[:notice] = 'original'
          # flash[:notice] # => ['original']
          #
          # Overwrite!
          #
          # Principle of least surprise
          # flash[:notice] = 'original'
          # flash[:notice] = 'altered'
          # flash[:notice] # => ['altered']
          #
          # The same line of code does all of the above:
          self[key] = StackableFlash::FlashStack.new.replace(value.kind_of?(Array) ? value : Array(value))

          # Leave existing behavior in place, but send the full array as the value so it doesn't get killed.
          send("[]_without_stacking=", key, self[key])
        end
      else
        # All StackableFlash functionality is completely bypassed
        send("[]_without_stacking=", key, value)
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
stackable_flash-0.0.2 lib/stackable_flash/stack_layer.rb
stackable_flash-0.0.1 lib/stackable_flash/stack_layer.rb