This project is archived and is in readonly mode.
model_name is not an instance method but a Class method
-
Vijay Dev
- Assigned user set to Xavier Noria
Hmm.. It is a method defined in the ActiveModel::Naming module which is extended in ActiveRecord to make the method available as a class method for the ActiveRecord classes. I assume the documentation shows it as a 'public instance method' of the module, which is right.
-
Javix
As far as I understand, in any OO language, public instance method are called on an instance of a class, so in this case it is supposed to work like that:
@@@code user = User.new
user.model_nameas no matter which instance method. But in reality it looks more like a public class method which are defined and can be called as follows:class User
def self.model_name
#bla-bla endend
User.model_name
And this is exactly what is happening. Or it is me who don't understand the difference preperly between instance methods and class methods. If it's the case, so correct me. If not, I'd modified the documentation so that it would be more clear. Regards -
Xavier Noria
- State changed from new to wontfix
- Importance changed from to Low
You're right, it is an instance method of the module it belongs to, which is ActiveModel::Naming.
Now, as Vijay explains, that does not mean it is an instance method in classes that use the module. In particular, if the class uses extend, it becomes a class method in that class. It is still an instance method in the module.
To be even more exact, model_name is indeed an instance method, but an instance method of the singleton class of ActiveRecord::Base, which is the class where ActiveModel::Naming is being included (that's what extend does). But anyway we understand what we mean by class methods.
Unfortunately, documentation tools as of today are not smart enough to be able to list model_name as a class method of ActiveRecord::Base. I have a plan to try to get better docs in that sense, perhaps someday.
-
Vijay Dev
In Ruby, modules and classes behave just the same (with a few differences of course). The method model_name is a public instance of the Naming module. You are right when you say that it looks more like a public class method. It is one for the User class in your eg. That's because the Naming module is extended by ActiveRecord::Base.
When a module is extended in a class, all the instance methods of the module become accessible as class methods in that class. By contrast, when a module is included in a class, all the instance methods of the module become accessible as instance methods in that class.
-
Vijay Dev
@Xavier: Opened up the page and kept on typing, I missed your update :)
-
Javix
OK, thak you guys, it's clear for me now.