Skip to content

Instantly share code, notes, and snippets.

@brianhempel
Created February 17, 2015 17:32
Show Gist options
  • Save brianhempel/56823fb777fb567b676a to your computer and use it in GitHub Desktop.
Save brianhempel/56823fb777fb567b676a to your computer and use it in GitHub Desktop.
Lazily convert an Enumerator or Enumerator::Lazy to a JSON array. Save as config/initializers/enumerator_to_json.rb
# Natively, Enumerators get JSONized like "#<Enumerator::Lazy:0x007f8714807080>", or they explode, either of which is a problem.
# We want them to make an array, and do it lazily so we don't have to keep the items in memory!
class Enumerator
def to_json(state)
state.depth += 1
string = "[\n"
first_item = true
self.each do |item|
separator = ",\n" unless first_item
as_json = item.as_json
indentation = state.indent * state.depth
string << "#{separator}#{indentation}#{as_json.to_json(state)}"
first_item = false
end
state.depth -= 1
indentation = state.indent * state.depth
string << "\n#{indentation}]"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment