Class: RubyUnitValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/ruby_unit_validator.rb

Overview

Validates that a value names a unit supported by the RubyUnits gem.

Instance Method Summary collapse

Instance Method Details

#validate_each(object, attribute, value) ⇒ void

This method returns an undefined value.

Validates a single attribute value (or each element of an array) as a RubyUnits unit.

Parameters:

  • object (ActiveModel::Model)

    the record being validated

  • attribute (Symbol)

    the attribute name

  • value (String, Array<String>, nil)

    the unit name(s) to validate



11
12
13
14
15
16
17
# File 'app/validators/ruby_unit_validator.rb', line 11

def validate_each(object, attribute, value)
  [value].flatten.filter_map(&:presence).each do |v|
    RubyUnits::Unit.new("1 #{v}")
  rescue ArgumentError
    object.errors.add(attribute.to_sym, (options[:message] || "#{v} is not a supported unit"))
  end
end