Sha256: fb09eea8cd6a99ffcb02ef53bf8fd7df2a33ad13c2d8e44ef2838a70b4572ae7

Contents?: true

Size: 1.24 KB

Versions: 34

Compression:

Stored size: 1.24 KB

Contents

module Bmg
  module Reader
    class TextFile
      include Reader

      DEFAULT_OPTIONS = {
        strip: true,
        parse: nil
      }

      def initialize(type, path, options = {})
        options = { parse: options } if options.is_a?(Regexp)
        @path = path
        @options = DEFAULT_OPTIONS.merge(options)
        @type = infer_type(type)
      end
      attr_reader :path, :options

    public # Relation

      def each
        path.each_line.each_with_index do |text, line|
          text = text.strip if strip?
          parsed = parse(text)
          yield({line: 1+line}.merge(parsed)) if parsed
        end
      end

    private

      def infer_type(base)
        return base unless base == Bmg::Type::ANY
        attr_list = if rx = options[:parse]
          [:line] + rx.names.map(&:to_sym)
        else
          [:line, :text]
        end
        base
          .with_attrlist(attr_list)
          .with_keys([[:line]])
      end

      def strip?
        options[:strip]
      end

      def parse(text)
        return { text: text } unless rx = options[:parse]
        if match = rx.match(text)
          TupleAlgebra.symbolize_keys(match.named_captures)
        end
      end

    end # class TextFile
  end # module Reader
end # module Bmg

Version data entries

34 entries across 34 versions & 1 rubygems

Version Path
bmg-0.23.3 lib/bmg/reader/text_file.rb
bmg-0.23.2 lib/bmg/reader/text_file.rb
bmg-0.23.1 lib/bmg/reader/text_file.rb
bmg-0.23.0 lib/bmg/reader/text_file.rb
bmg-0.21.5 lib/bmg/reader/text_file.rb
bmg-0.21.4 lib/bmg/reader/text_file.rb
bmg-0.20.5 lib/bmg/reader/text_file.rb
bmg-0.19.3 lib/bmg/reader/text_file.rb
bmg-0.21.3 lib/bmg/reader/text_file.rb
bmg-0.21.2 lib/bmg/reader/text_file.rb
bmg-0.21.0 lib/bmg/reader/text_file.rb
bmg-0.20.4 lib/bmg/reader/text_file.rb
bmg-0.20.2 lib/bmg/reader/text_file.rb
bmg-0.20.1 lib/bmg/reader/text_file.rb
bmg-0.20.0 lib/bmg/reader/text_file.rb
bmg-0.19.2 lib/bmg/reader/text_file.rb
bmg-0.19.1 lib/bmg/reader/text_file.rb
bmg-0.19.0 lib/bmg/reader/text_file.rb
bmg-0.18.15 lib/bmg/reader/text_file.rb
bmg-0.18.14 lib/bmg/reader/text_file.rb