Shopify / measured-rails

Rails adapter for the measured gem. Encapsulate measurements and their units in Ruby and Rails.
MIT License
92 stars 13 forks source link

Add numericality validator options to measured #4

Closed cyprusad closed 9 years ago

cyprusad commented 9 years ago

@Shopify/shipping

Adds numericality validations on the measured fields to support numerical comparisons like <, ==, >, <=, >= as you'd expect. We can now validate measured fields in the model to be within certain pre-set bounds. Differences in units while doing bound validation checks also works. You can also set custom validation error messages for failing validations.

For example, you can set a measured field called length in your model and create validations for it like,

measured_length :length
validates :length, measured: {greater_than: Measured::Length.new(3, :m), less_than: Measured::Length.new(500, :cm), message: "Custom validation error message"}

Validating against non-Measured fields raises an error. You can also pass Procs while valdiating

measured_length :length
validates :length, measured: {equal_to: "Not a length"}
measured_length :length
validates :length, measured: {equal_to: Proc.new { Measured::Length.new(100, :cm) }}
kmcphillips commented 9 years ago

I would love to see support for 0 as a number, because it's a special case where a unit doesn't matter.

validates :length, measured: { greater_than: 0 }

You can do that in a separate PR though.

cyprusad commented 9 years ago

I am thinking I'll deal with the 0 case as well as a special check for FixNum both in a separate PR.

kmcphillips commented 9 years ago

Great