简体   繁体   中英

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:

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:

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 ).

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. 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 .

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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