Skip to content

Instantly share code, notes, and snippets.

@herenow
Last active December 2, 2017 02:39
Show Gist options
  • Save herenow/fd81af33edb3c3bfc75c44101b02c19a to your computer and use it in GitHub Desktop.
Save herenow/fd81af33edb3c3bfc75c44101b02c19a to your computer and use it in GitHub Desktop.
ApplicationRecord (model) debug_id method
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
# Returns a string to be used in log messages.
# Concats the object's class name w/ it's id, so we can easely
# identify and search for the object in log messages.
#
# Example:
#
# user = User.new(id: 25)
# logger.info "Failed to save #{user.debug_id}"
# => "Failed to save User#25"
def debug_id
object_id = self.persisted? ? self.id : 'new'
"#{self.class.name}##{object_id}"
end
end
@herenow
Copy link
Author

herenow commented Dec 2, 2017

This method is specially useful for displaying the object's id in log
messages.

It will return the object's class name w/ its id.

It makes the object easily identifiable and searchable, without having
to always manually log what object we are logging.

Usage example:

user = User.new(id: 25)
logger.info "Failed to save #{user.debug_id}"
=> "Failed to save User#25"

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