Module: FlashTruncation
- Included in:
 - ApplicationController
 
- Defined in:
 - app/controllers/concerns/flash_truncation.rb
 
Overview
Module FlashTruncation provides the truncate_flash method to automatically trim long flash messages to prevent them from overflowing the cookie
Constant Summary collapse
- STRING_OVERHEAD =
          
Encoding a json string results in a two-byte overhead for the “ either side. Taking this into account is strictly unnecessary, as we've already got a bit of overhead built in, but lets keep things as predictable as possible.
 2
Instance Method Summary collapse
- 
  
    
      #max_flash_size  ⇒ Object 
    
    
  
  
  
  
  
  
  
  
  
    
The maximum cookie size is 4096 bytes, however this is post-encryption, which increases the size.
 - 
  
    
      #truncate_flash(message, max_size = max_flash_size)  ⇒ Array, String 
    
    
  
  
  
  
  
  
  
  
  
    
Truncates the flash message to avoid an ActionDispatch::Cookies::CookieOverflow.
 - 
  
    
      #truncate_flash_array(array, max_size = max_flash_size)  ⇒ Array 
    
    
  
  
  
  
  
  
  
  
  
    
Handles truncation of arrays passed to the flash.
 
Instance Method Details
#max_flash_size ⇒ Object
The maximum cookie size is 4096 bytes, however this is post-encryption, which increases the size. The value of 2048 was obtained by mapping the size of encrypted strings. In practice 2255 bytes was the largest size, but I rounded down to 2kb to provide a bit of overhead for array serialization, additional flash information to and allow for slight implementation changes.
      41 42 43  | 
    
      # File 'app/controllers/concerns/flash_truncation.rb', line 41 def max_flash_size 2048 - session.to_json.bytesize end  | 
  
#truncate_flash(message, max_size = max_flash_size) ⇒ Array, String
Truncates the flash message to avoid an ActionDispatch::Cookies::CookieOverflow. Maximum cookie size is checked against ActionDispatch::Cookies::MAX_COOKIE_SIZE which is 4096 bytes; however: - This is the size of the session cookie post encryption, which inflates the size - This cookie also needs to contain other data, such as the session_id, user_uuid and user_name
      26 27 28 29 30 31 32 33 34 35  | 
    
      # File 'app/controllers/concerns/flash_truncation.rb', line 26 def truncate_flash(, max_size = max_flash_size) return if .to_json.bytesize <= max_size case when String .truncate(max_size - STRING_OVERHEAD) when Array truncate_flash_array(, max_size) end end  | 
  
#truncate_flash_array(array, max_size = max_flash_size) ⇒ Array
Handles truncation of arrays passed to the flash. This is not intended to be used directly, instead use truncate_flash.
      54 55 56 57 58 59 60 61  | 
    
      # File 'app/controllers/concerns/flash_truncation.rb', line 54 def truncate_flash_array(array, max_size = max_flash_size) array.each_with_object([]) do |, | remaining = max_size - .to_json.bytesize return if remaining <= 0 << truncate_flash(, remaining) end end  |