Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails实例模型包含可变条件下的模块_Ruby On Rails_Ruby On Rails 4_Model_Module - Fatal编程技术网

Ruby on rails rails实例模型包含可变条件下的模块

Ruby on rails rails实例模型包含可变条件下的模块,ruby-on-rails,ruby-on-rails-4,model,module,Ruby On Rails,Ruby On Rails 4,Model,Module,我需要知道是否可以将模块包含到实例化模型中 今天起作用的是: 在控制器中 @m = MyModel.create(params) 在模型中 class Doc < ActiveRecord::Base after_save :set_include def set_include if bool self.class.send(:include, Module1) else self.class.send(:include,

我需要知道是否可以将模块包含到实例化模型中

今天起作用的是:

在控制器中

@m = MyModel.create(params)
在模型中

class Doc < ActiveRecord::Base

   after_save :set_include

   def set_include
     if bool
       self.class.send(:include, Module1)
     else
       self.class.send(:include, Module2)
     end
   end

end
类文档
这是可行的,但我担心,
self.class
实际上包含了类模型的模块,而不是实例化模型

class Doc < ActiveRecord::Base

   after_save :set_include

   def set_include
     if bool
       self.class.send(:include, Module1)
     else
       self.class.send(:include, Module2)
     end
   end

end
在这种情况下,这将起作用。 保存对象后,将调用模块方法

但在许多情况下,控制器会调用一些模块方法

我想到了在控制器的动作
之前在一个
中调用方法
set\u include
(在上面)。 但我真的认为这不是个好主意

你知道我怎样才能用一种好的方式做到这一点吗


谢谢

您需要使用实例类(也称为egenklass):


然而,您想要这样做的事实是可疑的,可能会导致灾难。因此,问题是:你真正想在这里实现什么?肯定有更好的方法。对你的直接问题,答案是否定的。您的代码看起来只是在工作,实际上并不是在修改类的实例,而是在修改类本身。因此,它的所有实例都将获得这种“好处”。可能不是你想要的。让我用简单的ruby示例演示:

您可以改为使用实例,如:

应用于您的代码,它将是:

class Doc < ActiveRecord::Base
   after_save :set_include

   def set_include
     if bool
       extend(Module1)
     else
       extend(Module2)
     end
   end
end
类文档

此外,
self
也不是必需的

在imo中没有太多意义,只是包括两个模块并使用其方法。这两个模块作为相同的方法名,这就是为什么。正如我所说,这两个模块的方法名相同,因为旧代码不容易重构,并且在很多地方避免了if和else。但是如果它不能实现,我会找到另一种方法用上面的代码实现它,但它很可能会在将来给你带来很多麻烦。