开发者

How to include a module in all of Rails project's ActiveRecord models?

开发者 https://www.devze.com 2022-12-31 15:05 出处:网络
I want to include this module in every ActiveRe开发者_如何转开发cord model in my Rails app, without dropping include NotificationResourceableTraits in each file. Is there a way?

I want to include this module in every ActiveRe开发者_如何转开发cord model in my Rails app, without dropping include NotificationResourceableTraits in each file. Is there a way?

module NotificationResourceableTraits
  def self.included(base)
    base.has_many :notification_resources, :as => :notification_resourceable
    base.has_many :notifications, :through => :notification_resources
  end
end


I've tackled this problem just recently. Take a look at my Gist: http://gist.github.com/404298

You could simply do this:

ModelDiscovery.valid_active_record_classes.each do |model|
  model.include YourMixinModule
end

Explanation

  1. Get list of all files in 'app/models'
  2. Convert filenames to CamelCase
  3. Constantize all of them
  4. Check if the tables exist (if you want)
0

精彩评论

暂无评论...
验证码 换一张
取 消