views:

362

answers:

3

I've always thought this sort of thing ugly:

require File.join(File.dirname(__FILE__), 'hirb/config')

Is there a prettier alternative, maybe one written for Rails?

require_relative 'hirb/config'
require_relative '../another/file'
+6  A: 

You could do

Dir.chdir(File.dirname(__FILE__) do
  require 'hirb/config'
  require '../another/file'
end

Whether or not that's better is a matter of taste, of course.

sepp2k
When code is ugly because of required but consistent cruft (e.g. the `File.join(File.dirname(__FILE__), path)` stuff here), abstract abstract abstract!
Sarah Vessels
I think this one isn't going to work out because __FILE__ is always relative to the file it is defined in, not the file it is called in.
tadman
@tadman: Oh, right. Damn.
sepp2k
+5  A: 

The best approach is probably preparing your load path so you don't need to do all this. It's not especially difficult for your main module or init file to introduce a few other locations.

This is also affected by the RUBYLIB environment variable, as well as the -I command line parameter.

$: << File.expand_path(File.join('..', 'lib'), File.dirname(__FILE__))
tadman
caller[0] means you can abstract
jrhicks
+3  A: 

You can extend the kernel.

module Kernel
    def require_relative(path)
      require File.join(File.dirname(caller[0]), path.to_str)
    end
end
jrhicks
...but where do you require that? ;-)
Mike Woodhouse
Perfect. Thanks.
Mario
And why, exactly, isn't this native to Ruby itself? It's not commonplace?
Mario