如何初始化一个轨宝石里面加协会用户指定车型 [英] how to initialise a rails gem which add associations to models specified by user

查看:169
本文介绍了如何初始化一个轨宝石里面加协会用户指定车型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建一个需要协会添加到用户定义某些型号宝石的过程。

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.

推荐答案

也许你可以看看的的Rails :: Railtie

当我写我的宝石之一,我需要等到我的Rails应用程序的所有车型初始化我的宝石之前加载。我想这也是您的需要。我做了这样的事情:

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

config.after_initialize 回调为我工作得很好!

The config.after_initialize callback worked fine for me!

这篇关于如何初始化一个轨宝石里面加协会用户指定车型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆