简体   繁体   English

:: Base类的优点/缺点(而不是acts_as_foo)

[英]pros/cons of a ::Base class (rather than acts_as_foo)

Rather than an acts_as_foo syntax**, I'm toying with the idea of extending ActiveSensor::Base < ActiveRecord::Base and then extending this base class with all the errors/validations/class methods/whizbangs. 而不是使用acts_as_foo语法**,我想扩展ActiveSensor::Base < ActiveRecord::Base ,然后使用所有错误/验证/类方法/ whizbangs扩展此基类。

Proposed: #active_sensor.rb gem 建议:#active_sensor.rb gem

module ActiveSensor
  include ActiveRecord

  autoload :VERSION, 'active_sensor/version'
  autoload :ActiveSensorError, 'active_sensor/base'
  autoload :Base, 'active_sensor/base'
  autoload :Validations, 'active_sensor/validations'
end

Pros: I think it looks cleaner. 优点:我认为它看起来更干净。 Architecture and class build-up emulates ActiveRecord I have a lot of subclassing going on... want to check whether a component is hardware using :is_a? 架构和类的构建模拟ActiveRecord我正在进行许多子类化工作...要使用:is_a?检查组件是否为硬件:is_a? method. 方法。

Cons: holding an extra inheritance class layer in memory... never used independently not very conventional (only seen 1 other rails plugin do this) 缺点:在内存中保留了一个额外的继承类层...从未独立使用过,不是很常规(仅看到其他1个Rails插件可以这样做)

Any advice? 有什么建议吗? Is creating a new ::Base class just dumb? 创建一个新的:: Base类只是愚蠢的吗? If so, why? 如果是这样,为什么?

** The acts_as_foo pattern is common for Rails gems. ** acts_as_foo模式在Rails gem中很常见。 This class method is added to every AR object, which loads and extends class and instance methods when loading the class. 将该类方法添加到每个AR对象,该对象在加载类时加载并扩展类和实例方法。

I think you've already answered yourself. 我想你已经回答了自己。 Quite simply, if you extend Base then you add the functionality to every Active Record class in your system, whereas if you use acts_as_foo - you can add it only to the models that require it. 很简单,如果扩展Base,则将功能添加到系统中的每个Active Record类,而如果使用acts_as_foo,则只能将其添加到需要它的模型中。

Obviously form this, it's better to use acts_as_foo if you only want the functionality for some of your models... but if you want it in every model, then feel free to extend Base. 显然,如果只需要某些模型的功能,最好使用acts_as_foo ...但是如果要在每个模型中使用它,则可以随时扩展Base。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM