6

How do you correctly initialize Redmine plugins that need to instantiate a model (read a database record) defined in the plugin itself?

For example, I have a plugin my_redmine_plugin which comes with a model MyPluginModel. On plugin initialization, I'd like to

  • read a record of MyPluginModel from DB
  • run some initialization code with the record

Given the following code:

require 'redmine'

Redmine::Plugin.register :my_redmine_plugin do
  name 'My Redmine Plugin'

  # ...    
end

Rails.configuration.to_prepare do
  m = MyPluginModel.find(1)
  run_some_init_code(m)
end

It looks like to_prepare runs before the migration:

$ bundle exec rake redmine:plugins:migrate NAME=my_redmine_plugin

`table_structure': Could not find table 'mypluginmodel' (ActiveRecord::StatementInvalid)
...

When I comment out the to_prepare block during migration, everything works fine. Is there any way to detect the migration process?

Michael Krupp
  • 2,042
  • 3
  • 19
  • 36

1 Answers1

0

Try using after_initialize instead of to_prepare. This is not a Redmine problem - Rails initialization process has different hooks that are run at different times during startup. See the API docs for further information.

Update: thinking about it this might still not help with the migration - you could just rescue from that error in your hook.

jkraemer
  • 357
  • 1
  • 6
  • When simply catching the Exception, I'd still have to find a way to detect if it was caused during migration (ignore it) or production (exit with error). Which brings us back to my initial question: How to detect migration? – Michael Krupp Jan 08 '16 at 12:23
  • 1
    @MichaelKrupp see https://stackoverflow.com/questions/1858230/how-to-detect-whether-my-rails-is-running-in-migration-or-not-in-environment-rb – bbozo Feb 04 '16 at 07:58
  • @bbozo thank you! Now I at least have a workaround. Though I could imagine running into all sorts of funny edge-cases with this, as some other people already commented on the site you linked. – Michael Krupp Feb 04 '16 at 14:12