Module: ShowMessage::ViewHelpers

Defined in:
lib/show_message/view_helpers.rb

Instance Method Summary collapse

Instance Method Details

#show_message(options_or_ids = nil, options = nil) ⇒ Object

render the applicable messages

Parameters:

  • options_or_ids (defaults to: nil)

    options or the ids to target

  • options (defaults to: nil)

    options for the view



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
# File 'lib/show_message/view_helpers.rb', line 8

def show_message(options_or_ids = nil, options = nil)
  if options_or_ids.is_a?(Hash)
    display_ids = []
    options = options_or_ids
  else
    display_ids = options_or_ids
    options ||= {}
  end

  display_ids = display_ids.is_a?(Array) ? display_ids : [display_ids]
  display_ids = display_ids.compact.map(&:to_s)
  # target all messages if no target is specified
  display_ids.push('all') if display_ids.empty?

  data = []
  message_keys = %w(success error warning info notice alert)

  flash.to_h.slice(*message_keys).each do |key, message_hash|
    # support basic usage of flash[:success] or flash[:error] which
    # would normally just return a string
    if message_hash.is_a?(Hash)
      message_hash.each do |id, messages|
        next unless display_ids.include?('all') || display_ids.include?(id)

        build_data(data, messages, key)
      end
    else
      next unless display_ids.include?('all')

      build_data(data, message_hash, key)
    end

    flash.discard(key)
  end

  render partial: 'show_message/show_message', locals: {
    data: data, options: options
  }
end