Skip to content
Steve Kenworthy edited this page Jan 3, 2014 · 1 revision

Lazy Load Hooks

Commit e58e3faf introduces the notion of lazy load hooks as provided by ActiveSupport.

Read here for more information on how to use them

If you are developing a plugin and need to register some code to run after a particular model has loaded you can register a load hook.

E.g. Fat Free CRM uses this feature to load the settings file after the Setting class is invoked.

ActiveSupport.on_load(:fat_free_crm_setting) do

  setting_files = [FatFreeCRM.root.join("config", "settings.default.yml")]
  setting_files << Rails.root.join("config", "settings.yml") unless Rails.env == 'test'
  setting_files.each do |settings_file|
    Setting.load_settings_from_yaml(settings_file) if File.exist?(settings_file)
  end

end

(Taken from https://github.com/fatfreecrm/fat_free_crm/blob/master/lib/fat_free_crm/load_settings.rb)

The last line of https://github.com/fatfreecrm/fat_free_crm/blob/master/app/models/setting.rb#L118 class activates the hook.

ActiveSupport.run_load_hooks(:fat_free_crm_setting, self)

This can also be used in plugins. Say, for example, you want to register your own custom field. You can configure your engine.rb as such:

config.to_prepare do
  ActiveSupport.on_load(:fat_free_crm_field) do
    self.register(:as => 'example', :klass => 'CustomFieldExample', :type => 'string')
  end
end

This will be triggered when the 'fat_free_crm_field' hook is run. This happens immediately after the Field class is loaded.

Hooks have been placed on all models in the app/models directory. Take a look at the last line of each specific model for the name of the hook to register. They follow the "fat_free_crm_classname" convention.