问题
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