Class: Attributor::BigDecimal

Inherits:
Object
  • Object
show all
Includes:
Type
Defined in:
lib/attributor/types/bigdecimal.rb

Class Method Summary collapse

Methods included from Type

get_memoized_collection_class, set_memoized_collection_class

Class Method Details

.as_json_schema(shallow: false, example: nil, attribute_options: {}) ⇒ Object

Bigdecimal numbers are too big to be represented as numbers in JSON schema The way to do so, is to represent them as strings, but add a ‘format’ specifying how to parse that (seemingly, there is a ‘double’ well known type that json API claims we can use) … not sure if this is the right one, as technically BigDecimal has very large precision that a double wouldn’t be able to fit…



32
33
34
35
36
# File 'lib/attributor/types/bigdecimal.rb', line 32

def self.as_json_schema( shallow: false, example: nil, attribute_options: {} )
  hash = super
  hash[:format] = 'bigdecimal'
  hash
end

.example(_context = nil, options: {}) ⇒ Object



11
12
13
# File 'lib/attributor/types/bigdecimal.rb', line 11

def self.example(_context = nil, options: {})
  BigDecimal("#{Faker::Number.decimal(l_digits: 3, r_digits: 3)}")
end

.json_schema_typeObject



23
24
25
# File 'lib/attributor/types/bigdecimal.rb', line 23

def self.json_schema_type
  :string
end

.load(value, _context = Attributor::DEFAULT_ROOT_CONTEXT, **_options) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/attributor/types/bigdecimal.rb', line 15

def self.load(value, _context = Attributor::DEFAULT_ROOT_CONTEXT, **_options)
  return nil if value.nil?
  return value if value.is_a?(native_type)
  return BigDecimal(value, 10) if value.is_a?(::Float)
  return BigDecimal(value + '0') if value.is_a?(::String) && value.end_with?('.')
  BigDecimal(value)
end

.native_typeObject



7
8
9
# File 'lib/attributor/types/bigdecimal.rb', line 7

def self.native_type
  ::BigDecimal
end