September 25 2020
Rails Tip: How to Insert Middleware First

During the first iteration of our cloud monitoring service, we deployed software that sent malformed data to it, so we needed to correct the data on the server, as the data came in. The JSON itself was misconstructed for certain objects, so we needed to fix the issue before Rails parsed it.

In application.rb, I added the following line to ensure our middleware was called before anything else, including Rack and Rails middleware:

module RailsApp
  class Application < Rails::Application
    # Insert custom middleware before everything else to rewrite JSON POSTs.

    # What did not work:
    # config.middleware.insert_before ActionDispatch::ParamsParser, "FixJsonParseError"
    # config.middleware.insert_before ActionDispatch::ShowExceptions, "FixJsonParseError"
    # config.middleware.use "FixJsonParseError"

    # What did work:
    config.middleware.insert_before 0, "FixJsonParseError"
Twelve years at Retrospect Rails Tip: Non-Database Attribute in ActiveRecord SQL Query
LinkedIn GitHub Email