Shopify / measured

Encapsulate measurements and their units in Ruby and Ruby on Rails.
MIT License
362 stars 28 forks source link

Add an alias to an existing unit #146

Closed kushagra-03 closed 1 year ago

kushagra-03 commented 2 years ago

Is there a way to add an extra alias to an existing unit? I wanted to add gm alias to Measured::Weight as an alias for grams. But don't see a straightforward way of accomplishing that.

Looks like I might have to skip all the units and then redefine them using Measured.build, which seems like quite some work to add an alias.

https://github.com/Shopify/measured/issues/146#tasklist-block-e4b8f6e7-6aa0-4dc9-abc7-f1f1ce63264d

kmcphillips commented 2 years ago

This is an interesting question! (sorry for slow response. I am on parental leave.)

I do not believe there is a way to reopen the measurements after they have been built. It builds and caches a whole tree of conversions that would need to be rebuilt on change. That's probably not a feature we are interested in implementing for a minority of cases.

So I would suggest one two things for you:

Option 1

Define your own Measured::Weight.

If you gem 'measured', require: 'measured/base' it will not include any of the units. Then you can include volume and whatever manually. But then define your own class in your project that is basically a copy of weight.rb but that adds your :gm alias. You'd need to skip the cache, or generate your own cache and commit that too. Without the cache you will incur a cost on each ruby process startup to build the tree of conversions.

Down sides to this approach is the performance hit, and that you have to maintain your own version. Not that the definition of weights really changes much. But this will work.

Option 2

PR to this repo to just add :gm to this line. I think that's a pretty reasonable alias and I would merge it.

Down sides to this approach isn't much. You'd need to PR it here and then use a github ref until we release this gem. I could probably do that in the next week, but again I am on leave.

Let me know what you think.

kushagra-03 commented 2 years ago

Thanks for the response, I think Option 2 makes more sense. Quick question though, do you think it makes sense to introduce this change?

si_unit :g, aliases: [:gram, :grams, :gm, :gms]

Just noticed the plural form as well.

I'll go ahead and open up a PR.

kmcphillips commented 2 years ago

Yep. Go for the plural. Tag me on the review for the PR, or if you have questions.

kmcphillips commented 1 year ago

Fixed in #147