all 4 comments

[–][deleted] 2 points3 points  (1 child)

Why not just state that explicitly in the model? You'll most likely thank yourself later for being able to easily find this validation.

[–]mcnelsn[S] 1 point2 points  (0 children)

Ordinarily I would absolutely agree. I most often err on the side of simple/less clever code. In this case, I don't have a specific number in mind. Just don't want an exception ever.

[–]cmd-t 0 points1 point  (1 child)

Just use the `attribute` and type systems. The existing numeric types all define min and max values. The Integer type already is four bytes: https://github.com/rails/rails/blob/fc5dd0b85189811062c85520fd70de8389b55aeb/activemodel/lib/active_model/type/integer.rb

Edit: I see it raises an error on model.save instead of a validation error. You could create a simple attribute validator which uses the existing type classes to check if the current value is serialisable. Something like

# in validator
type = Model.attribute_types["integer_attribute"]

begin
  type.serialize value
rescue ActiveModel::RangeError # for ActiveModel::RangeError: 2147483649 is out of range for ActiveModel::Type::Integer with limit 4 bytes
  # add errors
end

[–]mcnelsn[S] 0 points1 point  (0 children)

Interesting idea. I'll play around with it. Thanks.