Skip to content

Instantly share code, notes, and snippets.

@simi
Last active May 17, 2022 06:59
Show Gist options
  • Save simi/95f6695dc6d6ec64b9be9f52e82a0498 to your computer and use it in GitHub Desktop.
Save simi/95f6695dc6d6ec64b9be9f52e82a0498 to your computer and use it in GitHub Desktop.
class MyEnumerator
attr_reader :scope, :block, :opened, :headers
def initialize(scope, headers, &block)
@scope = scope
@block = block
@opened = false
@cursor = PostgreSQLCursor::Cursor.new(scope.send(:to_unprepared_sql))
@headers = headers
@headers_provided = false
end
def next
open unless opened
unless @headers_provided
@headers_provided = true
return headers
end
row = fetch_row
if row.nil?
close
raise StopIteration
end
return @block.call(row)
end
def fetch_row
@column_types ||= @cursor.column_types
if row = @cursor.fetch
scope.klass.send(:instantiate, row, @column_types)
else
nil
end
end
def open
@cursor.open
@opened = true
end
def close
@cursor.close
@opened = false
end
end
MyEnumerator.new(scope, csv_header) do |revenue|
next if @options[:ignore_zero] && revenue.chain.any?(&:zero?)
CSV.generate_line(row(revenue))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment