Reputation: 19969
I would like to store some debug messages on an object as it can go through processing but I don't want to be storing this to the database. Is something like this a reasonable way, an instance variable wrapped in a method with a nil guard? Or is there a better way / pattern?
class Bid < ApplicationRecord
...
def debug_reasons
@debug_reasons ||= []
end
...
and then
bid.debug_reasons << "here is a reason"
Upvotes: 5
Views: 3417
Reputation: 33
I agree with Bustikiller that, for debugging purposes, logging the messages is a better option rather than changing your production code.
But, If you really need it, I would use the ruby attr_accessor
method rather than the ActiveRecord::Base.attribute method because the former doesn't expose an internal attribute as a model attribute.
The model attributes should be properties of the entity your model implements. A debug/internal method (such as #object_id and #to_s) should not be considered as an attribute and, therefore, they should not appear on attribute list (i.e. when you call #attributes
on a model instance). By using the .attribute
from ActiveRecord, you define debug_messages
as an attribute of Bid
which, I think, may not be an property of your Bid domain.
So, using the attr_accessor
you don't pollute the ActiveModel API with an internal/logic attribute.
Upvotes: 0
Reputation: 5363
What you're looking for is attribute
class Bid < ApplicationRecord
attribute :debug_reasons, :default => []
end
More info on attribute
http://api.rubyonrails.org/v5.0/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute
Upvotes: 10
Reputation: 2498
For debugging purposes I would use logging with the appropriate log level. This way the object behavior does not get messed up with the debugging.
In addition, the debug log level can (should) be disabled in production environments, but adding logic inside your models will not make it so easy.
Upvotes: 0