Episode 2 - class << self
Bharat Ruparel
26 posts
|
Hello David,
Now following the logic that you explained before this to turn this into self.method syntax, I did the following:
But when I run this, I get the following error message: main.rb:3: private method `attr_accessor’ called for Dave:Class (NoMethodError) I am not sure if I understand what is going on here. Why can’t I use the parallel but clearer syntax that you explained before this. By the way, brilliant example of include and extend in ActiveRecord setting. You are a really good teacher. |
Dave Thomas
Administrator
65 posts
|
Two problems: First, attr_accessor is a provate method, and so can’t be called with a receiver. Second, ‘self’ is the current class, so self.attr_accessor (if it worked) would be the same as attr_accessopr, which isn’t what you want. You want attr_accessor to go into the ghost singleton class. Dave |
Bharat Ruparel
26 posts
|
Thanks. I am finding that I have to go back and review the episodes multiple times to get a better understanding of the concepts. Every time I do that, I take a few steps forward, but sometimes, it is going backwards as well. I see that I have to start using the reference section of your book more often. The attr_accessor method is clearly documented as a private instance method there. I use NetBeans for my Ruby and Ruby on Rails work and its debugger is very helpful in steppig through the program code. I add a “watch” on the “self” variable and it is fun to see it change as control moves from line to line. One question I have is when would self become a module in these examples? I see it bounce between the Class names and Object (at the top level). |
Dave Thomas
Administrator
65 posts
|
Try:
|
Bharat Ruparel
26 posts
|
Thanks for the tip: I tried it, and it prints: Bharat Next, to see how it differs when you defined a method in it and inlcude it in a class, I created the following test scenario:
This prints the following: Bharat #<class1:0x27b0384> Next, I tried the following code:
This prints the following result: Bharat When I compare and contrast these results. I am thinking that a module is nothing but a class that cannot be instantiated. Also, a method in a module can be an instance method or a class method depending on whether the module is included in the class or extended. Fundamentally, it is just a grouping of similar behavior that can be shared across different classes. Is that a correct way of approaching it? Bharat |
5 posts, 2 voices
