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

标签 ruby-on-rails ruby design-patterns

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

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/

相关文章:

ruby - 在 Cucumber 中添加 Sinatra 助手

java - 如何在 JPA 域模型中实现状态设计模式

ruby-on-rails - Ruby on Rails 配置 - Plaid Gem

ruby - 如何使用正则表达式拆分字符串以在 +、-、*、/符号之间拆分?

design-patterns - 应用程序框架是反模式吗?

c++ - 数据结构优化

ruby-on-rails - 是否可以在 Rails Controller 之外使用 ActiveModel::Serializers?

ruby-on-rails - 如何从hidden_​​field_tag通过link_to参数传递值(Rails)

ruby-on-rails - 迭代开发 View 的最佳实践

javascript - 在 Javascript 中解析 Rails 数组时出现 "Unexpected token &"