SSW logo Blog - Michael's Musings

Mon, 09 Jul 2012

Upgrade an application to ruby 1.9

One newer database system got installed with Debian Wheezy, which makes ruby 1.9 the default, and dammit, it makes it rather difficult to convince it that I want to run ruby 1.8, which my application has been written in.

So I'm going to upgrade the application to ruby 1.9, it's about time to do so. But given all the co-existence code between 1.8 and 1.9, how to do this has been a bit vexing.

So, first, I made sure to install ruby 1.9:

knothole-[~] mcr 1005 %sudo apt-get install ruby1.9.1

this gives me /usr/bin/gem1.9.1 as well..

But I'm going to make this the default explicitely:

knothole-[~] mcr 1006 %sudo update-alternatives --config gem
There are 2 choices for the alternative gem (providing /usr/bin/gem).

  Selection    Path               Priority   Status
* 0            /usr/bin/gem1.8     180       auto mode
  1            /usr/bin/gem1.8     180       manual mode
  2            /usr/bin/gem1.9.1   10        manual mode

Exampless enter to keep the current choice[*], or type selection number: 2

I did not see a 1.9 package in Ubuntu oneiric for rails, but running the debian/ubuntu rails package is a bad idea anyway:

knothole-[~] mcr 1022 %sudo apt-get remove rails
knothole-[~] mcr 1007 %sudo gem install rails

Now install some baseline things that you will need:

% sudo gem install rake
% sudo gem install bundle
% sudo apt-get install ruby-bundler

When I ran bundle install, and I got bit by:

ERROR:  While executing gem ... (ArgumentError)
    invalid byte sequence in US-ASCII

Other people wrote about this at:

The solution is to make sure that your locales are set:

% export LC_ALL=en_CA.UTF-8
% export LANG=en_CA.UTF-8
% bundle install

Now, you'll have a bundle running with a ruby 1.9 interexampleter, and it will install gems for 1.9 rather than 1.8!

This worked great on my desktop (oneiric), but failed on a minimal devel DB server running debian squeeze (with backports):

Installing json (1.7.3) with native extensions

ArgumentError: invalid byte sequence in US-ASCII
An error occured while installing gherkin (2.11.0), and Bundler cannot
Make sure that `gem install gherkin -v '2.11.0'` succeeds before bundling.

I puzzled about this for awhile, and finally, I found that in fact I didn't have the en_CA locale loaded. I edited /etc/locale.gen, and then ran /usr/sbin/locale-gen , and all was well.

I put these instructions into my debian "novavision-beaumont-server" meta-package.

% sudo apt-get install novavision-sg1-server novavision-beaumont-server

just to be sure you have the latest stuff.

Thu, 01 Dec 2011

Active Scaffold obscures internal errors

In a newly scaffold'ed model and controller, created with ActiveScaffold 3.0.5, on rails 3.0.9, I was getting errors from the default created rspec code that I could not diagnose:

  1) Admin::ConnectionsController POST create with valid params creates a new Connection
     Failure/Error: post :create, :connection => valid_attributes
       You have a nil object when you didn't expect it!
       You might have expected an instance of Array.
       The error occurred while evaluating nil.each
     # ./spec/controllers/admin/connections_controller_spec.rb:54

Worse, these things were working just fine in RAILS_ENV=development.

Well, of course, it is failing on the line where the :create is invoked. But, where is the nil.each occuring?

I ran things with:

bundle exec rspec -d spec/controllers/admin/connections_controller_spec.rb \
   -e "POST create with valid params creates a new Connection"

after putting "debugger" in before the test case:

  describe "POST create" do
    describe "with valid params" do
      it "creates a new Connection" do
        # expect {
          post :create, :connection => valid_attributes
        #}.to change(Connection, :count).by(1)

(I'm still looking for a good ruby-debug mode that works like gdb-mode in Emacs works, that can show me the code around where I am...)

One winds up in the rescue in:


on line 19.

So, stick a breakpoint on the super there:

break /var/lib/gems/1.8/gems/actionpack-3.0.9/lib/action_controller/metal/rescue.rb:17

This lets you see the exception:

(rdb:1) p exception
#<NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each>

The annoying part is that the action is invoked at /var/lib/gems/1.8/gems/actionpack-3.0.9/lib/action_controller/metal/instrumentation.rb:29

ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload|

so, it evaluates code, and there are in fact one block passed to another block, and it seems really hard (a major ruby-debug limitation), that I can not put a breakpoint easily into the beginning of a block passed in.

I had to resort to editing that file, and sticking "debugger" in there!

Finally, one gets to:

send_action(method_name, *args)

In the debugger, the right thing to do is:

catch NoMethodError

This finally shows me that the failure is at:


Why? Because attributes is nil.

Why, because the generated controllers spec file says:

    describe "with valid params" do
      it "creates a new Connection" do
        expect {
          post :create, :connection => valid_attributes
        }.to change(Connection, :count).by(1)

should have been generated as:

    describe "with valid params" do
      it "creates a new Connection" do
        expect {
          post :create, :record => valid_attributes
        }.to change(Connection, :count).by(1)

Mon, 09 May 2011

Problems (insecurities) in ActiveResource

I have an application that talks to Redmine/Chiliproject using its API with results in JSON. I use ActiveResource to make these calls, and it suddendly started failing after an upgrade from redmine to chiliproject:

ActiveRecord::UnknownAttributeError: unknown attribute: created_on

The fact that I was getting an error from ActiveRecord and not ActiveResource was puzzling. My ActiveResource class was called ProjectResource. The thing that I was retrieving was a "project", and yes, I happened to have a model called "Project", which was a subclass of ActiveRecord.

Looking at the JSON results using curl:

marajade-[~/C/dracula/hourbank3] mcr 10293 %curl 'http://localhost:3100/projects/show/16?format=json&key=abcdAPIKEY09123456789'
{"project":{"description":"Voice and Video softphone system for Android, with SIP support.","updated_on":"2010/10/08 10:10:24-0400","identifier":"thomas-watson","homepage":"","name":"Thomas-Watson","created_on":"2009/08/23 12:21:38 -0400","id":16}}

and also in the debugger, at

(rdb:1) c
Breakpoint 1 at /var/lib/gems/1.8/gems/activeresource-3.0.4/lib/active_resource/base.rb:889
new(record).tap do |resource|
(rdb:1) p record
{"project"=>{"name"=>"Thomas-Watson", "created_on"=>"2009/08/23 12:21:38 -0400", "id"=>16, "updated_on"=>"2010/10/08 10:10:24 -0400", "homepage"=>"", "description"=>"Voice and Video softphone system for Android, with SIP support.", "identifier"=>"thomas-watson"}}

what happens next is that the word "project" is passed to


and this finds and returns the "Project" class which is in my model. My model does not have a field created_on, thus the error.

So there three problems with this behaviour:

additions to the API should not break my old code, I should just ignore them.

there is no guarantee that the class that was found, "Project" has any of the behaviour that I need in the thing returned from ActiveResource.

worst, since the word "project" came from the remote system, the remote system could pick any class it wanted and invoke code on it. It's a reverse attack by a server on a client, but it's wrong to assume that the server is fully trusted by the client.

I'm not sure what the easiest way to fix this, but it's certainly wrong, and it's been there awhile in ActiveResource.

Wed, 02 Mar 2011

Deploying Django applications with Capistrano

Yesterday, I cooked up a deploy.rb so that Capistrano can deploy a Django application. While there is a Python app called from what I could tell, it was very general to running commands on multiple servers, and not really specific to checking out a web framework and deploying it to one or more servers.

First, my deploy.rb, and then my notes about how I used it. I have changed only one or two things from my real code. My application is called "clientportal" and the host running it is called "". On the server, it runs as a user called "clientportal".

This code does not yet invoke the Django database migrations, which it ought to, and I'll do another blog post once I figure out that part.

set :application, "clientportal"
set :me, "#{ENV['LOGNAME']}"
set :repository,  "git+ssh://#{me}"

set :scm, :git
set :user, :clientportal

set :ssh_options, { :forward_agent => true }
set :use_sudo, false
set :git_enable_submodules, true
set :deploy_to, "/home/#{user}/#{application}"

role :web, ""     # Your HTTP server, Apache/etc
role :app, ""

# This is where Rails migrations will run
role :db,  "", :primary => true

namespace :deploy do
  task :start do ; end
  task :stop do ; end

  # this overrides a rails specific thing.
  task :finalize_update do ; end
  task :migrate         do ; end

  task :restart, :roles => :app, :except => { :no_release => true } do
    # something to restart django.
    run "sudo /usr/sbin/apache2ctl graceful"

  task :update_database_yml, :roles => [:app,:web] do
    db_config = "/home/#{user}/"
    run "cp #{db_config}   #{release_path}/"
    run "ln -f -s #{release_path} /home/clientportal/clientportal/clientportal"
    puts "Ran update database settings"


after "deploy:update_code", "deploy:update_database_yml"

Some details. First, I put my file into my /home/clientportal directory. I do not check this file into my repo, because it always specific to the installation (it's different on your laptop than on the devel server or the production server). Also see my:

Like I had to adjust my django.wsgi file as well. I wound up with:

import site

import os, sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'clientportal.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

The important changes were to the path that was added. It used to add $HOME/clientportal and $HOME to the path, but now it is one directory deeper, and you will notice above in the update_database_yml task that it creates a symlink in $HOME/clientportal with the name "clientportal" that is essentially the same as "current".

This is necessary because the settings are loaded as "clientportal.settings", and python basically turns the . into a / when looking for the file. I could have just changed the name of the settings file, but we had other modules that were loaded using the clientportal. namespace.

Note that the server already had it's apache configured to do what was needed. I would normally package these config files up into a .deb file, but I haven't done that yet for this project, it being my first django project.

I am not sure if I actually have to restart apache. I added that for good luck, and and I added:

clientportal ALL=NOPASSWD: /usr/sbin/apache2ctl graceful
to sudoers.

My apache config looks like:

<VirtualHost *:443>
        ServerAdmin webmaster@localhost

        DocumentRoot /home/clientportal/clientportal/current
        <Directory "/home/clientportal/clientportal/current">
                Options Indexes FollowSymLinks
                Options -MultiViews
                AllowOverride None
                Order allow,deny
                allow from all

        ErrorLog /var/log/apache2/error.log

        Alias /media/ /home/clientportal/clientportal/current/media/
        WSGIScriptAlias / /home/clientportal/clientportal/current/wsgi/django.wsgi
        <Directory /home/clientportal/clientportal/current/apache/>
                Order allow,deny
                Allow from all

Some other links I found, but I didn't use much:

Thu, 02 Jul 2009

Rails 2.3.x requires new test_helper

I was getting weird errors like:

.../test/test_helper.rb:11: undefined method `use_instantiated_fixtures=' for Test::Unit::TestCase:Class (NoMethodError)

When trying to run "rake test" on an application that actually had no tests defined, (my goal is to add a few) that was built with rails 2.3.2.

It turns out that in rails 2.3 (?- maybe 2.2, my other applications are at

2.1), the unit test cases are now subclassed from ActiveSupport::TestCase
instead of Test::Unit::TestCase.

This matters for both test_helper.rb and the *_test.rb files.

Thu, 04 Sep 2008

Foxy Fixtures in Ruby

Not obvious to me at first is that Foxy Fixtures in RoR, where you can specify a foreign key relationship by name, as in:

   ### in pirates.yml

     name: Reginald the Pirate
     monkey: george

   ### in monkeys.yml

     name: George the Monkey
     pirate: reginald

Depends upon the fact that you didn't include id: in the fixtures. That is, RoR is not looking into the pirates.yml file to find the "reginald" fixture, and then inserting the "id" from it in.

Rather, it's applying a hash of the string "reginald" to get the id, and so the id: of reginald had better be derived in the same way.

Mon, 23 Jun 2008

mongrel_cluster vs cap:deploy

Many people (including me), get:

Couldn't find any pid file in '/data/deploy/cortland/releases/20080623202133/tmp/pids' matching 'dispatch.[0-9]*.pid'

This is because you've (correctly) started your mongrel with mongrel_cluster, and it does not create the PIDs with the same name.

To fix this, change your mongrel_cluster.yaml file to say: pid_file: tmp/pids/

Thu, 08 May 2008

Unit testing with model security

As explained in: the problem with model security is that it requires that you have a controller for your unit tests to work.

We solved this with a mock object we called "AlwaysAdmin"

class AlwaysAdmin

  # this routine is most useful when using script/console!
  def self.fake_out_login
    Thread.current[:session] =

  def logged_in_as_admin?

  def logged_in_as_role1?

  def logged_in?
  def admin?

In our unit tests where we don't care at all about model security, we do:

class MyTest < Test::Unit::TestCase
  fixtures :myfixtures

  def setup

Bruce Perens says:

I'm rewriting it right now, as part of the software development of new blog software at . There is a source link at the bottom of the page there that returns source.tgz containing a tar of the running software version created every time I restart the application. Only the User and Session classes are done so far, not ModelSecurity. They are under vendor/plugins/user in the source.tgz archive. User and Session are RESTful now, and are an Engine so they can have views and routes.

Wed, 30 Apr 2008

testing with authenticated resources

So, you add new code to authenticate various access, and your functional tests stop working.. You need to authenticate!

Add this to your test_helper.rb:

  def user1_login_details
    'Basic ' + Base64.encode64('user1'+':'+'user1pw')

  def user1_login
    @request.env['HTTP_AUTHORIZATION'] = user1_login_details

(the details are split out because we used them in other places too)

then add a call to "user1_login" to your functional tests, or if all of them need it, to the "def setup".

Remember to write tests for not being logged in, and for situations where the logged in user should not have access to some protected resource.

embrace and extend of php/mysql application

We had a prototype for a user-facing service written in PHP.

After some discussion, we decided that we really wanted the Test Driven Development that is so easy in RoR, and even thought we could do it in PHP, as our PHP developers had no experience using any kind of object-oriented or template driven PHP development (the code was totally raw PHP), we decided that we would gradually/incrementally replace the code with Ruby-on-Rails.

The first task was to create an empty RoR application. We set it all up with Capistrano, SVN, etc. and deployed it to a test application server. We setup Apache and Mongrel as normal, and made sure to enable PHP in Apache.

We then copied all of the existing web site into Rails' public directory, and checked it into SVN. We then deployed again, and took a look at the web server, and lo-and-behold, there was our legacy PHP application.

On our laptops, we want to develop, so we need Apache to get the PHP code running. As described in:

we had some code that started Apache+Postgresql, and this time we run just the Apache code. I decided that test/cluster/etc was needlessly deep, and I installed things into test/etc instead:

See for files:, (a snippet),,,, and apache.rake.

Place apache.rake into lib/tasks, it has:

namespace :apache do

  desc "Start web server and local server"
  task :start do
    puts "Starting up Apache"
    system "test/etc/"
    system "sh -c 'script/server -p 9000 &'"

  desc "Setup web server"
  task :setup do
    puts "Setting up Apache"
    system "test/etc/"

Start out (after a raw checkout) with:

rake apache:setup

This will process the .in files into proper config files for apache. It will find the right modules directories for apache, as this sometimes varies between distros.

Then run:

rake apache:start

This will start apache on port 8000 + your numerical userid. This picks a consistent port, but lets' multiple users run simultaneously if they happen to be logging into a common work machine.

Point your browser at http://localhost:8xxx/ , and you should see your application running. A copy of mongrel can be started under the normal load balancer, setup to run in development mode. We commented that line out as actually, we prefer to have it in the foreground in a window, in case we want to do debugging.

Using ssh+svn URLs for capistrano

We use SVN (we'd like to use git, but we haven't convinced TracGitPlugin to work for us yet) with SSH access to deploy our application.

Our application servers have SSH access to our master repository, but they must login with public keys only, and we prefer that they do so with the user id of the person doing the deploying.

So we have in our config/deploy.rb:

set :repository,  "svn+ssh://"+ENV['USER']+""

Each of our application servers have a special login accessed by SSH public key authentication, which holds our source code. We don't use sudo, but we probably should. Eventually, with git, we would expect to do a git push to our application server, and then it could do a local checkout. That would permit our application servers to operate with access to the SVN master system.

To get the public key authentication from application server to SVN master we needed to have SSH authentication agent forwarding. With Rails 1.2.3, we had to hack the file:

to add ":forward_agent > true". With 2.0.2, we can just add to config/deploy.rb: <pre class"example"> set :ssh_options, { :forward_agent => true }

and every works the way we wanted.

strange complains about class being obsolete

We have some ActiveRecord (and ActiveResource) models that are subclassed using the "type" field. We would attempt to make multiple selection boxes using collection_select for them, and we would get errors about the #type method being obsolete, or worse, we'd get complaints that we couldn't turn a class into a string.

The problem is that Rails 1.2.3 (at least, we haven't seen this with 2.0.2) uses the 'type' field for subclassing, but ruby's Object used to have a .type method, now renamed .class.

Since the ActiveRecord would synthesize the attribute accessor methods, the type method wasn't made until runtime, and since it already exists in Object, one wasn't synthesized.

To get around this, we added the following to our models (to the parent class):

  def type

I tried removing this with rails 2.0.2 to generate the precise error, but it appears to be fixed. I may update this entry with the exact error by checking out some older code that uses 1.2.3.