gpt4 book ai didi

ruby-on-rails - 插件关系设计

转载 作者:太空宇宙 更新时间:2023-11-03 16:26:22 24 4
gpt4 key购买 nike

我想为应用程序构建插件系统

Site.first.plugins #=> [ 
#<Plugin id: 1, site_id: 1, plugin_type: "Plugin::GoogleAnalityc", created_at: "2014-06-06 08:34:19", updated_at: "2014-06-06 08:34:19">,
#<Plugin id: 1, site_id: 1, plugin_type: "Plugin::GoogleAdwords", created_at: "2014-06-06 08:34:19", updated_at: "2014-06-06 08:34:19">
] # and onther classes with its own implementations

所以我有这样的模型关系:

class Site < ActiveRecord::Base
has_many :plugins
end

class Plugin < ActiveRecord::Base
belongs_to :site
# there's starts my problem
# I need that class will be defined dynamicly
# to achive turned on plugin
has_many :plugin_types, class_name: self.plugin_type
end

class Plugin::GoogleAnalityc < ActiveRecord::Base
belongs_to :plugin
end

所以我会

Site.first.plugins # list of all turned on plugins
Site.first.plugins.first.plygin_types # => [
#<Plugin::GoogleAnalitycs id: 1, plugin_id: 1, key: 'counterID', value: '1234567', created_at: "2014-06-06 08:34:19", updated_at: "2014-06-06 08:34:19">,
#<Plugin::GoogleAnalitycs id: 1, plugin_id: 1, key: 'targetID', value: '87654321', created_at: "2014-06-06 08:34:19", updated_at: "2014-06-06 08:34:19">
]

如果我\你不知道明天需要什么插件,你能建议插件系统的设计实现吗?

最佳答案

从代码的外观来看,最好使用 STI (Single Table Inheritance) :

#app/models/site.rb
Class Site < ActiveRecord::Base
has_and_belongs_to_many :plugins #-> will return plugins, which you can filter by type & call custom methods for
end

#need join table - plugins_sites
plugin_id | site_id

#app/models/plugin.rb
class Plugin < ActiveRecord::Base
#fields - id | type | your | attributes | created_at | updated_at
has_and_belongs_to_many :sites
end

#app/models/plugins/google_analytics.rb
Class GoogleAnalytics < Plugin
# ... custom stuff here
end

#app/models/plugins/wordpress.rb
Class Wordpress < Plugin
# ... custom stuff here
end

这将允许您调用:

@site = Site.find 1
@site.plugins.each do |plugin|
plugin.type #=> "GoogleAnalytics"
end

关于ruby-on-rails - 插件关系设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24077830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com