tags:

views:

43

answers:

1

Hi guys,

My question is the following:

I have a small Ruby code with different classes in a few files. In one of these file, I instantiate an object of the main class to start the execution.

So this file as to require my other classes.

(subquestion: is it a good way to start a ruby code ?)

But I have a problem when I run the code from an alias: let's say my main code is in DIR1/MyRubyCode.rb and I want to run the code from DIR2/MyRubyCode which is an alias (ln -s) to the .rb file.

Then my requires will fail.

I solved inelegantly the problem by adding the path DIR1 to $LOAD_PATH before the require. But I think there would be much better ways to do it.

Do you have any suggestions about that ?

Thanks !

+2  A: 

If you want to check if a Ruby file is being 'require'ed or executed with 'ruby MyRubyCode.rb', check the __FILE__ constant.

# If the first argument to `ruby` is this file.
if $0 == __FILE__
  # Execute some stuff.
end

As far as the require/$LOAD_PATH issue, you could always use the relative path in the require statement. For example:

# MyRubyCode.rb
require "#{File.dirname(__FILE__)}/foo_class"
require "#{File.dirname(__FILE__)}/bar_module"

Which would include the foo_class.rb and bar_module.rb files in the same directory as MyRubyCode.rb.

Oshuma
Thanks but if I require with File.dirname(__FILE__), when I launch the code using an alias it also tries to include from '.' and I still have the 'no such file to load' error.
Cedric H.
That is correct. You would have to get the target of the symlink (which would go in place of `File.dirname()`). Check out this post for a couple different ways of doing that:http://stackoverflow.com/questions/1237939/ruby-how-do-i-get-the-target-of-a-symlink
Oshuma
Thanks. It works well with `$LOAD_PATH << File.dirname(Pathname.new(File.expand_path(__FILE__)).realpath.to_s).to_s` .
Cedric H.