Skip to content

Instantly share code, notes, and snippets.

@binarylogic
Last active September 21, 2017 00:01
Show Gist options
  • Select an option

  • Save binarylogic/f662e2635ffda0e43e751d543799d334 to your computer and use it in GitHub Desktop.

Select an option

Save binarylogic/f662e2635ffda0e43e751d543799d334 to your computer and use it in GitHub Desktop.
Timber Auth Example
class ApplicationController < ActionController::Base
# Make sure this is called *after* you authenticate users
around_filter :set_user_context
private
def set_user_context(&block)
if !current_user.nil?
# Ensure the attributes are mapped properly here
user_context = Timber::Contexts::User.new(id: current_user.id, email: current_user.email, name: current_user.full_name)
Timber.with_context(user_context, &block)
end
end
end
@mrsweaters
Copy link

I had to also add a yield outside of the with_context block as my methods would not render:

def set_user_context
  if !current_user.nil?
    user_context = Timber::Contexts::User.new(id: current_user.id, email: current_user.email, name: current_user.full_name)
    Timber.with_context(user_context) do
      yield
    end
  end

  yield
end

@binarylogic
Copy link
Author

@mrsweaters this is actually the correct syntax. Notice how I pass &block down. This is important because it ensures all of your logs get the user context. I've updated the example as well as our docs: https://timber.io/docs/languages/ruby/configuration/capture-user-context

def set_user_context(&block)
  if !current_user.nil?
    user_context = Timber::Contexts::User.new(id: current_user.id, email: current_user.email, name: current_user.full_name)
    Timber.with_context(user_context, &block)
  end
end

Thanks for your help!

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