在ActiveRecord关联之前或之后包含Ruby模块

时间:2014-07-08 18:43:53

标签: ruby-on-rails ruby activerecord

我尝试根据Rails模型的关联来定义fetcher方法:

module Fetchers
  extend ActiveSupport::Concern

  included do
    reflect_on_all_associations.each do |association|
      define_method "fetch_#{association.name}" do
        # do something
      end
    end
  end
end

并将此模块包含在模型中:

class User < ActiveRecord::Base
  include Fetchers

  belongs_to :team
  has_many :projects
end

这样我就可以获得User#fetch_teamUser#fetch_projects等方法。

但是对于模块列出模型的关联,它需要包含在它们之后,这会导致像这样的尴尬代码:

class User < ActiveRecord::Base
  include CoolStuff
  include CommonMethods

  belongs_to :team
  has_many :projects

  include Fetchers

  scope :something, ->{ where(something: true) }

  after_save :do_this

  ...
end

有没有办法让Fetchers模块在生成方法之前先等待类关联定义?

0 个答案:

没有答案