Skip to main content

Posts

How to access ActiveRecord & Migrations outside of Ruby on Rails

Rails migrations are an extremely handy way of capturing changes to your database and rolling them back if they are incorrect. Manipulating or querying a database is a pretty useful tool and ActiveRecord turns your tables into objects so I looked into how to access these features outside of a Rails environment. I wanted to be able to either specify the database connection details directly in the script if I was running it outside of a Rails application, or to be able to bind into the Rails application's database.yml database configuration file. To run it as a standalone script with the database details described inside the script run: ruby play_with_the_database.rb To run it within the context of a Rails application place the script inside a new directory called db/script and run: ruby play_with_the_database.rb development If you want to run the above script against the production database run: ruby play_with_the_database.rb production I'll show you the ruby code that I came ...

htop - a great alternative to top for Ubuntu Linux

I colleague recommended that I install htop the other day. It's an alternative to top which offers colour (ooh), a tree sort view (aah), and the ability to kill off processes within htop itself (very cool). To install it, simply run: sudo aptitude install htop And to run it, simply type: htop This is what it looks like running (with the tree view selected): And here are some of the help options: Technorati Tags: , htop , top , Ubuntu , Linux , Andrew Beacock

Upgrading to Ubuntu 7.10 (Gutsy Gibbon) causes snmpd errors

When Gutsy Gibbon was released back in October I was quick to upgrade my home Ubuntu server to this new release. The upgrade went smoothly apart from one failure - a strange error message when upgrading the SNMP support: Starting network management services:invoke-rc.d: initscript snmpd, action "start" failed. dpkg: error processing snmpd (--configure): subprocess post-installation script returned error exit status 1 I didn't understand the error message and googling for it at the time brought up no solutions. I checked and found that snmpd was running successfully and all appeared fine. I recently applied some more updates and received the same error message so I investigated it again. This time I found the reason, the SNMP package upgrade scripts don't stop snmpd before they perform the upgrade , so you need to stop snmpd before you update. This is how I did it: $ sudo /etc/init.d/snmpd stop Stopping network management services: snmpd snmptrapd. $ sudo ...

How to rollback Rails database migrations

When you perform database migrations in Rails you use the following command: rake db:migrate If you want to roll back your change to need need to find out what version your database is currently at and then roll back to a previous version: rake db:migrate VERSION=<version to roll back to> I've never liked this way to roll back, seems to much like hard work to me so I found a migration rollback script on the programmingishard site and simplified so that it only rollback by one version: namespace :db do namespace :migrate do desc "Rollback the database schema to the previous version" task :rollback => :environment do previous_version = ActiveRecord::Migrator.current_version.to_i - 1 ActiveRecord::Migrator.migrate("db/migrate/", previous_version) puts "Schema rolled back to previous verison (#{previous_version})." end end end To use this scriptlet, copy and paste the code into a file called db_rollback.rake a...

How to get the schema version number out of your Rails migrations

When you want to revert your Rails migration you need the version number so that you can perform the rollback: rake db:migration VERSION=? One way is to access the database and take a look in the schema_info table to find the version number. An easier way is to add an additional task to Rake (found via the Quoted-Printable ): namespace :db do desc 'Print the current database migration version number' task :version => :environment do puts ActiveRecord::Migrator.current_version end end Copy this code into a file called db_version.rake and place it in the lib/tasks directory within your Rails application. To find out the current version number, simply run: rake db:version Technorati Tags: Rails , Version , Migration , Rake , QuotedPrintable , Andrew Beacock

How to truncate a log file using Ubuntu Linux

Have you ever wanted to truncate a log file that was being written to by a running process without stopping the process to do so? If so then all you need is the following to clear out the active log file: cat /dev/null > some_log_file.log There are some other great tips over on the Bash Cures Cancer blog . Technorati Tags: Truncate , Log , File , Ubuntu , Linux , Andrew Beacock

How to add system-wide environment variables to Ubuntu & Debian Linux

Following on from my last post on how to add shared libraries to Linux's system library path I wanted to share a related tip on system-wide environment variables. Common reasons for doing this are setting your locale, setting the location of a Java installation or specifying the character set that your database is using (if you use Oracle then that would be the NLS_LANG environment variable ). Debian actually has a policy against system-wide environment variables stating "a program must not depend on environment variables to get reasonable defaults" and suggests that all programs should have wrapper shell scripts to set the relevant variables. Ignoring this sound advice I tried adding them to /etc/profile but this didn't work when ssh was used from a remote machine to execute some commands (I was using Capistrano ). I couldn't find a complete way to do it (it wasn't picked up by any start scripts in /etc/init.d ) but I achieved the most success by placing ...

How to add shared libraries to Linux's system library path

Sometimes in Linux when you install a new software package the instructions tell you to add a directory of shared libraries to your $LD_LIBRARY_PATH environment variable in your .bashrc. You may have noticed that if you then create a shortcut icon on your desktop to this application it won't start because it can't find the libraries. A typical solution is to write a wrapper shell script to set the LD_LIBRARY_PATH and then call that application. Well, I've discovered how to add them to your system's library path allowing all environments to access them. Note: There are differences between Debian and Ubuntu (the two flavours of Linux that I'm familiar with). Ubuntu Create a new file in /etc/ld.so.conf.d/ called .conf Edit the file and add a line per directory of shared libraries (*.so files), it will look something like: /usr/lib/APPLICATION/lib Reload the list of system-wide library paths: sudo ldconfig Debian Edit /etc/ld.so.conf Add a line per directory of shared...

DESTRUCTOID's Team Fortress 2 for Beginners

Reverend Anthony over at the DESTRUCTOID gaming site has written a great set of beginner guides to the different classes of the rather excellent Team Fortress 2 game that came out of beta today. He's provided some tips for each class as well as a general post full of common tips. I've found them quite invaluable in getting to know the game quickly! Demoman Engineer Heavy Weapons Guy Medic Pyro Scout Soldier Sniper Spy General Tips Technorati Tags: TeamFortress2 , Valve , PC , Gaming , Andrew Beacock

A Capistrano recipe for restarting Apache 2 (on Linux)

Capistrano is the rather excellent tool for automating Rails application deployment. But it can do a lot more than just uploading Rails applications to live webservers. It's scripts are basically Rake scripts and so have the full power of Ruby behind then so you can pretty much write code to do anything that you want. I wanted a way to reload the configuration for my Apache2 web server running on my home Ubuntu server . I found a post on Mongrel and Capistrano 2.0 by John Ward which showed a very nifty way to create Capistrano tasks for variants of the same base command. My adapted version for controlling Apache is: namespace :apache do [:stop, :start, :restart, :reload].each do |action| desc "#{action.to_s.capitalize} Apache" task action, :roles => :web do invoke_command "/etc/init.d/apache2 #{action.to_s}", :via => run_method end end end Add this code to your config/deploy.rb . This will add four new tasks to Capistrano whi...

How to "Show Desktop" in Ubuntu Linux

Like Windows, Ubuntu (and pretty much every other Linux) has a "Show Desktop" icon on it's toolbar that minimizes all the running applications to the taskbar allowing full view of the desktop. I discovered it last week by accident whilst I was attempting to pull off a difficult triple-press-perfect-timing-required IDE 'shortcut' ;) The keyboard shortcut for "Show Desktop" is: Ctrl-Alt-D I also found a great linux desktop hotkeys article written by the Calgary Linux Users Group . Technorati Tags: Show Desktop , Ubuntu , Linux , CLUG , Andrew Beacock

How to restore Windows XP's "Show Desktop" icon

I'm not sure of the exact details but it seems that on some installations of XP the "show desktop" icon is missing from the quick launch toolbar (next to the Start button). Most other applications are also available in the Start menus so it's pretty easy to restore them but not the Show Desktop icon. The Techie Corner blog had the answer I was looking for - two different ways to restore the Show Desktop icon . I preferred the second technique - throw the following command into Start ->Run: regsvr32 /n /i:U shell32.dll Your show desktop icon should have instantly appeared in the quick launch toolbar! Technorati Tags: Show Desktop , Quick Launch , Windows XP , TechieCorner , Andrew Beacock

Manager Tools - my favourite podcast for over 2 years

Back in 2005 I blogged about the podcasts that I subscribe to and one of my favourites was Manager Tools . Well two years later my list has changed a little (click on the 'podcasts' link on the left for a closer look) but Manager Tools is still my favourite podcast, the moment the show music starts to play in my car I know I'm in for an hour of energetic & informative advice regarding all aspects of management & leadership. I'm amazed at how much time & effort Michael Auzenne & Mark Horstman put into producing a timely weekly show full of great content with such audio finesse as well. I was recently very fortunate to get a sneak preview of some of their premium content and I must say if it's all of the same high quality (which with Mike & Mark is a given) then it's definitely worth the month fee. They are consistantly the number 1 business podcast at PodcastAlley and have won the "Best Business Podcast" for two years in a row. ...

Having cron troubles with percent (%) signs in crontabs?

I recently wrote a cronjob which would save off my Ubuntu home server's current packages list every night to a dated file so that I have a history of the changes that I've made to my system. The entry in my crontab looked something like this: # package lists (5am) 0 5 * * * dpkg -l > /var/log/packages/`date +%F`.txt After a couple of days I decided to take a look at the files generated so far but to my disappointment I found none. After a quick search for dpkg in /var/log I found my problem reported in syslog: ... /USR/SBIN/CRON[28508]: ... CMD (dpkg -l > /var/log/packages/`date +) I noticed that the command recorded to the logs was up to '`date +' - the next character - the percent sign (%) - was causing some kind of issue. A quick search threw up the Wikipedia page for Crontab which mentioned: Another common mistake is to use unescaped % in your command; you have to escape them All I had to do was change % to be \% . My working crontab entry now looks li...

How to open Firefox Google searches in a new tab

I'm always using the built-in Google search box in Firefox to do my research. I used to click the 'New Tab' button (or CTRL-T) to open a fresh tab, then type in the box and hit return to open the results in my newly created tab. I then found that it will open in a new tab automatically if you use Ctrl-Return rather than just Return when searching. That was a great improvement but if I forgot to hold down Ctrl I would wipe out my current tab with the Google search results. Well I've found the ultimate solution from an 'Hacking Firefox' article on Computer World found via the excellent LifeHacker blog . It's an about:config value that makes the search results open in a new tab (in the same way that Ctrl-Return did). To enable it, enter about:config in the location bar. Enter browser.search.openintab in the "Filter" text box and then double click the listed browser.search.openintab to change it's value from false to true: Oh, and if you wa...

Getting Tomcat contexts to work in IntelliJ IDEA (and stop it starting Tomcat twice!)

If you run Tomcat within IDEA then you might have noticed a couple of things: Your application gets started, undeployed and then started again, increasing the start up time of Tomcat and reinitialising any load-on-startup servlets for a second time. Your carefully crafted <context> stanzas don't work as IDEA hasn't picked then up from either server.xml or META-INF/context.xml. When you start Tomcat inside IDEA it copies the contents of your Tomcat conf directory to an IntelliJ system area (on Linux it's hidden in your home directory) and then runs Tomcat looking at those configuration files instead of the normal ones. In doing this it seems to ignore any context.xml files, any context stanzas of the server.xml and messes up any context files you might have in conf/Catalina/ . To get around this big mess and just use your Tomcat as if you ran it outside of IDEA you simply add a CATALINA_BASE environment variable to the configuration of Tomcat (within IDEA) point...

How to get the Home & End keys working in remote Linux shells & terminals

Have you ever SSH'ed onto a remote linux server only to find that your Home and End keys don't take you to the start and end of the line and instead give you a rather unhelpful "~"? One solution is to use CTRL-A instead of Home and CTRL-E instead of End but I wanted to solve it properly. The linux command line is managed by readline . The configuration file for controlling key bindings (amongst other things) is /etc/inputrc . In Ubuntu this file contains a number of commented out sections relating to the Home and End keys. To find out which keycodes are being sent to readline when Home & End are pressed I used od - a stdin dump utility which can display ASCII characters or backslash escapes: $ od -c <Home key pressed> ^[[7~ <End key pressed> ^[[8~ The key bits here are the 7 and 8, these need to be entered at the very end of /etc/inputrc as follows: "\e[7~": beginning-of-line "\e[8~": end-of-line After you've made th...

Viewing Outlook vCalendar meeting invites in Thunderbird

I received an Outlook meeting invite in my email recently but because I use Thunderbird as my email reader I received the raw vCalendar data rather than a nicely formatted email with details of the meeting. After a quick google search I found a post on Daniel Tome's blog regarding Viewing Calendar Events in Mozilla Thunderbird . His suggestion was to install a Thunderbird add-on called Lightning . This adds a calendar into Thunderbird and also adds support for understanding vCalendar events. More information can be found at Lightning's home page . I installed the add-on and restarted Thunderbird and now the raw vCalendar email was transformed into a nicely formatted meeting invite - you even get the option to accept or decline the meeting. Just remember to right-click on the green "Install Now" button to download the add-on otherwise you will install it into firefox. Thanks again Daniel! . Technorati Tags: Thunderbird , Outlook , vCalendar , meeting , event , Lig...

Opening winmail.dat (TNEF) files in Thunderbird (on Ubuntu)

  UPDATE: I have an improved version of the script available here . I'm not going to repeat the many , many websites taking (and complaining) about Microsoft's proprietary e-mail attachment format called TNEF . I'm assuming that if you are reading this then you have found that these fixes are not working for you (or not possible to enforce). I'll also assume that the LookOut Thunderbird Add-on by Aron Rubin is also not working correctly for you (this was my experience on Ubuntu Edgy Eft). The best solution I could come up with was getting Thunderbird to run a script to unpack the winmail.dat extension into a folder on your Ubuntu desktop. It relies on the tnef command-line program , so make sure that is installed first (it's bundled with Ubuntu): sudo aptitude install tnef Below is my little script, save it in a file called 'tnef.sh' somewhere and make sure it's executable ( chmod +x tnef.sh ) - or just download it here . #!/bin/bash LOCATION=~/Deskt...

How to stop schema.rb from being generated when running Rails Migrations

A couple of days ago I blogged about why rails migrations caused the database schema to be dumped into schema.rb . I've now found a way to stop it from happening without changing the schema_type or modifying any core Rails or Rake classes. What I planned to do was override the db:migrate rake task to do the same as the default one bar the schema dump. My first attempt failed as it appears that rake will allow more than one task to have the same name, it runs then one after the other. The result of this was some strange migrations plus the delay due to dumping the schema! After a little googling I found an excellent post on Matthew Bass's blog entitled Overriding existing Rake tasks . This described a similar situation and I've based my code on his advice. I needed to delete the existing db:migrate task before adding my new one. You can't just call delete task on the Rake::Application class (there's no such method) so Matthew's suggestion was to add a del...