Ruby 子类:基于继承包含不同的模块

Dex*_*Dex 3 ruby ruby-on-rails

我有两个类,任务和子任务。子任务与任务几乎没有什么不同,除了一件重要的事情之外,它必须包含不同的模块。

出于我的目的,包含的模块 subtask_module 和 task_module 都具有相同的方法和别名,但一旦包含的模块扩展其方法,它们在内部的功能就会略有不同。对我来说没有办法解决这个问题,因为我正在使用插件。

例如,您在下面的belongs_to任务中看到。belongs_to是从包含的模块扩展而来的,但是它的功能根据我包含的模块而略有不同。

class Subtask < Task
  include subtask_module 
end

class Task
  include task_module

  # methods and aliases both classes use (defined in included file) 
  # but behavior changes based on
  # included file
  belongs_to :template    
end
Run Code Online (Sandbox Code Playgroud)

做这样的事情最好的方法是什么?现在它就像现在一样工作。但它看起来很臃肿,因为任务中会声明一些我不需要的未使用的东西。

什么是最好的方法?

Jos*_*eek 5

您也可以将 Task 转为子类,然后让每个子类继承通用的东西(尽可能使用上面的名称)

class Task
  belongs_to :template    
end

class Subtask1 < Task
  include subtask_file 
end

# this used to be Task, now is Subtask2
class Subtask2 < Task
  include task_file
end
Run Code Online (Sandbox Code Playgroud)

或者,您将共享功能移至其自己的模块中,然后包含该功能,并完全避免超类/子类(我会选择这个)。

module TaskShared
  belongs_to :template    
end

class Task
  include TaskShared
  include task_file
end

class Subtask
  include TaskShared
  include subtask_file 
end
Run Code Online (Sandbox Code Playgroud)

(belongs_to可能会给你带来困难。如果是这样,请尝试将其添加到包含的钩子中)

module TaskShared
  def self.included(klass)
    klass.belongs_to :template
  end
end
Run Code Online (Sandbox Code Playgroud)

请注意,在某些情况下,这会变得棘手,例如从 ActiveRecord::Base 类继承。