When a model belongs to more than one other model you can use polymorphic associations, and you can use class_eval to include a module:
module MyModule
extend ActiveSupport::Concern
included do
has_many :comments, as: postable
Comment.class_eval do
include Commentable
end
end
Module Commentable
extend ActiveSupport::Concern
included do
belongs_to :postable, polymorphic: true
end
def ping
p 'pong'
end
end
end
class Article < ActiveRecord::Base
include MyModule
end
class Post < ActiveRecord::Base
include MyModule
end
class Comment < ActiveRecord::Base
end
In a non-polymorphic way you can define included like this:
def self.included(base)
Comment.class_eval do
belongs_to base.name.underscore # Will result in belongs_to :article and belongs_to :post in this case
end
end