Joel VanderWerf
5/7/2009 12:41:00 AM
Nigel Hennan wrote:
> Hi,
>
> File.dirname(__FILE__) returns the current folder where the script in,
> How to get it from methods in included modules?
>
> My sample code as below:
>
> helper.rb
> ---------
>
> module Helper
> def your_path
> puts instance_eval { File.expand_path(File.dirname(__FILE__)) } #
> doesn't work
> end
> end
>
> a.rb
> -----
> require 'helper/helper'
>
> class A
> include Helper
> end
>
> A.new.your_path #=> return helper's file path, not class A's
This seems to work:
[~/tmp] cat helper/helper.rb
module Helper
def self.included m
file = caller[1][/(.*):\d+$/, 1] ## a bit fragile, maybe
dir = File.expand_path(File.dirname(file))
m.const_set "YourPath", dir
end
def your_path
self.class::YourPath
end
end
[~/tmp] cat a.rb
require 'helper/helper'
class A
include Helper
end
p A.new.your_path
[~/tmp] ruby a.rb
"/home/vjoel/tmp"
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407