Class: FindSubscriptions::CsvSchema

Inherits:
Object
  • Object
show all
Defined in:
lib/find_subscriptions/schema_registry.rb

Overview

Defines how to parse a CSV: required headers, amount column, debit/credit direction, and row-to-Transaction mapping.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(required_headers:, amount_key:, direction:, mapping:) ⇒ CsvSchema

direction: lambda(row_hash, amount_bd) => :debit or :credit mapping: lambda(row_hash, signed_amount_bd) => Transaction



39
40
41
42
43
44
# File 'lib/find_subscriptions/schema_registry.rb', line 39

def initialize(required_headers:, amount_key:, direction:, mapping:)
  @required_headers = required_headers.map(&:strip).to_set
  @amount_key = amount_key
  @direction = direction
  @mapping = mapping
end

Instance Attribute Details

#amount_keyObject (readonly)

Returns the value of attribute amount_key.



35
36
37
# File 'lib/find_subscriptions/schema_registry.rb', line 35

def amount_key
  @amount_key
end

#directionObject (readonly)

Returns the value of attribute direction.



35
36
37
# File 'lib/find_subscriptions/schema_registry.rb', line 35

def direction
  @direction
end

#mappingObject (readonly)

Returns the value of attribute mapping.



35
36
37
# File 'lib/find_subscriptions/schema_registry.rb', line 35

def mapping
  @mapping
end

#required_headersObject (readonly)

Returns the value of attribute required_headers.



35
36
37
# File 'lib/find_subscriptions/schema_registry.rb', line 35

def required_headers
  @required_headers
end

Instance Method Details

#==(other) ⇒ Object



66
67
68
69
70
# File 'lib/find_subscriptions/schema_registry.rb', line 66

def ==(other)
  other.is_a?(CsvSchema) &&
    @required_headers == other.required_headers &&
    @amount_key == other.amount_key
end

#map_row(row_hash) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/find_subscriptions/schema_registry.rb', line 51

def map_row(row_hash)
  raw_amount = row_hash.fetch(@amount_key).to_f
  dir = @direction.call(row_hash, raw_amount)

  signed =
    case dir
    when :debit  then raw_amount.abs     # outgoing positive
    when :credit then -raw_amount.abs    # incoming/refund negative
    else
      raise ArgumentError, 'direction must be :debit or :credit'
    end

  @mapping.call(row_hash, signed)
end

#matches_headers?(headers) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
49
# File 'lib/find_subscriptions/schema_registry.rb', line 46

def matches_headers?(headers)
  headers_set = headers.map(&:strip).to_set
  @required_headers.subset?(headers_set)
end