alex.bour
alex.bour

Reputation: 2964

Ruby get the size in bytes of an array

I would like to obtain the size in bytes of the content of an array (items) in ruby.

I fill my array like this:

  @records.each do |record|
    items << { :table => table, :id => record.id, :lruos => record.updated_at }
  end

In fact, I want to force sending the Content-Length of this array when I serialize it in JSON:

respond_to do |format|
  #response['Content-Length'] = items.to_s.size
  format.json { render :json => { :success => "OK", :items => items } }
end

So any idea to do this could be interesting. (for a reason I don't know the content length is not sent, so I want to force it)

I use Rails 3.0.5.

Upvotes: 11

Views: 12688

Answers (3)

Ninad Nehete
Ninad Nehete

Reputation: 560

Alternatively, you can also do this by item.to_json.bytesize. This will give you the size of JSON string that is being sent.

Upvotes: 6

techguy
techguy

Reputation: 57

For those that are still wondering - I found this to work

ActiveSupport::JSON.encode(items).size.to_s

Which while its many years later - may help someone.

Upvotes: 2

Sherwin Yu
Sherwin Yu

Reputation: 3230

Like WTP said, you probably intend on returning the size of the JSON representation instead of ruby representation of the array, because the JSON is the actual response to the browser. You can do this by encoding beforehand (yielding a string) and then checking its size.

response['Content-Length'] = ActiveSupport::JSON.encode(items).size

More about JSON serialization and rails

Upvotes: 10

Related Questions