Class: Danconia::Stores::ActiveRecord

Inherits:
Object
  • Object
show all
Defined in:
lib/danconia/stores/active_record.rb

Overview

Store implementation that persist rates using ActiveRecord.

Instance Method Summary collapse

Constructor Details

#initialize(unique_keys: %i[pair], date_field: nil) ⇒ ActiveRecord

Returns a new instance of ActiveRecord.

Parameters:

  • unique_keys (Array) (defaults to: %i[pair])

    each save_rates will update records with this keys’ values

  • date_field (Symbol) (defaults to: nil)

    used when storing daily rates



7
8
9
10
# File 'lib/danconia/stores/active_record.rb', line 7

def initialize unique_keys: %i[pair], date_field: nil
  @unique_keys = unique_keys
  @date_field = date_field
end

Instance Method Details

#rates(**filters) ⇒ Object

Returns an array of maps like the one it received.



27
28
29
# File 'lib/danconia/stores/active_record.rb', line 27

def rates **filters
  ExchangeRate.where(process_filters(filters)).map { |er| er.attributes.symbolize_keys }
end

#save_rates(rates) ⇒ Object

Creates or updates the rates by the ‘unique_keys` provided in the constructor.

Parameters:

  • rates (Array)

    must be an array of maps.



15
16
17
18
19
20
21
22
23
24
# File 'lib/danconia/stores/active_record.rb', line 15

def save_rates rates
  ExchangeRate.transaction do
    rates.each do |fields|
      ExchangeRate
        .where(fields.slice(*@unique_keys))
        .first_or_initialize
        .update(fields.slice(*ExchangeRate.column_names.map(&:to_sym)))
    end
  end
end