Unit Measurements Rails
A Rails adaptor that encapsulate measurements and their units in Ruby on Rails.
This gem is designed as a Rails integration for the unit_measurements gem.
It provides an
ActiveRecord adapter for persisting and retrieving measurements along with their units, simplifying complex
measurement handling within your Rails applications.
unit_measurements-rails in your Rails application, add the following line to your Gemfile:
And then execute:
$ bundle install
Or otherwise simply install it yourself as:
$ gem install unit_measurements-rails
This gem provides an ActiveRecord integration allowing you to declare measurement attributes with their corresponding units in your database schema:
class CreateCubes < ActiveRecord::Migration[7.0] def change create_table :cubes do |t| t.decimal :length_quantity, precision: 10, scale: 2 t.string :length_unit, limit: 12 t.timestamps end end end
Next, declare an atribute as measurement using
measured with its associated unit
class Cube < ActiveRecord::Base measured UnitMeasurements::Length, :length end
This setup allows you to access and assign measurement attributes conveniently:
cube = Cube.new cube.length = UnitMeasurements::Length.new(5, "ft") cube.length_quantity #=> 0.5e1 cube.length_unit #=> "ft" cube.length #=> 5.0 ft
You can specify multiple measurement attributes simultaneously:
class Cube < ActiveRecord::Base measured UnitMeasurements::Length, :length, :width end
Attribute names are expected to have the
_unit suffix, and be
VARCHAR types, respectively, and defaults values are accepted.
You can customize the model's quantity and unit accessors by specifying them in the
unit_attribute_name options, respectively.
class CubeWithCustomAccessor < ActiveRecord::Base measured_length :length, unit_attribute_name: :length_uom measured_length :width, quantity_attribute_name: :width_value end
For a more streamlined approach, predefined methods are available for commonly used
class Package < ActiveRecord::Base measured_length :size measured_area :carpet_area measured_volume :total_volume measured_weight :item_weight, :package_weight end
Contributions to this project are welcomed! To contribute:
- Fork this repository
- Create a new branch (
git checkout -b my-new-feature)
- Commit your changes (
git commit -am "Add some feature")
- Push the changes to your branch (
git push origin my-new-feature)
- Create new Pull Request
Copyright 2023 Harshal V. LADHE, Released under the MIT License.