Sha256: eea811074174de336d18010b42c9826cc944eafd5d3925b5baf304a892e49a23

Contents?: true

Size: 1.18 KB

Versions: 3

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true

require 'measured'

module Physical
  class Cuboid
    include PropertyReaders

    attr_reader :dimensions, :length, :width, :height, :weight, :id, :properties

    def initialize(id: nil, dimensions: [], weight: Measured::Weight(0, :g), properties: {})
      @id = id || SecureRandom.uuid
      @weight = Types::Weight[weight]
      @dimensions = []
      @dimensions = fill_dimensions(Types::Dimensions[dimensions])
      @length, @width, @height = *@dimensions
      @properties = properties
    end

    def volume
      Measured::Volume(dimensions.map { |d| d.convert_to(:cm).value }.reduce(1, &:*), :ml)
    end

    def density
      return Measured::Density(Float::INFINITY, :g_ml) if volume.value.zero?
      return Measured::Density(0.0, :g_ml) if volume.value.infinite?

      Measured::Density(weight.convert_to(:g).value / volume.convert_to(:ml).value, :g_ml)
    end

    def ==(other)
      other.is_a?(self.class) &&
        id == other&.id
    end

    private

    def fill_dimensions(dimensions)
      dimensions.fill(dimensions.length..2) do |index|
        @dimensions[index] || Measured::Length(self.class::DEFAULT_LENGTH, :cm)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
physical-0.5.1 lib/physical/cuboid.rb
physical-0.5.0 lib/physical/cuboid.rb
physical-0.4.9 lib/physical/cuboid.rb