Skip to content

Instantly share code, notes, and snippets.

@raj454raj
Last active May 20, 2020 09:19
Show Gist options
  • Save raj454raj/53dc18d1dad3e6bfe925778df6100505 to your computer and use it in GitHub Desktop.
Save raj454raj/53dc18d1dad3e6bfe925778df6100505 to your computer and use it in GitHub Desktop.
FlashHash override in Rails 3.0.20 code to support flashes created in Rails 3.2.22 (https://raj454raj.wordpress.com/2016/08/13/flashhash-issue-rails-upgrade/)
# This patch handles both types of flashes that are created in
# Rails 3.2.22 as well as those created in Rails 3.0.20
ActiveRecord::SessionStore::Session.class_eval do
def self.unmarshal(data)
return unless data
marshalled = nil
begin
decoded = ::Base64.decode64 data
marshalled = Marshal.load decoded
rescue ArgumentError => ae
if ae.message =~ /dump format error/
with_alternate_flash_klass do
marshalled = Marshal.load decoded
end
if marshalled['flash']
new_flash = ActionDispatch::Flash::FlashHash.new
flash_message = marshalled['flash'].instance_variable_get('@flashes')
flash_message.each { |k, v| new_flash[k] = v } if flash_message
used = marshalled['flash'].instance_variable_get('@used')
new_flash.instance_variable_set('@used', used) if used
# FlashHash object created in Rails 3.2 unparsed to support Rails 3.0 behavior
marshalled['flash'] = new_flash
end
else
raise ae
end
end
marshalled
end
def self.alternate_flash_klass
if ActionDispatch::Flash::FlashHash.ancestors.include? Hash
Class.new() do # Rails 3.2 FlashHash
def initialize
@used = Set.new
@closed = false
@flashes = {}
@now = nil
end
end
else
Class.new(Hash) do # Rails 3.0 FlashHash
def initialize
super
@used = Set.new
end
end
end
end
def self.with_alternate_flash_klass
temporary_flash_hash_klass = alternate_flash_klass
original_flash_hash_klass = ActionDispatch::Flash::FlashHash
ActionDispatch::Flash.send :remove_const, :FlashHash
ActionDispatch::Flash.const_set 'FlashHash', temporary_flash_hash_klass
yield
ActionDispatch::Flash.send :remove_const, :FlashHash
ActionDispatch::Flash.const_set 'FlashHash', original_flash_hash_klass
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment