module - Understanding the Ruby mixin's proxy class mechanism -
i refering follwing article, paragaph "pitfall #1": http://definingterms.com/2013/03/23/pitfalls-of-ruby-mixins/
i've got following setup, changed form of 1 used in article:
module emailreporter def send_report #sending report ... puts self.class end end class person end class employee < person include emailreporter end
as understand, when include emailreporter in employee, methods not pasted it, anonymous proxy class created , put inheritance chain above employee , under person.
when call employee.new.send_report, not in scope of employee, in scope of proxy class. thus, not have access constants or class variables of employee, have access instance variables.
questions:
if run employee.new.send_report, output "employee", not "employee__proxy_class". why that? shouldn't "self" refer proxy class?
the article suggest proxy class delegates method calls module emailreport. of course cannot call instance methods on it. whom proxy class delegate calls to?
thanks trying answer question!
i think fundamental problem in understanding value of self
. it's helpful add code tells self
@ different points of code. let's begin simple example:
class dad def hi puts "self in dad#hi = #{self}" end end class son < dad end son = son.new #=> #<son:0x007fc1f2966b88> son.methods.include?(:hi) #=> true son.hi # self in dad#hi = #<son:0x007fc1f2966b88>
just because:
son.method(:hi).owner #=> dad
does not mean self
changed when hi
invoked on self
. let's include mixin:
module helper def hi puts "self in helper#hi = #{self}" end end son.include helper son.hi # self in helper#hi = #<son:0x007fc1f29551d0> son.method(:hi).owner #=> helper
i think understand why helper#hi
invoked here rather dad#hi
.
does answer first question? don't understand second question, perhaps can answer you've been enlightened on self
. if not, please clarify #2 (with edit question).
Comments
Post a Comment