# encoding: utf-8
module Okei
# Stores and validates units of measure.
#
# Attributes:
# +uuids+:: list of Units::Uuid objects assigned (referred to) the unit.
# +code+:: literal cyrillic code ("КМ/Ч").
# +name+:: name of the unit ("Километры в час").
# +num+:: numeric code of the unit following the OKEI ("007").
# +int_code+:: a literal international code of the unit ("KMH").
# +base+:: literal cyrillic code of the basic unit of measure ("М/С").
# +factor+:: float number of basic units in a current unit (0.28).
# +measure+:: the name of measurement ("СКОРОСТЬ") used for filtering units.
#
# Methods:
# #uuid:: returns value of the first +uuids+ assigned to the unit.
# .by_uuid(value):: selects units by a given UUID.
#
# The first UUID can be set manually if necessary (when db populated from the
# outer list). Otherwise it will be assigned by default on the unit creation.
#
# @example
# unit = Unit.new(
# name: "Километры в час", code: "КМ/Ч", num: "007", int_code: "KMH",
# base: "М/С", factor: 0.28, measure: "СКОРОСТЬ"
# )
# # this can be skipped:
# unit.uuids.new value: "9ac7e74a-d51a-424c-8fcd-71b0b55f6658"
#
class Unit < ActiveRecord::Base
include Uuids::Base
# Format of OKEI numeric codes (three digits).
NUM_FORMAT = /\A\d{3}\z/
has_uuids
validates :code, :name, :base, :factor, :measure, presence: true
validates :code, :name, uniqueness: true, allow_nil: true
validates :factor, allow_nil: true, numericality: { greater_than: 0.0 }
validates :num, allow_nil: true, format: { with: NUM_FORMAT }
end
end