proposal: class<<obj to invoke extend_object

  • Thread starter Simon Strandgaard
  • Start date
S

Simon Strandgaard

'obj.extend' and 'class<<obj' are close cousins..
However there is a difference.. 'class<<obj' doesn't
invoke #extend_object, and #extended. To me it feels
inconsistent that there is no way to execute code on the
point when the extension occurs.

I propose that 'class<<obj' invokes #extend_object and #extended.



Lets make a comparison.. first I present some code
which works using #extend.
Next I present some code which doesn't work.. but
which should work.

server> ruby a.rb
hello
server> cat a.rb
module M
def self.extended(parent)
parent.init_m
end
def init_m
@str = "hello"
end
def hello
puts @str
end
end
class C
end
c = C.new
c.extend(M)
c.hello
server>



The next part doesn't work.. (thus the proposal)

server> cat b.rb
class C
end
c = C.new

class << c
def self.extended(parent) # proposal: invoke me ;-)
parent.init_m
end
def init_m
@str = "hello"
end
def hello
puts @str
end
end

c.hello
server> ruby b.rb
b.rb:13: warning: instance variable @str not initialized
nil
server>
 
Y

Yukihiro Matsumoto

Hi,

In message "proposal: class<<obj to invoke extend_object"

|'obj.extend' and 'class<<obj' are close cousins..
|However there is a difference.. 'class<<obj' doesn't
|invoke #extend_object, and #extended. To me it feels
|inconsistent that there is no way to execute code on the
|point when the extension occurs.

'obj.extend' add a module to the inheritance graph (per object base),
whereas 'class <<obj' add methods and attributes to the existing
singleton class. Virtually, singleton class always exists for each
object, never added, never extended.

matz.
 
S

Simon Strandgaard

In message "proposal: class<<obj to invoke extend_object"

|'obj.extend' and 'class<<obj' are close cousins..
|However there is a difference.. 'class<<obj' doesn't
|invoke #extend_object, and #extended. To me it feels
|inconsistent that there is no way to execute code on the
|point when the extension occurs.

'obj.extend' add a module to the inheritance graph (per object base),
whereas 'class <<obj' add methods and attributes to the existing
singleton class. Virtually, singleton class always exists for each
object, never added, never extended.

I don't get this.. (thanks+sorry matz).

I had the impression that they didn't differ much.
Is there anyone which can explain this to me?


Thanks in advance
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top