class ActiveRecord::Type::Decimal
Десятичный тип Active Model
Тип атрибута для десятичных чисел — числового представления с плавающей точкой и высокой точностью. Он зарегистрирован под ключом :decimal.
class BagOfCoffee include ActiveModel::Attributes attribute :weight, :decimal end
Экземпляры Numeric преобразуются в экземпляры BigDecimal. Для приведения любых других объектов используется их метод to_d, за исключением пустых строк, которые приводятся к nil. Если метод to_d не определен, объект преобразуется в строку с помощью to_s, а затем приводится с помощью to_d.
bag = BagOfCoffee.new bag.weight = 0.01 bag.weight # => 0.1e-1 bag.weight = "0.01" bag.weight # => 0.1e-1 bag.weight = "" bag.weight # => nil bag.weight = :arbitrary bag.weight # => nil (the result of `.to_s.to_d`)
Точность Decimal по умолчанию равна 18; ее можно настроить при объявлении атрибута:
class BagOfCoffee include ActiveModel::Attributes attribute :weight, :decimal, precision: 24 end
Константы
- BIGDECIMAL_PRECISION
Открытые методы экземпляра
# File activemodel/lib/active_model/type/decimal.rb, line 50 def type :decimal end
# File activemodel/lib/active_model/type/decimal.rb, line 54 def type_cast_for_schema(value) value.to_s.inspect end
© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.