about delegator

U

uncutstone

I have a question about ruby's delegate mechanism.

Ruby supports automatic delegate by inherited from DelegateClass or
SimpleDelegator. But what if I want a class can inherit from some other
class but still support automatic delegate. Since ruby doesn't support
multi inheritance, it seems no way.

Why automatic delegate cannot be supported by module instead of class?

Thanks in advance.
 
U

uncutstone

I rethink the problem and realize module cannot be used to implement
automatic delegate, because automatic delegate is based on automatic
call super.

I already get a solution if i want inherit from other class and also
need automatic delegation. I list the code below:

class Song
attr_reader :duration, :artist, :name
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
end
def bye
puts "goodbye: #{name}, #{artist}, #{duration}"
end
end

class SongDelegator
def initialize(aSong)
@aSong= aSong
end
def method_missing(methId)
str = methId.id2name
@aSong.send str
end
end

aSong = Song.new('f', 'i', 1200)
aSongDelegator = SongDelegator.new(aSong)
aSongDelegator.bye

It is easy to do. The core is redefine method_missing.
 

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

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,273
Latest member
DamonShoem

Latest Threads

Top