简体   繁体   English

如何从模块中获取扩展模块的类的名称?

[英]How do I get the name of a class extending a module, from the module?

I have the following model in my /app/models folder: 我的/ app / models文件夹中有以下模型:

class MyModel < ActiveRecord::Base
  require "dashboard"
  extend Dashboard

# ...
end

I then have in my /lib folder a file named dashboard.rb, which has the following code: 然后,我在/ lib文件夹中有一个名为dashboard.rb的文件,其中包含以下代码:

module Dashboard
  def self.my_function
    # --> My question pertains to what I need to put here...
  end
end

I'd like to write a line of code in MyModel::Dashboard.my_function so that it will return the name of my model (in this case MyModel ). 我想在MyModel::Dashboard.my_function编写一行代码,以便它返回我的模型的名称(在本例中为MyModel )。

I did find some information on Get class name from a module and https://gist.github.com/1014971 , but it seems like when my model inherits from ActiveRecord::Base , it's different. 我确实从模块https://gist.github.com/1014971中找到了有关Get类名的一些信息,但似乎当我的模型继承自ActiveRecord::Base ,它是不同的。 The latter of these articles supposedly explains this, but I'm at a loss. 据说这些文章的后者解释了这一点,但我不知所措。

I tried some permutations with superclass.name from within Dashboard.my_function , but I just get Dashboard or Module returned, and not MyModel . 我尝试使用Dashboard.my_function superclass.name一些排列,但我只是返回了DashboardModule ,而不是MyModel

Anyone who can shed light on how to do this would be greatly appreciated. 任何能够阐明如何做到这一点的人将不胜感激。

By using extend , you are making the module methods class methods of your MyModel class. 通过使用extend ,您将创建MyModel类的模块方法类方法。 Try this: 尝试这个:

module Dashboard
  def my_function
    self.name
  end
end


class MyModel < ActiveRecord::Base
  require "dashboard"
  extend Dashboard

  # ...
end

And rather than calling it as MyModel::Dashboard.my_function you would just call it directly on your model class -> MyModel.my_function would return MyModel 而不是将其称为MyModel::Dashboard.my_function您只需在模型类上直接调用它 - > MyModel.my_function将返回MyModel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM