require, from within lib, files located under the local path

J

Jean-denis Vauguet

Hi.

Here's an issue I've not been able to solve for some time now.

Let's say I designed a tiny library, following a standard structure:

$ tree
 
J

Jean-denis Vauguet

Ok so here's what I eventually did:

require 'pathname' # I love it :)
module MyLib
def self.extended base #:nodoc:
# the receiver is the extended module or class
@receiver = base

# paths of the receiver file and receiver stuff
@base_path = Pathname.new(File.expand_path($0)).dirname
@stuff_path = @base_path + "mylib_stuff"

# ... do whatever with base and the paths
end

# ...
end

I don't know if this practice of relying on $0 is solid, though.
Any hint?
 
B

Brian Candler

Jean-denis Vauguet said:
I don't know if this practice of relying on $0 is solid, though.

It's very risky:
* on many platforms it's truncated
* the script which the user started running isn't necessarily the file
which is requiring your code

I suggest you look at Kernel#caller instead.

Unfortunately it just gives you strings which you have to parse
yourself, and you'll probably need to grep out all the rubygems-related
paths.

For an example, look in the sinatra gem (lib/sinatra/base.rb,
specifically methods caller_locations and caller_files). Sinatra uses
this to locate the application source code, for reading inline
templates.
 
J

Jean-denis Vauguet

Brian said:
I suggest you look at Kernel#caller instead.

Unfortunately it just gives you strings which you have to parse
yourself, and you'll probably need to grep out all the rubygems-related
paths.

For an example, look in the sinatra gem (lib/sinatra/base.rb,
specifically methods caller_locations and caller_files). Sinatra uses
this to locate the application source code, for reading inline
templates.

Thank you so much :)
 

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,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top