Module: GovukPersonalisation::Flash

Defined in:
lib/govuk_personalisation/flash.rb

Constant Summary collapse

SESSION_SEPARATOR =
"$$"
MESSAGE_SEPARATOR =
","
MESSAGE_REGEX =
/\A[a-zA-Z0-9._\-]+\z/.freeze

Class Method Summary collapse

Class Method Details

.decode_session(encoded_session) ⇒ Array(String, Array<String>)?

Splits the session header into a session value (suitable for using in account-api calls) and flash messages.

Parameters:

  • encoded_session (String)

    the value of the ‘GOVUK-Account-Session` header

Returns:

  • (Array(String, Array<String>), nil)

    the session value and the flash messages



14
15
16
17
18
19
20
21
22
23
# File 'lib/govuk_personalisation/flash.rb', line 14

def self.decode_session(encoded_session)
  session_bits = encoded_session&.split(SESSION_SEPARATOR)
  return if session_bits.blank?

  if session_bits.length == 1
    [session_bits[0], []]
  else
    [session_bits[0], session_bits[1].split(MESSAGE_SEPARATOR)]
  end
end

.encode_session(session, flash) ⇒ String

Encodes the session value and a list of flash messages into a session header which can be returned to the user.

Parameters:

  • session (String)

    the session value

  • flash (Array<String>)

    the flash messages, which must all be ‘valid_message?`

Returns:

  • (String)

    the encoded session header value



32
33
34
35
36
37
38
# File 'lib/govuk_personalisation/flash.rb', line 32

def self.encode_session(session, flash)
  if flash.blank?
    session
  else
    "#{session}#{SESSION_SEPARATOR}#{flash.join(MESSAGE_SEPARATOR)}"
  end
end

.valid_message?(message) ⇒ true, false

Check if a string is valid as a flash message.

Parameters:

  • message (String, nil)

    the flash message

Returns:

  • (true, false)

    whether the message is valid or not.



45
46
47
48
49
# File 'lib/govuk_personalisation/flash.rb', line 45

def self.valid_message?(message)
  return false if message.nil?

  message.match? MESSAGE_REGEX
end