Sha256: 82ad9ef1846a1b6461f91a67450204bd520517c47a390495e6fc2ecbaf8a3721

Contents?: true

Size: 739 Bytes

Versions: 2

Compression:

Stored size: 739 Bytes

Contents

module Simple::SQL::Helpers::RowConverter
  # returns an array of converted records
  def self.convert(records, into:)
    hsh = records.first
    return records unless hsh

    if into == :struct
      converter = StructConverter.for(attributes: hsh.keys)
      records.map { |record| converter.convert(record) }
    else
      records.map { |record| into.new(record) }
    end
  end

  class StructConverter # :nodoc:
    def self.for(attributes:)
      @cache ||= {}
      @cache[attributes] ||= new(attributes)
    end

    private

    def initialize(attributes)
      @klass = Struct.new(*attributes)
    end

    public

    def convert(hsh)
      values = hsh.values_at(*@klass.members)
      @klass.new(*values)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
simple-sql-0.4.11 lib/simple/sql/helpers/row_converter.rb
simple-sql-0.4.10 lib/simple/sql/helpers/row_converter.rb