Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class name from a module

How I can get from a module the Class name of the class the module is included ?

module ActMethods
  def some_method(*attr_names)
    cls = self.class # this doesn't work 
  end
end

How I can get into the cls variable the name of the class to with this module is loaded ?

like image 433
astropanic Avatar asked Nov 28 '09 14:11

astropanic


People also ask

How to get class name in class method?

Use type() to get class name in Python One way of finding the Python class name of an object is by using the built-in type() method. The type() method returns the data type of the object passed to it as an argument. Still, to get the class name as string, you need to access the special built-in __name__ variable.


1 Answers

self.class does get you the class of the object the method is called on. Assuming the module was included into a class, this either is the class that included the module or a subclass thereof. If you really just want the name, you can use self.class.name instead.

If you extended a class with the module and you want to get that class, you can just do cls = self (or cls = name if you want the name of the class as a string).

If none of the above helps, you should clarify what you want.

like image 147
sepp2k Avatar answered Sep 17 '22 00:09

sepp2k