I have a lot places where the following pattern emerges. The case is that I need to prefill an attribute with "random" information, unless it is provided by a consumer of the Model.
class Server
validates :fqdn, presence: true
before_validation prefill_fqdn, if: :must_prefill_fqdn?
private
def must_prefill_fqdn?
#what best to check against?
end
def prefill_fqdn
self.fqdn = MyRandomNameGenerator.generate
end
end
I am looking for what to check against:
nil?
is rather limited and excludes values like""
. It checks if it is nil, not whether it was set by a consumer.empty?
catches more, but still does not match the requirement of "unless provided by the consumer", what if a user provides""
? It also renders thevalidate presence: true
pretty much useless: it will never be invalid.fqdn_changed?
seems to match best, but its name and parent class (ActiveModel::Dirty
suggests that this is not the proper test either. It is notchanged
but ratherprovided
. Or is this merely semantic and ischanged?
the proper helper here?
So, what is the best test to see "if a consumer provided an attribute".
Providing can be either in Server.new(fqdn: 'example.com')
(or
create
or build
. Or through one of the attribute-helpers, such as
fqdn=
or update_attribute(:fqdn, 'example.com')
and so on.