Sha256: fd0096b39e88cd6d485f2e326ccf1e19d85d8da989400a3f13c5acce183d47b1

Contents?: true

Size: 1.56 KB

Versions: 1

Compression:

Stored size: 1.56 KB

Contents

# frozen_string_literal: true

module Ductr
  module Sequel
    #
    # A lookup control that execute the query for a bunch of rows and merge them with the buffer's rows.
    #
    class MatchLookup < Ductr::ETL::BufferedTransform
      #
      # The looked up row key to match.
      #
      # @return [Symbol] The column name
      #
      def from_key
        @options[:merge].first
      end

      #
      # The buffer row key to match.
      #
      # @return [Symbol] The column name
      #
      def to_key
        @options[:merge].last
      end

      #
      # Opens the database if needed, calls the job's method and merges
      # the looked up rows with corresponding buffer rows.
      #
      # @yield [row] The each block
      # @yieldparam [Hash<Symbol, Object>] row The merged row
      #
      # @return [void]
      #
      def on_flush(&)
        call_method(adapter.db, buffer_keys).each do |row|
          match = buffer_find(row)
          next yield(row) unless match

          yield(row.merge match)
        end
      end

      private

      #
      # Find the corresponding row into the buffer.
      #
      # @param [Hash<Symbol, Object>] row The looked up row
      #
      # @return [Hash<Symbol, Object>, nil] the matching row if exists
      #
      def buffer_find(row)
        buffer.find { |r| r[from_key] == row[to_key] }
      end

      #
      # Maps the buffer keys into an array.
      #
      # @return [Array<Integer, String>] The keys array
      #
      def buffer_keys
        buffer.map { |row| row[from_key] }
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ductr-0.2.1 lib/ductr/sequel/match_lookup.rb