Sha256: 429d6e23846686722e4dd596e7ae55a06f7801b03033ddd760a211c565d71a89

Contents?: true

Size: 1013 Bytes

Versions: 8

Compression:

Stored size: 1013 Bytes

Contents

require "document/enum"
require "age_calculator"

module Renalware
  class Age < NestedAttribute
    AGE_IN_MONTHS_THRESHOLD = 3 # If below this number of years, age must be in months

    attribute :amount, Integer
    attribute :unit, Document::Enum, enums: %i(years months)

    validate :validate_unit

    def self.age_in_months_threshold
      AGE_IN_MONTHS_THRESHOLD
    end

    def self.new_from(years:, months:, **)
      new.tap do |age|
        if years && months
          if years < age_in_months_threshold
            age.amount = years * 12 + months
            age.unit = :months
          else
            age.amount = years
            age.unit = :years
          end
        end
      end
    end

    def to_s
      amount.present? ? "#{amount} #{unit.try(:text)}" : ""
    end

    private

    def validate_unit
      return unless amount.present?

      if amount < Age.age_in_months_threshold && unit.to_sym != :months
        errors.add(:unit, :invalid_unit)
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
renalware-core-2.0.0.pre.beta11 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.beta10 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.beta9 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.beta8 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.beta7 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.beta6 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.beta5 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.beta4 app/documents/renalware/age.rb