Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby get the size in bytes of an array

Tags:

arrays

ruby

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.

like image 886
alex.bour Avatar asked Feb 11 '12 09:02

alex.bour


1 Answers

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

like image 114
Sherwin Yu Avatar answered Sep 17 '22 12:09

Sherwin Yu