Sha256: 03e21216459fa5c069920851acae58538de3b8edb037d16b06fb1864c37df65a

Contents?: true

Size: 1.02 KB

Versions: 1

Compression:

Stored size: 1.02 KB

Contents

require 'csv'

module Streamer
  module FactProviders
    # CSVProvider implements Finder Provider interface
    class CSVProvider
      attr_reader :path, :key

      def initialize(path)
        @path = path
      end

      def find(key)
        @key = key
        return hash_result if segments.size == 2
        return scalar_result if segments.size == 3
      end

      def segments
        key.split('.')
      end

      def hash_result
        Hash[headers.zip CSV.parse_line(lines)]
      end

      def scalar_result
        hash_result[segments[2]]
      end

      def lines
        `#{processing_statement}`.strip
      end

      def headers
        @headers ||= CSV.parse_line(`head -n 1 #{path}`)
      end

      def field_number(field)
        headers.index(field) + 1
      end

      def processing_statement
        segs = segments
        return unless segs.size > 1 && segs.size < 4
        <<-STMT
awk -F'","|,' '($#{field_number(segs[0])} ~ /^#{segs[1]}$/){print $0}' #{path}
        STMT
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
streamer-0.2.1 lib/streamer/fact_providers/csv_provider.rb