How to correctly instantiate a model in plugin init.rb?
Asked Answered
G

1

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?

Graaf answered 6/1, 2016 at 14:1 Comment(0)
P
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.

Pallmall answered 7/1, 2016 at 0:6 Comment(3)
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?Graaf
@MichaelKrupp see #1858730Neilla
@Neilla 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.Graaf

© 2022 - 2024 — McMap. All rights reserved.