Monday, June 27, 2011

How to install mysql2 Ruby Gem without having MySQL installed

It's all about the libraries my friends. If you get something like this:

Installing mysql2 (0.2.11) with native extensions /usr/local/lib/ruby/site_ruby/1.9.1/rubygems/installer.rb:551:in `rescue in block in build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

        /usr/local/bin/ruby extconf.rb
checking for rb_thread_blocking_region()... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lm... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lz... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lsocket... no
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lnsl... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lmygcc... no
checking for mysql_query() in -lmysqlclient... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Then you just need to do this:


1) sudo apt-get install libmysqlclient-dev
2) sudo gem install mysql2



Monday, June 20, 2011

Converting Ruby Time to Milliseconds

Coming from Java land, I am really used to working in milliseconds and often times I want to time a block of code in milliseconds, so here's how I do it:

start_time = Time.now
# some code to time
end_time = Time.now
duration_in_ms = ((end_time.to_f - start_time.to_f) * 1000.0).to_i

Or to get current time since epoch in milliseconds:

(Time.now.to_f * 1000.0).to_i

Installing pg gem without having Postgres installed

If you get this error:


ubuntu@ip-10-204-65-124:~$ sudo gem install pg
Building native extensions.  This could take a while...
ERROR:  Error installing pg:
ERROR: Failed to build gem native extension.


        /usr/local/bin/ruby extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***

Try:

sudo apt-get install libpq-dev 

Then try again: 

sudo gem install pg


Saturday, June 11, 2011

sed: How to replace a line containing a matching pattern

Since it's hard to pipe commands with sudo, here's a one liner that works with sudo:


    sudo sed -i '/SL_TEMPLATE_ID/ c\SL_TEMPLATE_ID=1071' myfile.txt

The -i tells it to modify the file in place. Get rid of the -i to test it first.