Class: Gitlab::Json::LimitedEncoder

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/json.rb

Constant Summary collapse

LimitExceeded =
Class.new(StandardError)

Class Method Summary collapse

Class Method Details

.encode(object, limit: 25.megabytes) ⇒ String

Generates JSON for an object or raise an error if the resulting json string is too big

Parameters:

  • object (Hash, Array, Object)

    must be hash, array, or an object that responds to .to_h or .to_json

  • limit (Integer) (defaults to: 25.megabytes)

    max size of the resulting json string

Returns:

  • (String)

Raises:

  • (LimitExceeded)

    if the resulting json string is bigger than the specified limit


209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/gitlab/json.rb', line 209

def self.encode(object, limit: 25.megabytes)
  return ::Gitlab::Json.dump(object) unless Feature.enabled?(:json_limited_encoder)

  buffer = []
  buffer_size = 0

  ::Yajl::Encoder.encode(object) do |data_chunk|
    chunk_size = data_chunk.bytesize

    raise LimitExceeded if buffer_size + chunk_size > limit

    buffer << data_chunk
    buffer_size += chunk_size
  end

  buffer.join('')
end