Sunday, September 13, 2009

Export MySQL query result to a CSV file


SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM test_table;


http://tlug.dnho.net/node/209
http://dev.mysql.com/doc/refman/4.1/en/select.html

Another example:

SELECT v.id,v.name,t.name,d.name INTO OUTFILE '/root/tr_villages.csv'
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM villages v JOIN taluqs t ON v.taluq_id=t.id JOIN districts d ON t.district_id=d.id
WHERE t.district_id IN (163,164,165,166);

Wednesday, September 9, 2009

IRB tricks: assign last statement's return value to a var

irb(main):001:0> 1+2
=> 3
irb(main):002:0> a=_
=> 3
irb(main):003:0> a
=> 3

Underscore assigns the last executed statement's return value to a.

Tuesday, March 10, 2009

Anonymous functions

An interesting fact:
var sum = function(x,y,z) {
return (x+y+z);
}(1,2,3);
is an anonymous function. That means sub is now 6. If you call sum with any arguments it will bark at you. Where as this:
var sum = function(x,y,z) {
return (x+y+z);
};
is a named function. Sum is a function that accepts 3 arguments. If you call sub(2,3,5), it will return 10.

Thursday, February 26, 2009

Errno::ECONNREFUSED: Connection refused - connect(2)

Errno::ECONNREFUSED: Connection refused - connect(2)

If you get this error, one of the reason could be incorrect or no ActionMailer settings. The following structure needs to be present in your production.rb (or whatever config file):

ActionMailer::Base.smtp_settings = {
:address => 'smtp.gmail.com',
:port => 587,
:domain => 'mydomain.com',
:authentication => :plain,
:user_name => 'user@mydomain.com',
:password => 'password'
}

Tuesday, February 17, 2009

Using define_method to create a method that takes arguments

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/211436
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/211440

Example:

Setting.all.each do |setting|
define_method setting.name do |*a|
r = find(:first, :include => :setting, :conditions => ["setting_id = ?", setting.id])
full_record = (a.length == 0) ? false : a[0]
full_record ? r : r.value
end
end

Wednesday, January 28, 2009

after_initialize and after_find can't be private

after_initialize and after_find can't be private. Another note: they need to be explicitly define like:

def after_initialize
# do stuff here.
end