Class: StrongerParameters::DecimalConstraint

Inherits:
Constraint
  • Object
show all
Defined in:
lib/stronger_parameters/constraints/decimal_constraint.rb

Instance Method Summary collapse

Methods inherited from Constraint

#&, #==, #required, #required?, #|

Constructor Details

#initialize(precision, scale) ⇒ DecimalConstraint

Returns a new instance of DecimalConstraint.



6
7
8
9
10
# File 'lib/stronger_parameters/constraints/decimal_constraint.rb', line 6

def initialize(precision, scale)
  @precision = precision
  @scale = scale
  @regex = /\A-?\d{1,#{precision - scale}}#{"(\\.\\d{1,#{scale}})?" if scale > 0}\Z/
end

Instance Method Details

#value(v) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/stronger_parameters/constraints/decimal_constraint.rb', line 12

def value(v)
  match = v.to_s
  if match =~ @regex
    BigDecimal(match)
  else
    StrongerParameters::InvalidValue.new(v, "must be a decimal with precision #{@precision} and scale #{@scale}")
  end
end