Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors like "NoMethodError: undefined method `sweep' for #<Hash …" after downgrading to Rails 3 from Rails 4

We upgraded to Rails 4, had some major issues and downgraded again (reverted the upgrade commit).

We then got errors like

NoMethodError (undefined method `sweep' for #<Hash:0x007f01ab44a940>):

seemingly because Rails 4 stores a flash in the session in a way that Rails 3 can't read.

What is a good way to solve this?

like image 778
Henrik N Avatar asked Jun 18 '15 13:06

Henrik N


2 Answers

We ended up solving this by patching Rails itself to catch this error and delete the borked flash. This means that it self-heals quite transparently.

We also made sure to only apply this patch on Rails 3, so it doesn't cause issues when we make another attempt at upgrading to Rails 4.

We stuck this in config/initializers/rails4_to_rails3_downgradability.rb:

if Rails::VERSION::MAJOR == 3

  module ActionDispatch
    class Flash
      def call(env)
        if (session = env['rack.session']) && (flash = session['flash'])

          # Beginning of change!

          if flash.respond_to?(:sweep)
            flash.sweep
          else
            session.delete("flash")
          end

          # End of change!

        end

        @app.call(env)
      ensure
        session    = env['rack.session'] || {}
        flash_hash = env[KEY]

        if flash_hash
          if !flash_hash.empty? || session.key?('flash')
            session["flash"] = flash_hash
            new_hash = flash_hash.dup
          else
            new_hash = flash_hash
          end

          env[KEY] = new_hash
        end

        if session.key?('flash') && session['flash'].empty?
          session.delete('flash')
        end
      end
    end
  end

end
like image 193
Henrik N Avatar answered Nov 06 '22 12:11

Henrik N


Faced the same issue, resolved by telling users to clear cookies. Might not a solution for everyone, just pointing out that it's an option.

like image 7
Swaroop Avatar answered Nov 06 '22 12:11

Swaroop