aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/lib/action_controller/metal/flash.rb
blob: e0708a9421afe812264c43779095c0a0d8cc405e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# frozen_string_literal: true
module ActionController #:nodoc:
  module Flash
    extend ActiveSupport::Concern

    included do
      class_attribute :_flash_types, instance_accessor: false, default: []

      delegate :flash, to: :request
      add_flash_types(:alert, :notice)
    end

    module ClassMethods
      # Creates new flash types. You can pass as many types as you want to create
      # flash types other than the default <tt>alert</tt> and <tt>notice</tt> in
      # your controllers and views. For instance:
      #
      #   # in application_controller.rb
      #   class ApplicationController < ActionController::Base
      #     add_flash_types :warning
      #   end
      #
      #   # in your controller
      #   redirect_to user_path(@user), warning: "Incomplete profile"
      #
      #   # in your view
      #   <%= warning %>
      #
      # This method will automatically define a new method for each of the given
      # names, and it will be available in your views.
      def add_flash_types(*types)
        types.each do |type|
          next if _flash_types.include?(type)

          define_method(type) do
            request.flash[type]
          end
          helper_method type

          self._flash_types += [type]
        end
      end
    end

    private
      def redirect_to(options = {}, response_status_and_flash = {}) #:doc:
        self.class._flash_types.each do |flash_type|
          if type = response_status_and_flash.delete(flash_type)
            flash[flash_type] = type
          end
        end

        if other_flashes = response_status_and_flash.delete(:flash)
          flash.update(other_flashes)
        end

        super(options, response_status_and_flash)
      end
  end
end