Note: This was the best title I could think of that wouldn't make this question seem like a dup. Please feel free to edit if it does not capture the point of the question
So I've been reading Advanced Rails and I had a question that wasn't fully answered by these posts:
- When to use `self.foo` instead of `foo` in Ruby methods
- In Ruby. How do I refer to the class from within class << self definition?
- Why use "self" to access ActiveRecord/Rails model properties?
In my understanding, within a class definition, self
refers to the object referenced by the pointer klass
, so for the example of an eigenclass:
class A
class << self
def to.s
"Woot"
end
end
end
is the exact same as:
class << A
def to.s
"Woot"
end
end
This is because as you open up the class, ruby is creating a Class:A (virtual)
class and assigning A
's klass
pointer to it. To my understanding this means that within the context of this class definition self == A
My question is (assuming my understanding as I've described it above is accurate) why then in an ActiveRecord::Base subclass in Rails does the use of self
seem to be merely a disambiguation of the instance
and not the class
itself?
For example, if I have a class: A < ActiveRecord::Base
with an attribute name
, I cannot call A.name = "blah"
outside the class definition. However, I CAN use ( and indeed MUST use ) self in assignment within the class definition like so: self.name = "blah"
.
If the use of self
in Ruby refers to the Class
object and not the instance
, why does this work in ActiveRecord and how does Rails make the distinction?