Ruby developer. CTO. Swimmer. Always trying to write more
Delayed Job is a popular gem for running background tasks on Rails applications. Apartment is another useful gem for switching Postgresql schemas in response to particular subdomains (it means that visiting ibm.myapp.com will automatically switch to the ‘ibm’ schema and select * from user will only return IBM users).
Luckily the Apartment gem has instructions for configuring it to work with DelayedJob. These instructions persist a new
database attribute which is then used to switch schemas inside a DelayedJob hook. Unfortunately, it does require using the
syck YAML parser and whilst this worked for me in development, I couldn’t get it working in production. Also, the default parser in Ruby 1.9.3 is Psych and I’d really rather keep it that way.
Just pass in basic scalar types (integer, strings, etc) and arrays, and use these to search for the correct ActiveRecord. It all works considerably easier this way and is much simpler to understand. To be honest, this seems like good practice anyway and I’d prefer if DelayedJob didn’t try to serialise AR records at all. I still use the DelayedJob hooks provided by Apartment to automatically switch database schemas before and after job invocation though because they are simple and reliable.