Skip to content

Instantly share code, notes, and snippets.

@keeran
Last active October 7, 2021 17:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keeran/a9367045abea89557c2006e3bedad9f2 to your computer and use it in GitHub Desktop.
Save keeran/a9367045abea89557c2006e3bedad9f2 to your computer and use it in GitHub Desktop.

Migrating from Marginalia

ActiveRecord ships with the same default configuration as Marginalia. For basic use, enable the feature in your application configuration:

# config/application.rb
module MyApp
  class Application < Rails::Application
    config.active_record.query_log_tags_enabled = true
  end
end

For a more involved configuration query log tags operate in a similar way to Marginalia, but instead of defining new methods to be called at runtime you pass Procs to the configuration:

# config/application.rb
module MyApp
  class Application < Rails::Application
    config.active_record.query_log_tags = [
      :application,
      { 
        custom_tag: -> { "Custom content here" }
      }
    ]
  end
end

Instead of referring to marginalia_controller, any object can be stored in the context and then referenced in a tag definition. The default configuration will set the context with controller & job as appropriate.

class MyController < ApplicationController
  def controller_info
    "custom_information"
  end
end

ActiveRecord::QueryLogs.update_context(server: "server_name")
ActiveRecord::QueryLogs.tags = [
  controller_info: -> { context[:controller]&.controller_info }, 
  server: -> { context[:server] }
]
# /*controller_info:custom_information,server:server_name*/

To reset or update the value of the comment context, use #update_context:

ActiveRecord::QueryLogs.update_context(controller: nil)
ActiveRecord::QueryLogs.update_context(server: "new server name”)

Inline annotations can be added to any queries during block execution:

before:

Marginalia.with_annotation("foo") do
  Account.where(id: 1234567890).first
end

after:

ActiveRecord::QueryLogs.with_tag("foo") do
  Account.where(id: 1234567890).first
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment