Wednesday, October 24, 2012

gzip compression/decompression in Ruby

Recently I did some investigation compression and decompression in gzip format using Ruby. Here I posted my ruby code:
require 'zlib'
require 'stringio'
require 'json'
def gunzip(data)
io = StringIO.new(data, "rb")
gz = Zlib::GzipReader.new(io)
decompressed = gz.read
end
def gzip(string)
wio = StringIO.new("w")
w_gz = Zlib::GzipWriter.new(wio)
w_gz.write(string)
w_gz.close
compressed = wio.string
end
data = (1..100).collect {|i| {"id_#{i}" => "value_#{i}" } }
contents = data.to_json
compressed = gzip(contents)
decompressed = gunzip(compressed)
puts "compressed string:"
puts compressed
puts "decompressed success? #{decompressed == contents}"
puts "uncompressed data size: #{contents.length}"
puts "decompressed data size: #{compressed.length}"
puts "compress ratio: #{compressed.length.to_f / contents.length.to_f}"
view raw gistfile1.rb hosted with ❤ by GitHub

Sunday, October 21, 2012

How to render JSON in rhodes mobile framework

Currently I am using Rhodes framework to build mobile applications. Recently I just figured out how to request an Ajax call from view, and controller how to render a JSON object and return it to the view.

Sample code
Ajax call to request json object using jQuery:
$.getJSON(<%= url_for :action => :request_json %>, function(data) {
alert(data.a);
alert(data.b);
});

code of rending json in controller

def request_json
@response['headers']['Content-Type']='application/json'
obj = {"a" => 1, "b"=> 2}
result = obj.to_json
render :string => result, :use_layout_on_ajax => true
end

I found this solution in the Rhomobile launchpad forum, it works perfectly.
This exactly looks like render json behaviour in Ruby on Rails.