Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamic conversions #151

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Conversation

AlexB52
Copy link

@AlexB52 AlexB52 commented May 7, 2023

This PR attempts to solve #59 by allowing dynamic unit system definitions.

Current unit system definitions assume units are all proportional to each other y = a * x. This change allows any conversion but removes the ability to cache dynamic unit systems, which might be good enough for small ones.

You can create dynamic systems by passing a conversion and a reverse_conversion proc and an optional conversion description. Please take a look at the Temperature example below. The PR also has temperature acceptance tests as proof of concept.

Notes:

  • Trying to use a cache on a dynamic unit system will raise.
  • Current behaviour and caching are preserved in systems with no dynamic units.
Measured::Temperature = Measured.build do
  unit :C, aliases: [:c, :celsius]

  unit :K, value: [
    {
      conversion: ->(k) { k - BigDecimal('273.15') },
      reverse_conversion: ->(c) { c + BigDecimal('273.15') },
      description: 'celsius + 273.15'
    }, 'C'], aliases: [:k, :kelvin]

  unit :F, value: [
    {
      conversion: ->(f) { (f-32) * Rational(5,9) },
      reverse_conversion: ->(c) { c * Rational(9,5) + 32 },
      description: '9 * celsius / 5 + 32'
    }, 'C'], aliases: [:f, :farenheit]
end

AlexB52 added 5 commits May 11, 2023 08:48
  * Allow reverse_conversion & conversion procs as value
  * Extract UnitConversion into Dynamic and Static classes
  * Test dynamic conversion from Unit class
@AlexB52 AlexB52 force-pushed the dynamic-conversion branch from 793e768 to f01b652 Compare May 10, 2023 20:49
@AlexB52 AlexB52 changed the title Dynamic conversion Dynamic conversions May 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant