Ruby prob with File.dirname(__FILE__) and class inherance
I have the parent class in /dir1/test1.rb then i have the child class in /dir2/test2.rb
the test1 class has a method that uses the "File.dirname(FILE)". BUT when i call this method from the test2, that in开发者_开发技巧herent from test1 the dir is the dir1, insted the dir2, where the test2 is.
How to make it work?
It's kind of hacky but if you have a method that is already in every child class, like def initialize
then you can do this from within an instance method in the parent class:
self.class.instance_method(:initialize).source_location[0]
Or from within a class method of the parent class:
self.instance_method(:initialize).source_location[0]
This will return the location of the file where the method is defined (eg. /dir2/test2.rb
).
the use of __FILE__
has to be in test2.rb
It's really that simple. How about this?
class Test2
def self.here
@here ||= File.dirname(__FILE__)
end
end
Then in the method in test1 you call self.here
精彩评论