1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/actionpack/lib/action_controller/metal/flash.rb

62 lines
1.7 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
module ActionController #:nodoc:
module Flash
extend ActiveSupport::Concern
included do
class_attribute :_flash_types, instance_accessor: false, default: []
2012-07-06 14:34:56 -04:00
delegate :flash, to: :request
2012-07-06 14:34:56 -04:00
add_flash_types(:alert, :notice)
end
2012-07-06 14:34:56 -04:00
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.
2012-07-06 14:34:56 -04:00
def add_flash_types(*types)
types.each do |type|
next if _flash_types.include?(type)
define_method(type) do
request.flash[type]
2012-07-06 14:34:56 -04:00
end
helper_method(type) if respond_to?(:helper_method)
2012-07-06 14:34:56 -04:00
self._flash_types += [type]
end
2012-07-06 14:34:56 -04:00
end
end
private
def redirect_to(options = {}, response_options_and_flash = {}) #:doc:
2012-07-06 14:34:56 -04:00
self.class._flash_types.each do |flash_type|
if type = response_options_and_flash.delete(flash_type)
2012-07-06 14:34:56 -04:00
flash[flash_type] = type
end
end
if other_flashes = response_options_and_flash.delete(:flash)
flash.update(other_flashes)
end
super(options, response_options_and_flash)
end
end
end