Class variable inside block of defining instance method

C

Charles Oliver Nutter

Ruby doesn't scope quite like that normally, but you can do it using
instance_eval and define_method:

def initialize(server1, server2)
@echo = echo = IRC::Client.new(*server1)
@listen = IRC::Client.new(*server2)
@echo.instance_eval do
define_method :message_received do |nick, channel, message, *args|
if channel == "#Pre"
echo.puts("PRIVMSG #{echo.channel} :#{message}")
end
end
end
end

instance_eval has some quirks, and define_method methods are never as
fast as normal methods (since they have full block dispatch
semantics), but this should do what you need.

- Charlie
 
R

Robert Klemme

2010/1/25 Charles Oliver Nutter said:
Ruby doesn't scope quite like that normally, but you can do it using
instance_eval and define_method:

def initialize(server1, server2)
=A0@echo =3D echo =3D IRC::Client.new(*server1)
=A0@listen =3D IRC::Client.new(*server2)
[email protected]_eval do
=A0 =A0define_method :message_received do |nick, channel, message, *args|
=A0 =A0 =A0if channel =3D=3D "#Pre"
=A0 =A0 =A0 =A0echo.puts("PRIVMSG #{echo.channel} :#{message}")
=A0 =A0 =A0end
=A0 =A0end
=A0end
end

instance_eval has some quirks, and define_method methods are never as
fast as normal methods (since they have full block dispatch
semantics), but this should do what you need.

Unlikely, since the method was defined on @listen and not @echo. :)
This is probably a better solution:

def initialize(server1, server2)
@echo =3D IRC::Client.new(*server1)
@listen =3D IRC::Client.new(*server2)

class <<@listen
attr_accessor :echo
end
=09
@listen.echo =3D @echo
=09
def @listen.message_received(nick, channel, message, *args)
if channel =3D=3D "#Pre"
echo.puts("PRIVMSG #{echo.channel} :#{message}")
end
end
end

Kind regards

robert


--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

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,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top