0

I am in the process of creating a gem which needs to add associations to some models defined by the user.

I have an initialiser file which can be copied into the app by a rails generator command and this is where the user will specify the models to add the associations to.

BloggyGem.setup do |config|
  config.user = User
  config.post = Post
end

Inside the Gem, I have this specified

 opts = BloggyGem.settings
 opts.user.has_many opts.post.to_s.downcase.pluralize.to_sym, 
                   :class_name => opts.post.model_name

 opts.post.belongs_to opts.user.to_s.downcase.singularize.to_sym,
                      :class_name => opts.user.model_name

My tests are passing in my gem, but rails initialises slightly differently so wanted to be sure of the best way to do it.

Nick
  • 239
  • 3
  • 14

1 Answers1

0

Maybe you can take a look at Rails::Railtie

When I wrote one of mine gems, I needed to wait until all the models in my Rails app were loaded before initializing my gem. I guess it's also your need. I did something like this:

module GemName
  class Railtie < Rails::Railtie

    config.after_initialize do
      class ActiveRecord::Base
        include GemName::ModelAdditions
        globalize
      end
    end
  end
end

The config.after_initialize callback worked fine for me!

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Mathieu Mahé
  • 2,647
  • 3
  • 35
  • 50