Author's Bio: Anton Mamaenko

Sunday, March 28, 2010

Ruby dynamic file reload

Ruby allows to load, and reload code from the files by using load(...) function. This is very useful, when working in interactive console mode. You can reload libraries, classes, etc.
For example, You have a class, and a module declared in file 'myLib.rb'

module MyLib
class MyClass
def Ping
puts "I am Bob"
end
end
end

Then you open the irb, and type:

load 'myLib.rb'
include MyLib
t=MyClass.new
t.Ping

this will obviousely result in "I am Bob" message output on the screen, but wait, you wanted the MyClass instances to be pinged as "Alice"! So you open the myLib.rb, without exiting irb, and change the Ping method to

...
def Ping
puts "I am Alice"
end
...

then all you need to reload this module - is to type in irb:
load 'myLib.rb'

Quite obvious so far, but the cool part is that You Don't need to create another instance of the MyClass. Your changed method is changed in the existing instance of MyClass, so to output the new Ping result you type:

load 'myLib.rb'
t.Ping

That's it! Same You can do with attributes, and their accessors. Note, however, that you Cannot remove methods, i.e. if you edit your MyClass to be something like:

module MyLib
class MyClass
def SuperPing
puts "I am much better now..."
end
end
end

and then reload the library, its old instance will still have the old Ping method, so you have both Ping, and SuperPing now. Even if if instantiated again

t2=MyClass.new

the new instance will still have the Ping method. To fix it you will need to restart Ruby.

No comments:

Post a Comment

Search This Blog