草庐IT

ruby-on-rails - rails : dynamically define class method based on parent class name within module/concern

coder 2025-05-24 原文

我想根据包含此 Mixin 的类名在 Mixin 中动态生成一个类方法。

这是我当前的代码:

module MyModule  
  extend ActiveSupport::Concern  

  # def some_methods  
  #   ...  
  # end  

  module ClassMethods  

    # Here is where I'm stuck...
    define_method "#{self.name.downcase}_status" do  
      # do something...  
    end  

  end  
end  

class MyClass < ActiveRecord::Base  
  include MyModule  
end  

# What I'm trying to achieve:
MyClass.myclass_status

但这给了我以下方法名称:

MyClass.mymodule::classmethods_status  

在方法定义中获取基类名称是可行的(self、self.name...),但我无法使其适用于方法名称...

到目前为止,我已经尝试过了

define_method "#{self}"
define_method "#{self.name"
define_method "#{self.class}"
define_method "#{self.class.name}"
define_method "#{self.model_name}"
define_method "#{self.parent.name}"

但这些似乎都不起作用:/

有什么方法可以检索基类名称(不确定如何调用包含我的模块的类)。我已经为这个问题苦苦挣扎了几个小时,我似乎无法找到一个干净的解决方案:(

谢谢!

最佳答案

你不能那样做——此时还不知道哪个类(或哪些类)包含该模块。

如果您定义了一个self.included 方法,每次包含该模块时都会调用该方法,并且执行包含的操作将作为参数传递。或者,由于您使用的是 AS::Concern,您可以这样做

included do 
  #code here is executed in the context of the including class
end

关于ruby-on-rails - rails : dynamically define class method based on parent class name within module/concern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14706820/

有关ruby-on-rails - rails : dynamically define class method based on parent class name within module/concern的更多相关文章

随机推荐