how to initialise a rails gem which add associations to models specified by user

醉酒当歌 提交于 2019-12-25 02:21:22

问题


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.


回答1:


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!



来源:https://stackoverflow.com/questions/8719141/how-to-initialise-a-rails-gem-which-add-associations-to-models-specified-by-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!