Class: TypedEAV::CurrencyStorageContract

Inherits:
FieldStorageContract show all
Defined in:
lib/typed_eav/currency_storage_contract.rb

Overview

Storage contract for Field::Currency’s two-cell value shape.

Constant Summary collapse

VALUE_COLUMNS =
%i[decimal_value string_value].freeze
AMOUNT_COLUMN =
:decimal_value
CURRENCY_COLUMN =
:string_value

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from FieldStorageContract

#after_snapshot, #before_snapshot, #changed?, #initialize, #query_column, #value_columns

Constructor Details

This class inherits a constructor from TypedEAV::FieldStorageContract

Class Method Details

.query_column(operator) ⇒ Object



14
15
16
# File 'lib/typed_eav/currency_storage_contract.rb', line 14

def self.query_column(operator)
  operator == :currency_eq ? CURRENCY_COLUMN : AMOUNT_COLUMN
end

.value_columnsObject



10
11
12
# File 'lib/typed_eav/currency_storage_contract.rb', line 10

def self.value_columns
  VALUE_COLUMNS
end

Instance Method Details

#apply_default(value_record) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/typed_eav/currency_storage_contract.rb', line 38

def apply_default(value_record)
  default = field.default_value
  return unless default.is_a?(Hash)

  value_record[AMOUNT_COLUMN] = default[:amount] || default["amount"]
  value_record[CURRENCY_COLUMN] = default[:currency] || default["currency"]
end

#read(value_record) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/typed_eav/currency_storage_contract.rb', line 20

def read(value_record)
  amount = value_record[AMOUNT_COLUMN]
  currency = value_record[CURRENCY_COLUMN]
  return nil if amount.nil? && currency.nil?

  { amount: amount, currency: currency }
end

#write(value_record, casted) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/typed_eav/currency_storage_contract.rb', line 28

def write(value_record, casted)
  if casted.nil?
    value_record[AMOUNT_COLUMN] = nil
    value_record[CURRENCY_COLUMN] = nil
  else
    value_record[AMOUNT_COLUMN] = casted[:amount]
    value_record[CURRENCY_COLUMN] = casted[:currency]
  end
end