Month: December 2010

Quick start to Ruby with MySQL

Posted by – December 14, 2010

I’ve done Ruby on Rails with MySQL but never done done Ruby with MySQL. I just did this last week to check a small thing. I didn’t want to establish the whole Rails’s process. I takes a lot of memory.

Let’s do a quick start.

Install a driver first. You can get one that’s written by C or Ruby. If you got gem then that’s easy.

$ sudo gem install mysql

It’s written by C

It’s quite easy to start. Require ‘mysql’ then create a connection to the database and then query. If install by gem, just require ‘rubygems’ first.

require 'rubygems'
require 'mysql'
db = Mysql::new("host", "user", "passwd", "db")
res = db.query("select * from mytable")
res.each do |row|
  puts "id: #{row[0]}"

and this is what I got

id: 1
id: 2
id: 3
id: 4

Looks simple. The index of an element in an array is sorted by the sequence of columns in the table.

Or you can get the column names instead of the indexes by each_hash

res.each_hash do |row|
  puts "id: #{row['id']}"

More information at the pages of the driver.

What the heck is JSONP?

Posted by – December 9, 2010

I’ve got it working but didn’t know how it works.

To avoid the same origin policy, JSON is a good thing to help you. The thing on the same origin policy is the browser requests from JavaScript or Flash aren’t allowed because we need to protect from script injection attacks. If this happens, the resources like http cookies will be accessed then your authentication or password in the cookies can be stolen.

So we can’t fix this but we can avoid it. The basic idea is we can request any Javascript anywhere.

<script src="http://somewhere/jsfile" type="text/javascript"></script>

Once it loaded, the browser could execute this javascript.

But if it receives json then it does nothing. We can make a returned Javascritpt looks like this.

var json_var = {'var1':'val1'};

It would be better if we can define the callback function.


The server needs to provide this padding. The next thing is we have to declare this function(myCallback) to be executed once it loaded.

For instance, Graph on Facebook allows us to define the callback

by putting the ?callback=yourCallback at the end of uri

I misunderstood when I started because I saw the doc from jQuery that can put the dataType as jsonp and I thought it was just another asynchronous request which can request across the domain name on the browser.

Basically, jQuery actually provides the callback function as well like

jsonp1291493679672 is the callback function to be defined in window like window['jsonp1291493679672'] which defines data and returns this data to the callback function we put in the ajax request. What it does is, jQuery puts ?callback=? at the end of uri and replaces a question mark(?) with jsonp1291493679672. The numbers at the end comes from now() btw.