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 the validate 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 not changed but rather provided. Or is this merely semantic and is changed? 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.

有帮助吗?

解决方案

You could test whether the params are present like so: params[:param_name].present?

The present? method (inverse of blank?) tests for empty? but also returns false for whitespace so that '', ' ', nil, [], and {} are all false.

An improvement on this would be to use the presence method. Then you could do this directly in your controller method without the need for callbacks:

fqdn = params[:fqdn].presence || MyRandomNameGenerator.generate
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top