Search code examples
ruby-on-railsactiverecordcrondelayed-jobobservers

Monitor database table for external changes from within Rails application


I'm integrating some non-rails-model tables in my Rails application. Everything works out very nicely, the way I set up the model is:

class Change < ActiveRecord::Base
  establish_connection(ActiveRecord::Base.configurations["otherdb_#{RAILS_ENV}"])
  set_table_name  "change"
end

This way I can use the Change model for all existing records with find etc.

Now I'd like to run some sort of notification, when a record is added to the table. Since the model never gets created via Change.new and Change.save using ActiveRecord::Observer is not an option.

Is there any way I can get some of my Rails code to be executed, whenever a new record is added? I looked at delayed_job but can't quite get my head around, how to set that up. I imagine it evolves around a cron-job, that selects all rows that where created since the job last ran and then calls the respective Rails code for each row.

Update Currently looking at Javan's Whenever, looks like it can solve the 'run rails code from cron part'.


Solution

  • This is what I finally did: Use Whenever, because it integrates nicely with Capistrano and showed me how to run Rails code from within cron. My missing peace was basically

    script/runner -e production 'ChangeObserver.recentchanges'
    

    which is now run every 5 minutes. The recentchanges reads the last looked-at ID from a tmp-file, pulls all new Change records which have a higher ID than that and runs the normal observer code for each record (and saves the highest looked-at ID to the tmp-file, of course).