I like my models to be printed nicely, to make the class of the model as well as the id and other data available, so, when they end up in a log or console, I can now exactly what it is. I’ve been doing this since before Rails 3 and since Rails projects now have an ApplicationRecord
class, it’s even easier.
On my global parent for all model classes, ApplicationRecord
I add this:
def to_s(extra = nil) if extra extra = ":#{extra}" end "#<#{self.class.name}:#{id}#{extra}>" end
That makes all records automatically print as:
<ModelName:id>
For example:
<User:123>
which makes the record findable.
But also, allows the sub-classes to add a bit of extra information without having to re-specify the whole format. For example, for the User
class, it might be:
def to_s super(email) end
so that when the user gets printed, it ends up being:
<User:123:sam@example.com>
which I found helps a lot with quickly debugging issues, in production as well as development environments.
Hey!
Neat trick, I’ve done something similar but never in AR models.
I would suggest using `#inspect` though. `#to_s` may unintentionally end up somewhere in production frontend (through interpolation) and expose something we don’t want to (like a personal email). `#inspect` I *think* should be picked up by repls (irb, pry) automatically and can be used for logging through `puts user.inspect`
Hey!
Neat trick, I’ve done something similar but never in AR models.
I would suggest using `#inspect` though. `#to_s` may unintentionally end up somewhere in production frontend (through interpolation) and expose something we don’t want to (like a personal email). `#inspect` I *think* should be picked up by repls (irb, pry) automatically and can be used for logging through `puts user.inspect`