Class: Pod4::Alert

Inherits:
Object
  • Object
show all
Defined in:
lib/pod4/alert.rb

Overview

An Alert is an error, warning or note which might be raised in validation in the model.

They are, however, designed to follow all the way through the controller to the view; you should use them whenever you want to display a message on the page.

Constant Summary collapse

ALERTTYPES =

Valid values for @type: :error, :warning, :info or :success

[:error, :warning, :info, :success]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, field = nil, message) ⇒ Alert

A new alert must have a type (error warning info or success); there should be a message to display, obviously. Note that you can pass an exception in place of a message, in which case You may optionally specify the name of the field to be highlighted. Models will give validation alerts a field that corresponds to the model attribute; but this is not enforced here, and your controller will have to sort things out if the model is expecting different field names.

Raises:

  • (ArgumentError)


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/pod4/alert.rb', line 38

def initialize(type, field=nil, message)
  raise ArgumentError, "unknown alert type" unless ALERTTYPES.include? type.to_s.to_sym

  @type      = type.to_s.to_sym
  @field     = field ? field.to_sym : nil
  @exception = nil

  if message.kind_of?(Exception)
    @exception = message.dup
    @message   = @exception.message

    # SwingShift validation exceptions hold the field name
    @field ||= @exception.field if @exception.respond_to?(:field)

  else
    @message = message

  end
end

Instance Attribute Details

#exceptionObject (readonly)

The exception attached to the alert, or nil if there isn’t one



19
20
21
# File 'lib/pod4/alert.rb', line 19

def exception
  @exception
end

#fieldObject

The field name associated with the alert, or nil



22
23
24
# File 'lib/pod4/alert.rb', line 22

def field
  @field
end

#messageObject

The alert message



25
26
27
# File 'lib/pod4/alert.rb', line 25

def message
  @message
end

#typeObject (readonly)

The alert type



16
17
18
# File 'lib/pod4/alert.rb', line 16

def type
  @type
end

Instance Method Details

#<=>(other) ⇒ Object

An array of Alert is automatically sorted into descending order of seriousness



62
63
64
# File 'lib/pod4/alert.rb', line 62

def <=>(other)
  ALERTTYPES.index(self.type) <=> ALERTTYPES.index(other.type)
end

#log(file = '') ⇒ Object

Write self to the log



70
71
72
73
74
75
76
77
78
# File 'lib/pod4/alert.rb', line 70

def log(file='')
  case self.type
    when :error   then Pod4.logger.error(file) { self.message }
    when :warning then Pod4.logger.warn(file)  { self.message }
    else Pod4.logger.info(file) { self.message }
  end

  self
end