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
Nigel Hennan wrote:
module 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”