Problem with Object.const_get?

A

anne001

I am trying to use the catapult code.
If I move the FooBar.rb file in the lib directory, Catapult serves the
FooBar code fine.
If I copy the FooBar class in the catapult.rb file, Catapult fails.

Yet the FooBar class is the same in both case, and the code calling
Object.const_get is the same in both case, the only difference is that
when the program reads from file, it runs require cname first.

What could be the problem with Object.const_get when the class is
defined in the same file as the Objec.const_get request?

this is the section of catapult code involved:

def self.new_from_name( class_name )
cname = String.new( class_name.untaint )
obj = nil
begin
obj = Object.const_get( cname ).new()
rescue Exception
begin
require cname
obj = Object.const_get( cname ).new
rescue Exception
raise "Error: Cannot create object #{cname}: #{$!}
Tried loading from \n#{$:.join( "\n")}" unless obj
end
end
obj
end

class FooBar
def run( path )
"<html>This is FooBar!<br/>We have path #{path}</html>"
end
def content_type
"text/html"
end
end
 
A

anne001

I figured it out. This is really an interpreted language! the classes
have to be defined
before the code that uses them. I had added the class at the end of the
file, and apparently Ruby does not look there.

I found this code to see if a class is defined or not
x = []
ObjectSpace.each_object(Class) { |c| x << c }
p x
 
R

Robert Klemme

anne001 said:
I figured it out. This is really an interpreted language! the classes
have to be defined
before the code that uses them. I had added the class at the end of the
file, and apparently Ruby does not look there.

That's true. Files are evaluated top to bottom - class definitions do
not make a difference - they are expressions just like any other
expression. The only difference is BEGIN and END blocks:

15:41:08 [Temp]: ruby <<XXX
BEGIN { puts "begin" }
puts "run"
END { puts "end" }
XXX
begin
run
end
16:54:51 [Temp]: ruby <<XXX
END { puts "end" }
puts "run"
BEGIN { puts "begin" }
XXX
begin
run
end
16:56:01 [Temp]: ruby <<XXX
puts "run"
END { puts "end" }
BEGIN { puts "begin" }
XXX
begin
run
end
16:56:18 [Temp]:
I found this code to see if a class is defined or not
x = []
ObjectSpace.each_object(Class) { |c| x << c }
p x

That's quite inefficient and it will also not cover classes that reside
in files that are not yet loaded. You can as well just do "p
YourClassName" at a point where you expect this class to be defined and
potentially get bitten by the exception - as you experienced. :)

Kind regards

robert
 

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,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top