Module: SimplyMessages::ActionViewExtension::InstanceMethods

Defined in:
lib/simply_messages/action_view_extension.rb

Instance Method Summary collapse

Instance Method Details

#messages_block(options = {}) ⇒ Object



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
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/simply_messages/action_view_extension.rb', line 9

def messages_block(options = {})
  # make options[:for] an array
  options[:for] ||= []
  options[:for] = [options[:for]] unless options[:for].is_a?(Array)

  # add model object associated with current controller
  options[:for] << controller.controller_name.split('/').last.gsub(/\_controller$/, '').singularize.to_sym

  # fetch all model objects
  model_objects = options[:for].map do |model_object|
    if model_object.instance_of?(String) or model_object.instance_of?(Symbol)
      instance_variable_get("@#{model_object}")
    else
      model_object
    end
  end.select { |m| m.present? }.uniq

  # messages_block
  messages_block = ''

  # notice/success
  flash_msg = ''
  [:notice, :success].each do |key|
    if flash[key].present?
      flash_msg += (:p, flash[key])
      messages_block += (:div, flash_msg.html_safe, :class => key.to_s)
    end
  end

  # alert/error
  flash_msg = ''
  html_class = ''
  [:alert, :error].each do |key|
    if flash[key].present?
      flash_msg += (:p, flash[key])
      html_class += key.to_s
    end
  end

  # all models errors
  errors = ''
  model_objects.each do |model|
    if model.errors.any?
      errors += (:p, I18n.translate(
        model.errors.count > 1 ? :other : :one,
        :count => model.errors.count,
        :model => model.class.model_name.human,
        :scope => [:activerecord, :errors, :template, :header]) + ':')

      msg = ''
      model.errors.full_messages.each do |e|
        msg += (:li, e)
      end
      errors += (:ul, msg.html_safe)
    end
  end

  if flash_msg.present? or errors.present?
    messages_block += (:div, flash_msg.html_safe + errors.html_safe, :class => (html_class.presence || 'alert'))
  end

  messages_block.html_safe
end