DEV Community

haroldus-
haroldus-

Posted on

How to use Rails validators out of context

Why reinvent the wheel?

ActiveModel::Validations::NumericalityValidator.new(attributes: [nil]).send(:is_number?, "666", Float::DIG, nil)

=> true

ActiveModel::Validations::NumericalityValidator.new(attributes: [nil]).send(:is_number?, "meh", Float::DIG, nil)

=> false
Enter fullscreen mode Exit fullscreen mode

Now it is possible to validate, for example, a nested JSON value before storing it on a JSON column.

# app/models/amendment.rb
class Amendment > ApplicationRecord

  store_accessor :amendments, :clauses

  validate :amendments_validation

  private

  def amendments_validation
    if self.clauses.present?
      if self.clauses["price"].present?
        errors.add(:clauses, "price is not a number") unless ActiveModel::Validations::NumericalityValidator.new(attributes:[nil]).send(:is_number?, self.clauses["price"], Float::DIG, nil)
      end
    end
  end

end
Enter fullscreen mode Exit fullscreen mode

Discussion (0)