Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save LucasBarretto86/29bceb6c6fe6cf3e776376dca42c8903 to your computer and use it in GitHub Desktop.
Save LucasBarretto86/29bceb6c6fe6cf3e776376dca42c8903 to your computer and use it in GitHub Desktop.
Current class and ActiveSupport::CurrentAttributes Basic Implementation

Current class and ActiveSupport::CurrentAttributes

CurrentAttributes came out on Rails 5.2 allow us to control session variables, follow steps bellow

Basic implementation for common usage

Create current.rb class

# frozen_string_literal: true

class Current < ActiveSupport::CurrentAttributes
  attribute :request_id, :user_agent, :ip_address, :user, :request
end

Create controller concern set_current_attributes.rb to load attributes

# frozen_string_literal: true

module SetCurrentAttributes
  extend ActiveSupport::Concern

  included do
    before_action do
      Current.request_id = request.uuid
      Current.user_agent = request.user_agent
      Current.ip_address = request.ip
      Current.request = request
    end
  end
end

Include concern to the application_controller.rb

class ApplicationController < ActionController::Base 
  include SetCurrentAttributes
end

Initializer implementation for Mailer usage

Since mailer preview uses Rails classes and itself is required to add initializer configs to be able to set data coming from session request

Basic implementation for mailer initializer config/initializers/action_mailer.rb

# frozen_string_literal: true

Rails.application.reloader.to_prepare do
  class Rails::MailersController
    before_action :set_current_request

    private

    def set_current_request
      Current.request = request
    end
  end
end

That will allow you to have all request with the mailers preview methods

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment