For Programmers: Free Programming Magazines  


Home > Archive > Ruby > August 2005 > Adding instance methods to class at runtime









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Adding instance methods to class at runtime
Jon A. Lambert

2005-08-29, 7:02 pm

I want to add instance methods to a class at runtine.

$ cat testcmds.rb
module Bar
def hello
puts "hello called"
end
end

class Foo
end

Foo.include(Bar)

Foo.new.hello

$ ruby testcmds.rb
testcmds.rb:10: private method `include' called for Foo:Class
(NoMethodError)

How can I do this?



David A. Black

2005-08-29, 7:02 pm

Hi --

On Tue, 30 Aug 2005, Jon A. Lambert wrote:

> I want to add instance methods to a class at runtine.


There's no other time to do it :-)

> $ cat testcmds.rb
> module Bar
> def hello
> puts "hello called"
> end
> end
>
> class Foo
> end
>
> Foo.include(Bar)


You can reopen the class and do the include:

class Foo
include Bar
end

or you can use send:

Foo.send("include", Bar)


David

--
David A. Black
dblack@wobblini.net


Kirk Haines

2005-08-29, 7:02 pm

On Monday 29 August 2005 2:52 pm, Jon A. Lambert wrote:
> I want to add instance methods to a class at runtine.
>
> $ cat testcmds.rb
> module Bar
> def hello
> puts "hello called"
> end
> end
>
> class Foo
> end
>
> Foo.include(Bar)
>
> Foo.new.hello
>
> $ ruby testcmds.rb
> testcmds.rb:10: private method `include' called for Foo:Class
> (NoMethodError)
>
> How can I do this?


irb(main):013:0* Foo.send(:include, Bar)
=> Foo
irb(main):014:0> Foo.new.hello
hello called


Kirk Haines


Jon A. Lambert

2005-08-29, 7:03 pm

David A. Black wrote:
> or you can use send:
>
> Foo.send("include", Bar)
>


Excellent Thank you.
I think my problem was scope then.
Here's what I be doing and it now works like a charm.

$ cat cmd1/cmd_bar.rb
module Command
def cmd_bar
puts "cmd_bar one called"
end
end

$ cat cmd2/cmd_bar.rb
module Command
def cmd_bar
puts "cmd_bar two called"
end
end

$ cat testcmds.rb

class Foo
end

def load1
cmds = Dir.glob("cmd1/cmd_*.rb")
cmds.each {|c| load(c)}
Foo.send(:include,Command)
end

def load2
cmds = Dir.glob("cmd2/cmd_*.rb")
cmds.each {|c| load(c)}
Foo.send(:include,Command)
end

f = Foo.new

load1
f.cmd_bar

load2
f.cmd_bar

$ ruby testcmds.rb
cmd_bar one called
cmd_bar two called

--
J. Lambert



Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com