Sha256: 0795051a06a20518192c7ad46adf907e2af4a0c19a42e9bd773ca25f1172db7c

Contents?: true

Size: 1007 Bytes

Versions: 27

Compression:

Stored size: 1007 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 if amount.blank?

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

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
renalware-core-2.0.16 app/documents/renalware/age.rb
renalware-core-2.0.15 app/documents/renalware/age.rb
renalware-core-2.0.14 app/documents/renalware/age.rb
renalware-core-2.0.13 app/documents/renalware/age.rb
renalware-core-2.0.12 app/documents/renalware/age.rb
renalware-core-2.0.11 app/documents/renalware/age.rb
renalware-core-2.0.9 app/documents/renalware/age.rb
renalware-core-2.0.8 app/documents/renalware/age.rb
renalware-core-2.0.7 app/documents/renalware/age.rb
renalware-core-2.0.5 app/documents/renalware/age.rb
renalware-core-2.0.4 app/documents/renalware/age.rb
renalware-core-2.0.3 app/documents/renalware/age.rb
renalware-core-2.0.2 app/documents/renalware/age.rb
renalware-core-2.0.1 app/documents/renalware/age.rb
renalware-core-2.0.0 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.rc13 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.rc11 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.rc10 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.rc9 app/documents/renalware/age.rb
renalware-core-2.0.0.pre.rc8 app/documents/renalware/age.rb