gpt4 book ai didi

ruby-on-rails - 将模块/类中的代码注入(inject)到另一个模块/类中

转载 作者:太空宇宙 更新时间:2023-11-03 16:50:53 24 4
gpt4 key购买 nike

我想知道将代码从一个模块/类注入(inject)另一个模块/类的常见做法。我有:

module MyModule
extend ActiveSupport::Concern

included do
# The has_many association for Article / Post.
has_many :comments

# Here, from MyModule, I would like to "inject" the related belongs_to
# association into Comment where the belongs_to association should be
# 'belongs_to :article' for Article and 'belongs_to :post' for Post.
end

module ClassMethods
# ...
end
end

class Article < ActiveRecord::Base
include MyModule
end

class Post < ActiveRecord::Base
include MyModule
end

class Comment < ActiveRecord::Base
end

要将 belongs_to 关联注入(inject)到 Comment 中,我可以使用 instance_exec 方法,但也许有更聪明的方法。我应该怎么做才能避免代码重复?我应该在 Commentinclude 其他模块,还是将所有相关代码保留在 MyModule 中,然后从那里注入(inject)?在这些情况下如何进行?

最佳答案

当一个模型属于多个其他模型时,您可以使用 polymorphic associations ,你可以使用 class_eval 来包含一个模块:

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

以非多态的方式,你可以像这样定义包含:

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

关于ruby-on-rails - 将模块/类中的代码注入(inject)到另一个模块/类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22352353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com